我正在尝试从网址加载图片并设置为gridview,当我滚动屏幕图像更改时。我是android的初学者。我不知道我的代码中有什么问题。 这是我的代码..
public class Photos extends Activity {
public static final String TAG_IMAGE_NAME = "image_name";
public static final String TAG_IMAGE_THUMB_NAME = "image_thumb_name";
public static String URL = "http://...../..../..../mainAPI.php";
ArrayList<HashMap<String, String>> photoList;
String responseData = null;
static GridView gridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photos);
gridView = (GridView)findViewById(R.id.gridView);
photoList = new ArrayList<HashMap<String,String>>();
new AsyncData().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImage.class);
// passing array index
i.putExtra("ImageName", TAG_IMAGE_NAME);
startActivity(i);
}
});
}
class AsyncData extends AsyncTask<String, Void, Void> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Photos.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("rquest","{\"method\":\"photogallery\",\"body\":[{}]}"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
responseData = EntityUtils.toString(resEntity);
try {
JSONArray data = new JSONArray(responseData);
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = data.getJSONObject(i);
String photoName = c.getString(TAG_IMAGE_NAME);
String imageThumbName = c.getString(TAG_IMAGE_THUMB_NAME);
map.put(TAG_IMAGE_NAME, photoName);
map.put(TAG_IMAGE_THUMB_NAME, imageThumbName);
photoList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
gridView.setAdapter(new PhotosAdapter(Photos.this, R.layout.photo_row, photoList));
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
PhgotosAdapter Class
public class PhotosAdapter extends ArrayAdapter<HashMap<String, String>>{
Context context;
String uri;
Bitmap bitmap;
ArrayList<HashMap<String, String>> myList;
HashMap<String, String> myData;
int layout;
public PhotosAdapter(Context context, int textViewResourceId, List<HashMap<String, String>> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.myList = (ArrayList<HashMap<String, String>>) objects;
this.layout = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layout, parent, false);
myData = myList.get(position);
ImageView image = (ImageView)row.findViewById(R.id.imagePhoto);
try{
ImageDownloadTask task = new ImageDownloadTask(image);
task.execute();
uri = "" + myData.get(Photos.TAG_IMAGE_THUMB_NAME).replace(" ", "%20");
image.setImageBitmap(bitmap);
image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return row;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class ImageDownloadTask extends AsyncTask<Void, Integer, Bitmap> {
private ImageView mView;
ProgressDialog pDialog;
ImageDownloadTask(ImageView view){
mView = view;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
bitmap = getBitmapFromURL(uri);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
mView.setImageBitmap(result);
}
}
}
我不知道它有什么问题,请帮助我并给出一些解决方案。
答案 0 :(得分:0)
ImageLoader imageLoader;
imageLoader=new ImageLoader(context.getApplicationContext());
imageLoader.DisplayImage(urlname, imageViewname);
try it
答案 1 :(得分:0)
答案 2 :(得分:0)
这是我试过的代码..图像正在显示..您可以根据需要自定义网格视图。您只需将以下代码复制并粘贴到您的活动中即可尝试..
public class act extends Activity { static String uri1="https://i3.ytimg.com/vi/bQaWsVQSLdY/default.jpg"; static String uri2="https://i4.ytimg.com/vi/cJQCniWQdno/mqdefault.jpg"; static String uri3="https://i1.ytimg.com/vi/D8dA4pE5hEY/mqdefault.jpg"; public static String[] urls={uri1,uri2,uri3}; public Bitmap bitmap; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView grd=(GridView)findViewById(R.id.gridView1); grd.setAdapter(new ImageAdapter(this)); grd.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent,View v,int pos,long id) { Toast.makeText(getBaseContext(),"pic"+(pos+1)+"select ",Toast.LENGTH_SHORT).show(); } }); } public class ImageAdapter extends BaseAdapter { private Context context; private int itemBackground; ImageAdapter(Context c) { context=c; TypedArray a=obtainStyledAttributes(R.styleable.Gallery1); itemBackground=a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground,0); a.recycle(); } public int getCount() { return urls.length; } public Object getItem(int pos) { return pos; } public long getItemId(int pos) { return pos; } public View getView(int pos,View cv,ViewGroup vg) { Bitmap bitmap= DownloadImage( urls[pos] ); ImageView imageview=new ImageView(context); imageview.setImageBitmap(bitmap); return cv; } private Bitmap DownloadImage(String URL) { final String URL1=URL; new Thread() { public void run() { InputStream in = null; Message msg = Message.obtain(); msg.what = 1; try { in = OpenHttpConnection(URL1); Bitmap bitmap = BitmapFactory.decodeStream(in); Bundle b = new Bundle(); b.putParcelable("bitmap", bitmap); msg.setData(b); in.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }.start(); return bitmap; } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try{ HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } } }