使用Json从服务器将图像导入Listview时出错

时间:2022-12-29 21:18:17

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 Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "id";
    static String COUNTRY = "name";

    static String FLAG = "image";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.activity_sub_menu);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<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();
        // }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonarray = JsonFunctions
                    .getJSONfromURL("http://cloud.granddubai.com/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 = new HashMap<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();
            }
            return null;
        }

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

i am new to android ...one more thing few images are not available in table.is that the reason???? here is my json:

我是新手android ...还有一些东西,桌面上没有几张图片。这就是原因????这是我的json:

[
  {
    "id": "1",
    "name": "Bianca Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Bianca.png"
  },
  {
    "id": "2",
    "name": "Cheese Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Cheese.png"
  },
  {
    "id": "3",
    "name": "Chicken BBQ Pizza:",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Chicken BBQ.png"
  },
  {
    "id": "4",
    "name": "Deluxe Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Deluxe.png"
  },
  {
    "id": "5",
    "name": "Greek Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Greek.png"
  },
  {
    "id": "6",
    "name": "Hawaiian Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Hawaiian.png"
  },
  {
    "id": "7",
    "name": "Meat Lovers Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Meat Lovers.png"
  },
  {
    "id": "8",
    "name": "Pepperoni Pizza",
    "image": ""
  },
  {
    "id": "9",
    "name": "Shrimp Pizza",
    "image": ""
  },
  {
    "id": "10",
    "name": "Vegetable Pizza",
    "image": ""
  },
  {
    "id": "11",
    "name": "Original Italian Pizza",
    "image": ""
  },
  {
    "id": "12",
    "name": "Beef Strips Pasta",
    "image": ""
  },
  {
    "id": "13",
    "name": "Chicken Pasta",
    "image": ""
  },
  {
    "id": "14",
    "name": "Meat Balls Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Meat Lovers.png"
  },
  {
    "id": "15",
    "name": "Sausage Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Sausage.png"
  },
  {
    "id": "16",
    "name": "Shrimp Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Shrimp.png"
  },
  {
    "id": "17",
    "name": "Vegetable Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Vegetable.png"
  },
  {
    "id": "18",
    "name": "Pesto Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Pesto.png"
  },
  {
    "id": "19",
    "name": "Chicken Lasagna",
    "image": ""
  },
  {
    "id": "20",
    "name": "Meat Lasagna",
    "image": ""
  },
  {
    "id": "21",
    "name": "Vegetable Lasagna",
    "image": ""
  },
  {
    "id": "22",
    "name": "Caesar Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Caesar.png"
  },
  {
    "id": "23",
    "name": "Chicken Caesar Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Chicken Caesar.png"
  },
  {
    "id": "24",
    "name": "Garden Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Garden.png"
  },
  {
    "id": "25",
    "name": "Greek Salad",
    "image": ""
  },
  {
    "id": "26",
    "name": "Pasta Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Pasta Salad.png"
  },
  {
    "id": "27",
    "name": "Sunny Side up ",
    "image": ""
  },
  {
    "id": "28",
    "name": "Omelette ",
    "image": ""
  },
  {
    "id": "29",
    "name": "Scrambled Eggs",
    "image": ""
  },
  {
    "id": "30",
    "name": "Scrambled Egg with toppings",
    "image": ""
  },
  {
    "id": "31",
    "name": "Coffee",
    "image": ""
  },
  {
    "id": "32",
    "name": "Fresh Juice",
    "image": ""
  },
  {
    "id": "36",
    "name": "Water 500ml",
    "image": ""
  },
  {
    "id": "35",
    "name": "Pepsi Can",
    "image": ""
  },
  {
    "id": "37",
    "name": "Soup",
    "image": ""
  },
  {
    "id": "38",
    "name": "Special Offer Family Pack",
    "image": ""
  }
]

this is my php file

这是我的php文件

<?php 
include ('config.php');


$id = $_GET['id'];



$sql = mysqli_query($conn,"SELECT * FROM main_menu_items  ");

$arr = array();
$i=0;
while($result = mysqli_fetch_array($sql))
{
$arr[$i]['id']= $result['id'];
$arr[$i]['name']= $result['name'];
$arr[$i]['image']=$result['image'];
$i++;
}
echo json_encode($arr);

?>

this is my imageloader:

这是我的imageloader:

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.nicon1;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // Decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            // Recommended Size 512
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

here is my Listview Adapter

这是我的Listview适配器

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
                           ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView id;
        TextView name;
        TextView population;
        ImageView image;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.list_item1, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        id = (TextView) itemView.findViewById(R.id.idq);
        name = (TextView) itemView.findViewById(R.id.type1);


        // Locate the ImageView in listview_item.xml
        image = (ImageView) itemView.findViewById(R.id.subimg);

        // Capture position and set results to the TextViews
        id.setText(resultp.get(SubMenu.RANK));
        name.setText(resultp.get(SubMenu.COUNTRY));

        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image);
        // Capture ListView item click
        /**itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);
                // Pass all data rank
                intent.putExtra("rank", resultp.get(MainActivity.RANK));
                // Pass all data country
                intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
                // Pass all data population
                intent.putExtra("population",resultp.get(MainActivity.POPULATION));
                // Pass all data flag
                intent.putExtra("flag", resultp.get(MainActivity.FLAG));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });*/
        return itemView;
    }
}

5 个解决方案

#1


0  

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 {}.

因为来自服务器的响应结构是JSONArray([])而不是JSONObject({})。那是起始元素是[]而不是{}。

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

在JsonFunctions类中添加以下方法并调用此方法:

public static JSONArray getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(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 string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            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 = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }

I changed your code, please use it:

我更改了你的代码,请使用它:

public class SubMenu extends Activity {
        // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapter adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String RANK = "id";
        static String COUNTRY = "name";

        static String FLAG = "image";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.activity_sub_menu);
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }

        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<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();
            // }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<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 = new HashMap<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();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {
                // Locate the listview in listview_main.xml
                listview = (ListView) findViewById(R.id.list1);
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapter(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.

由于没有名为“main_menu_items”的键,我注释掉了该代码。

#2


0  

You are getting response as JSONArray so you

你正在以JSONArray的身份得到回应

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

Now you can access jsonArray like:

现在你可以访问jsonArray了:

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("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.

愿它能帮到你。谢谢。

#3


0  

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

JSONArray jsonarray = JSONfunctions.getJSONfromURL(jsonStr); //得到一个数组

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

您可以使用此代码段进行解析

#4


0  

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

两个类中的JSONObject和JSONArray之间存在冲突。干得好!

SubMenu.class

SubMenu.class

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

        static String FLAG = "image";


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.solver_activity);
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }

        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<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();
            // }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<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 = new HashMap<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();
                }
                return null;
            }

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

JsonFunction.class

JsonFunction.class

public class JsonFunctions {

    public static JSONArray getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(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 string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            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 = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

#5


0  

You can do like this

你可以这样做

ArrayList<HashMap<String, String>> arraylist;
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
        protected Void doInBackground(Void... params) {

            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                HttpHandler sh = new HttpHandler();

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

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

                JSONArray jsonObject = new JSONArray(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 = new HashMap<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();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            Log.e("Downloaded DataSize = ", ""+arraylist.size());
        }
    }

This is you HttpHandler class

这是你的HttpHandler类

public class HttpHandler
{
    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(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) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        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

如果要在imageview中显示图像,请使用Glide库。将以下行添加到您的应用级build.gradle文件中

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 = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load(url).into(imageView);

For detail please check this link

有关详细信息,请查看此链接

#1


0  

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 {}.

因为来自服务器的响应结构是JSONArray([])而不是JSONObject({})。那是起始元素是[]而不是{}。

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

在JsonFunctions类中添加以下方法并调用此方法:

public static JSONArray getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(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 string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            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 = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }

I changed your code, please use it:

我更改了你的代码,请使用它:

public class SubMenu extends Activity {
        // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapter adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String RANK = "id";
        static String COUNTRY = "name";

        static String FLAG = "image";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.activity_sub_menu);
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }

        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<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();
            // }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<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 = new HashMap<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();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {
                // Locate the listview in listview_main.xml
                listview = (ListView) findViewById(R.id.list1);
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapter(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.

由于没有名为“main_menu_items”的键,我注释掉了该代码。

#2


0  

You are getting response as JSONArray so you

你正在以JSONArray的身份得到回应

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

Now you can access jsonArray like:

现在你可以访问jsonArray了:

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("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.

愿它能帮到你。谢谢。

#3


0  

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

JSONArray jsonarray = JSONfunctions.getJSONfromURL(jsonStr); //得到一个数组

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

您可以使用此代码段进行解析

#4


0  

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

两个类中的JSONObject和JSONArray之间存在冲突。干得好!

SubMenu.class

SubMenu.class

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

        static String FLAG = "image";


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.solver_activity);
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }

        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<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();
            // }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<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 = new HashMap<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();
                }
                return null;
            }

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

JsonFunction.class

JsonFunction.class

public class JsonFunctions {

    public static JSONArray getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(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 string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            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 = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

#5


0  

You can do like this

你可以这样做

ArrayList<HashMap<String, String>> arraylist;
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
        protected Void doInBackground(Void... params) {

            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                HttpHandler sh = new HttpHandler();

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

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

                JSONArray jsonObject = new JSONArray(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 = new HashMap<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();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            Log.e("Downloaded DataSize = ", ""+arraylist.size());
        }
    }

This is you HttpHandler class

这是你的HttpHandler类

public class HttpHandler
{
    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(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) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        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

如果要在imageview中显示图像,请使用Glide库。将以下行添加到您的应用级build.gradle文件中

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 = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load(url).into(imageView);

For detail please check this link

有关详细信息,请查看此链接