如何从android中的json url填充我的gridview?

时间:2014-01-16 07:34:39

标签: android android-gridview

我想用图片填充网格视图。图像存储在MySql数据库中。我用PHP编写了一个服务器端脚本,用于选择所需的图像并将响应转换为json。

现在如何将这些图像加载到gridview中?

有许多相关问题,但我无法找到合适的解决方案。我也提到了Universal Image Loader,这个例子很好,但是有什么简单的方法吗?

我使用this SO question作为参考,我从网址获取的JSON代码为: -

public String getJSONUrl(String strUrl) throws IOException {
    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();

}

有人可以指导我吗?

更新我的代码。

我的主要活动:

JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;

String strUrl = "http://192.168.0.215/data/test_image_thumb.php";
/*
 * static String RANK = "rank"; 
 * static String COUNTRY = "country"; static
 * String POPULATION = "population";
 */

static String FLAG = "image";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     new DownloadJSON().execute();
}

private class DownloadJSON extends AsyncTask<Void,Void,Void>{


    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        /*Creating a progress dialog*/
        mProgressDialog = new ProgressDialog(MainActivity.this);

        /*Set progress title*/
        mProgressDialog.setTitle("Image Gallery");

        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);

        // Show progressdialog
        mProgressDialog.show();

    }


    @Override
    protected Void doInBackground(Void...params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        //data = downloadUrl(strUrl);
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions.getJSONfromURL("http://192.168.0.215/data/test_image_thumb.php");

        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("products");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                /*map.put("rank", jsonobject.getString("rank"));
                map.put("country", jsonobject.getString("country"));
                map.put("population", jsonobject.getString("population"));*/
                map.put("flag", jsonobject.getString("image"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        // Locate the GridView in main.xml
        gridview = (GridView) findViewById(R.id.gridView1);
        // Pass the results into GridViewAdapter.java
        adapter = new GridViewAdapter(MainActivity.this, arraylist);
        // Set the adapter to the gridview
        gridview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }

}

和Json编码代码是......

try {

            result = downloadUrl(url);

            jArray = new JSONObject(result);

        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return jArray;
    }


    private static String downloadUrl(String strUrl) throws IOException {

        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);

                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                    sb.append(line);
                }

                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }

我按照这个答案中的参考。问题是我没有在我的日志中遇到错误,但也没有在网格视图中填充所需的图像!

有人可以纠正我......

0 个答案:

没有答案