Skip to content Skip to sidebar Skip to footer

Error Getting Images Into Listview From Server Using Json

i am not getting my listview images from server...it gives me only Launcher images but not the image from server... here is my submenu activity: public class SubMenu extends Act

Solution 1:

You need to use like this:

JSONArray response = JsonFunctions
                    .getJSONfromURL("http://cloud.gr....../broccoli/menu_typeitem.php");

Because the structure of response from server is a JSONArray([]) not a JSONObject({}). That is the starting element is [] not {}.

Add this below method in JsonFunctions class and call this method:

publicstaticJSONArraygetJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URLtry {
            HttpClient httpclient = newDefaultHttpClient();
            HttpPost httppost = newHttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to stringtry {
            BufferedReader reader = newBufferedReader(newInputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = newStringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = newJSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }

I changed your code, please use it:

publicclassSubMenuextendsActivity {
        // Declare VariablesJSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapter adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        staticStringRANK = "id";
        staticStringCOUNTRY = "name";

        staticStringFLAG = "image";

        @OverridepublicvoidonCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xmlsetContentView(R.layout.activity_sub_menu);
            // Execute DownloadJSON AsyncTasknewDownloadJSON().execute();
        }

        // DownloadJSON AsyncTaskprivateclassDownloadJSONextendsAsyncTask<Void, Void, Void> {

            // @Override//  protected void onPreExecute() {//  super.onPreExecute();// Create a progressdialog//   mProgressDialog = new ProgressDialog(SubMenu.this);// Set progressdialog title//   mProgressDialog.setTitle("Categories of Main categories.....");// Set progressdialog message//  mProgressDialog.setMessage("Loading...");//  mProgressDialog.setIndeterminate(false);// Show progressdialog//  mProgressDialog.show();// }@OverrideprotectedVoiddoInBackground(Void... params) {
                // Create an array
                arraylist = newArrayList<HashMap<String, String>>();
                // Retrieve JSON Objects from the given URL address
                jsonarray = JsonFunctions
                        .getJSONfromURL("http://cloud.gr....../broccoli/menu_typeitem.php");

                try {
                    // Locate the array name in JSON//                    jsonarray = jsonobject.getJSONArray("main_menu_items");for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = newHashMap<String, String>();

                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("id", jsonobject.getString("id"));
                        map.put("name", jsonobject.getString("name"));

                        map.put("image", jsonobject.getString("image"));
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                returnnull;
            }

            @OverrideprotectedvoidonPostExecute(Void args) {
                // Locate the listview in listview_main.xml
                listview = (ListView) findViewById(R.id.list1);
                // Pass the results into ListViewAdapter.java
                adapter = newListViewAdapter(SubMenu.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
    }

As there is no key named "main_menu_items", I commented out that code.

Solution 2:

You are getting response as JSONArray so you

JSONArray jsonArray = JsonFunctions.getJSONfromURL("http://cloud.gr....../broccoli/menu_typeitem.php");

Now you can access jsonArray like:

for (int i = 0; i < jsonarray.length(); i++) {
   HashMap<String, String> map = new HashMap<String, String>();

   jsonobject = jsonarray.getJSONObject(i);
   // Retrive JSON Objectsmap.put("id", jsonobject.getString("id"));
   map.put("name", jsonobject.getString("name"));
   map.put("image", jsonobject.getString("image"));
   // Set the JSON Objects into the array
   arraylist.add(map);
}

May it will help you. Thank you.

Solution 3:

JSONArray jsonarray = JSONfunctions.getJSONfromURL(jsonStr);//to get an array

for (int i = 0; i < jsonarray.length(); i++) {
  try {
        JSONObject jsonobject = jsonarray.getJSONObject(i);
        enter other parsing code here..
      }catch (JSONException e) {
        e.printStackTrace();
      } 
}

you can use this snippet for parsing

Solution 4:

You had conflicts between JSONObject and JSONArray in both class. Here you go!

SubMenu.class

// Declare Variables// JSONObject jsonarray;JSONArray jsonarray;
        ListView listview;
        //ListViewAdapter adapter;ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        staticStringRANK = "id";
        staticStringCOUNTRY = "name";

        staticStringFLAG = "image";


        @OverridepublicvoidonCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xmlsetContentView(R.layout.solver_activity);
            // Execute DownloadJSON AsyncTasknewDownloadJSON().execute();
        }

        // DownloadJSON AsyncTaskprivateclassDownloadJSONextendsAsyncTask<Void, Void, Void> {

            // @Override//  protected void onPreExecute() {//  super.onPreExecute();// Create a progressdialog//   mProgressDialog = new ProgressDialog(SubMenu.this);// Set progressdialog title//   mProgressDialog.setTitle("Categories of Main categories.....");// Set progressdialog message//  mProgressDialog.setMessage("Loading...");//  mProgressDialog.setIndeterminate(false);// Show progressdialog//  mProgressDialog.show();// }@OverrideprotectedVoiddoInBackground(Void... params) {
                // Create an array
                arraylist = newArrayList<HashMap<String, String>>();
                // Retrieve JSON Objects from the given URL address
                jsonarray = JsonFunctions
                        .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php");

                try {
                     for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = newHashMap<String, String>();
                        JSONObject jsonobject;
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("id", jsonobject.getString("id"));
                        map.put("name", jsonobject.getString("name"));

                        map.put("image", jsonobject.getString("image"));
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                         Log.e(TAG, "doInBackground: "+ i );
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                returnnull;
            }

            @OverrideprotectedvoidonPostExecute(Void args) {
                // Locate the listview in listview_main.xml
                listview = (ListView) findViewById(R.id.list1);
                // Pass the results into ListViewAdapter.java
                adapter = newListViewAdapter(SubMenu.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }

JsonFunction.class

publicclassJsonFunctions {

    publicstaticJSONArraygetJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URLtry {
            HttpClient httpclient = newDefaultHttpClient();
            HttpPost httppost = newHttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to stringtry {
            BufferedReader reader = newBufferedReader(newInputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = newStringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = newJSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

Solution 5:

You can do like this

ArrayList<HashMap<String, String>> arraylist;
privateclassDownloadJSONextendsAsyncTask<Void, Void, Void> {

    @OverrideprotectedVoiddoInBackground(Void... params) {

            try {
                arraylist = newArrayList<HashMap<String, String>>();
                HttpHandler sh = newHttpHandler();

                // Making a request to url and getting responseString jsonStr = sh.makeServiceCall("http://cloud.granddubai.com/broccoli/menu_typeitem.php");

                Log.e(TAG, "JsonString = " + jsonStr);

                JSONArray jsonObject = newJSONArray(jsonStr);

                for (int i = 0; i< jsonObject.length(); i++){
                    JSONObject job = jsonObject.getJSONObject(i);
                    Log.i(TAG, "Id = "+ job.getString("id"));

                HashMap<String, String> map = newHashMap<String, String>();

                // Retrive JSON Objects
                map.put("id", job.getString("id"));
                map.put("name", job.getString("name"));

                map.put("image", job.getString("image"));
                // Set the JSON Objects into the array
                arraylist.add(map);

                }

            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            returnnull;
        }

        @OverrideprotectedvoidonPostExecute(Void args) {
            // Locate the listview in listview_main.xmlLog.e("Downloaded DataSize = ", ""+arraylist.size());
        }
    }

This is you HttpHandler class

publicclassHttpHandler
{
    privatestaticfinalStringTAG= HttpHandler.class.getSimpleName();

    publicHttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        Stringresponse=null;
        try {
            URLurl=newURL(reqUrl);
            HttpURLConnectionconn= (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the responseInputStreamin=newBufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReaderreader=newBufferedReader(newInputStreamReader(is));
        StringBuildersb=newStringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

When you want to show your image in imageview then use Glide library. Add below line to your app level build.gradle file

compile'com.github.bumptech.glide:glide:3.7.0'

Now you can do code like this to download image and display into imageview

ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load(url).into(imageView);

For detail please check this link

Post a Comment for "Error Getting Images Into Listview From Server Using Json"