我是android新手。我试图实现一个Asnyc任务,通过解析从服务器返回的json,一次下载一组5个图像。 界面上有一个下一个按钮,用于移动图像视图中的第二个3 4图像。
目前的代码工作正常,但我认为如果一次下载所有5组图像,效率会更高。
当我点击下一个按钮时,如果图像尚未下载,那么是否可能会显示动画gif或加载圈?
您能告诉我下载应该如何,以及如何实现此加载效果。
Main_activty
public class MainActivity extends Activity {
public static String[] name = new String[5];
public static String[] pic = new String[5];
int z = 1;
public static int zimgload ;
String ab;
// public static Bitmap btm;
public static Bitmap[] btm = new Bitmap[5];
public static ImageView imageview;
public static TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
zimgload = 0;
textView = (TextView) findViewById(R.id.textView1);
imageview = (ImageView) findViewById(R.id.imageView1);
load();
textView.setText(name[0]);
//imageview.setImageBitmap(btm[0]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void next(View v) throws Exception {
if (z<5){
textView.setText(name[z]);
imageview.setImageBitmap(btm[z]);
z++;
}
else
{z=1;
zimgload = 0;
load();
textView.setText(name[0]);
imageview.setImageBitmap(btm[0]);
}
}
void load(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
try {
Jsonfromserver jsondata = new Jsonfromserver();
String result = jsondata.getdata();
JSONArray jArray = new JSONArray(result);
name = new String[jArray.length()];
pic = new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
name[i] = oneObject.getString("name");
small[i] = oneObject.getString("small");
}
new ImageDownloader().execute(small[0]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return downloadBitmap(param[0]);
}
@Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
// simpleWaitDialog =
// ProgressDialog.show(ImageDownladerActivity.this,"Wait",
// "Downloading Image");
}
@Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called"+zimgload);
//ImageView imageview = (ImageView) findViewById(R.id.imageView1);
if (zimgload==0)
{imageview.setImageBitmap(result);}
if (zimgload<5)
{
btm[zimgload] = result;
zimgload++;
if (zimgload!=5)
{new ImageDownloader().execute(small[zimgload]); }
Log.i("noiw", "in if"+zimgload);
}
else{
Log.i("else", "ooooooo"+zimgload);
zimgload=1;
}
//imageview.setImageBitmap(btm);
// simpleWaitDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
// forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
// check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that
// android understands
final Bitmap bitmap = BitmapFactory
.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for
// IOException
getRequest.abort();
Log.e("ImageDownloader",
"Something went wrong while retrieving bitmap from "
+ url + e.toString());
}
return null;
}
}
}
Jsonformserver类
public class Jsonfromserver {
public String getdata(){
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.xxx.com/api/randomimage.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default i beleive
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
}
catch (Exception e){e.printStackTrace();
}
return result;
}}
答案 0 :(得分:0)
延迟加载图像变得非常复杂。总有一些改进。
最好的现成解决方案,我鼓励您在推出自己的解决方案之前尝试
https://github.com/nostra13/Android-Universal-Image-Loader
它仍然不完美,即使我在使用上述库后已经使用了自定义解决方案,但它确实接近大多数应用程序需求。