将从服务器接收的位图添加到android中的图像gridview

时间:2014-07-07 06:55:42

标签: android imageview base64 android-gridview android-bitmap

我有一个android代码,它以json数据的形式从服务器接收图像as base64字符串。代码如下。收到图像后,我必须将图像解码为位图。之后我必须在图像gridview中显示这些图像。这怎么能实现?请帮我。提前谢谢。

package com.example.mygallery;

//skipping the import section
public class Gallery extends Activity 
{

    int refresh=0;
    Bitmap decodedByte;
    GridView gridView;
    String username,password,count1,status;
    int count;
    ArrayList<String>imagearraylist;
    ProgressDialog pd;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        gridView = (GridView) findViewById(R.id.grid_view);
        SharedPreferences sp=getSharedPreferences("My_login", MODE_PRIVATE);
        username=sp.getString("username", "");
        password=sp.getString("password", "");
        new serverconnection().execute();


    }

    public class serverconnection extends AsyncTask<Void, String, Void>
    {

        @Override
        protected Void doInBackground(Void... params) 
        {
            // TODO Auto-generated method stub

            try
            {
                String link="http://tonyjoseph.site90.com/sendimage.php"; 
                String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");  
                URL url = new URL(link);
                URLConnection conn = url.openConnection(); 
                conn.setDoOutput(true); 
                OutputStreamWriter wr = new OutputStreamWriter (conn.getOutputStream()); 
                wr.write( data );
                wr.flush();
                BufferedReader reader = new BufferedReader (new InputStreamReader(conn.getInputStream())); 
                StringBuilder sb=new StringBuilder();
                String line = null; // Read Server Response 
                while((line = reader.readLine()) != null) 
                { 
                    sb.append(line);
                    break;
                }
                String status=sb.toString();
                JSONObject jsonResponse1;

                try 
                {

                    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                    jsonResponse1 = new JSONObject(status);

                    /***** Returns the value mapped by name if it exists and is a JSONArray. Returns null otherwise.*******/
                    JSONArray jsonMainNode=jsonResponse1.optJSONArray("Android");


                    /*********** Process each JSON Node ************/
                    int lengthJsonArr = jsonMainNode.length();

                    Log.d("Json Array Length",String.valueOf(lengthJsonArr));


                    for(int j1=0;j1<lengthJsonArr;j1++)
                    {
                        Context mContext;
                        /****** Get Object for each JSON node.***********/
                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(j1);

                        /******* Fetch node values **********/
                        String index=jsonChildNode.optString("index").toString();
                        String imagename=jsonChildNode.optString("imagename").toString();

                        //Here I get the images from server as string one after another
                        byte[] decodedString = Base64.decode(imagename, Base64.DEFAULT);
                        decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

                        // At this stage I will be getting a list of bitmapsfrom the server which is converted from the received json
                        // i need to display these bitmaps into a image grid view ie display the images as a grid
                        // how can this be acheived??


                    }

                }
                catch(Exception ex)
                {
                    System.out.print(ex);
                }

            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) 
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Toast.makeText(Gallery.this, "Loading complete", Toast.LENGTH_LONG).show();
            pd.dismiss();

        }
        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd=new ProgressDialog(Gallery.this);
            pd.setTitle("Loading images..");
            pd.setMessage("Please wait");
            pd.setCancelable(false);
            pd.show();
        }


    }


}

1 个答案:

答案 0 :(得分:1)

在该阶段,使用runOnUiThread将收到的位图放在网格中#39;但是,如果您不首先保存或缓存所有收到的位图,则网格将通过UI更新将其丢失。通知数据集更改后,实际placing in the grid将由getView()次调用完成。

实际上你根本不需要runOnUiThread。只需在doInBackGround中将所有图像保存到特定文件夹即可。然后在onPostExecute中执行notifyDataSetChanged。 listview知道从该文件夹中检索。