0

我是安卓新手。我试图通过解析从服务器返回的 json 来实现一个 Asnyc 任务,该任务一次下载一组 5 个图像。界面上有一个下一步按钮,用于替换图像视图中的 2nd 3 4 图像。

  1. 当前代码工作正常,但我认为如果一次下载所有 5 组图像,它可以提高效率。

  2. 是否有可能当我单击下一步按钮时,如果图像尚未下载,则显示动画 gif 或加载圆圈?

能否请您告诉我应该如何下载,以及如何实现这种加载效果。

主要活动

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;

}}
4

1 回答 1

0

延迟加载图像很快就会变得非常复杂。总有需要改进的地方。

我鼓励您在推出自己的产品之前尝试的最佳现成解决方案是

https://github.com/nostra13/Android-Universal-Image-Loader

它仍然不完美,即使我在使用上述库后使用了自定义解决方案,但对于大多数应用程序的需求来说它肯定是接近的。

于 2013-04-30T06:21:00.643 回答