Помогите с загрузкой изображений на андроид
сделал по примеру загрузку с сервера через listview но приложение отказывается загружать изображение по нажатию.
package com.myapp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private ListView lstView;
private ImageAdapter imageAdapter;
private Handler handler = new Handler();;
ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ProgressBar
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setClipToPadding(false);
imageAdapter = new ImageAdapter(getApplicationContext());
lstView.setAdapter(imageAdapter);
// OnClick
lstView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
startDownload(position);
}
});
new LoadContentFromServer().execute();
}
//Download
public void startDownload(final int position) {
Runnable runnable = new Runnable() {
int Status = 0;
public void run() {
String urlDownload = MyArrList.get(position).get("ImagePathFull").toString();
int count = 0;
try {
URL url = new URL(urlDownload);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
// Get File Name from URL
String fileName = urlDownload.substring(urlDownload.lastIndexOf('/')+1, urlDownload.length() );
OutputStream output = new FileOutputStream("/mnt/sdcard/mydata/"+fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
Status = (int)((total*100)/lenghtOfFile);
output.write(data, 0, count);
// Update ProgressBar
handler.post(new Runnable() {
public void run() {
updateStatus(position,Status);
}
});
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
}
};
new Thread(runnable).start();
}
private void updateStatus(int index,int Status){
View v = lstView.getChildAt(index - lstView.getFirstVisiblePosition());
// Update ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setProgress(Status);
}
class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {
protected void onPreExecute() {
super.onPreExecute();
setProgressBarIndeterminateVisibility(true);
}
@Override
protected Object doInBackground(Object... params) {
/** JSON from URL
* [
* {"ImageID":"1","ImageName":"Image 1","ImagePath_Thumbnail":"http://www.thaicreate.com/android/img1_thum.jpg" ,"ImagePath_FullPhoto":"http://www.thaicreate.com/android/img1_full.jpg"},
* {"ImageID":"2","ImageName":"Image 2","ImagePath_Thumbnail":"http://www.thaicreate.com/android/img2_thum.jpg" ,"ImagePath_FullPhoto":"http://www.thaicreate.com/android/img2_full.jpg"},
* {"ImageID":"3","ImageName":"Image 3","ImagePath_Thumbnail":"http://www.thaicreate.com/android/img3_thum.jpg" ,"ImagePath_FullPhoto":"http://www.thaicreate.com/android/img3_full.jpg"},
* {"ImageID":"4","ImageName":"Image 4","ImagePath_Thumbnail":"http://www.thaicreate.com/android/img4_thum.jpg" ,"ImagePath_FullPhoto":"http://www.thaicreate.com/android/img4_full.jpg"},
* {"ImageID":"5","ImageName":"Image 5","ImagePath_Thumbnail":"http://www.thaicreate.com/android/img5_thum.jpg" ,"ImagePath_FullPhoto":"http://www.thaicreate.com/android/img5_full.jpg"},
* {"ImageID":"6","ImageName":"Image 6","ImagePath_Thumbnail":"http://www.thaicreate.com/android/img6_thum.jpg" ,"ImagePath_FullPhoto":"http://www.thaicreate.com/android/img6_full.jpg"}
* ]
*/
String url = "http://www.thaicreate.com/android/getJSON.php";
JSONArray data;
try {
data = new JSONArray(getJSONUrl(url));
MyArrList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("ImageID", (String)c.getString("ImageID"));
map.put("ImageName", (String)c.getString("ImageName"));
// Thumbnail Get ImageBitmap To Object
map.put("ImagePathThum", (String)c.getString("ImagePath_Thumbnail"));
map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("ImagePath_Thumbnail")));
// Full (for View Popup)
map.put("ImagePathFull", (String)c.getString("ImagePath_FullPhoto"));
MyArrList.add(map);
publishProgress(i);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void onProgressUpdate(Integer... progress) {
imageAdapter.notifyDataSetChanged();
}
@Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context context) {
mContext = context;
}
public int getCount() {
return MyArrList.size();
}
public Object getItem(int position) {
return MyArrList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColImage
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height = 80;
imageView.getLayoutParams().width = 80;
imageView.setPadding(10, 10, 10, 10);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
try
{
imageView.setImageBitmap((Bitmap)MyArrList.get(position).get("ImageThumBitmap"));
} catch (Exception e) {
// When Error
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
// ColImgID
TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImgID);
txtImgID.setPadding(10, 0, 0, 0);
txtImgID.setText("ID : " + MyArrList.get(position).get("ImageID").toString());
// ColImgName
TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgName);
txtPicName.setPadding(10, 0, 0, 0);
txtPicName.setText("Name : " + MyArrList.get(position).get("ImageName").toString());
// progressBar
ProgressBar progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
progress.setPadding(10, 0, 10, 0);
return convertView;
}
}
/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
/***** Get Image Resource from URL (End) *****/
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM images WHERE 1 ";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($objConnect);
echo json_encode($resultArray);
?>
Источник: Stack Overflow на русском