【问题标题】:How to JSON parse images from mysql and populate listview如何 JSON 解析来自 mysql 的图像并填充列表视图
【发布时间】:2014-03-05 18:14:36
【问题描述】:

大家好,我正在尝试使用数据库中的图像填充列表视图。我已将图像上传到服务器,并采用http://www.spinner.bl.ee/images/ATE.png 之类的完整路径并将其作为varchar 存储在名为image 的数据库列中。然后我有一个.php 文件,你可以在这里看到http://spinner.bl.ee/getstocks.php,它给了我一个名为metoxes 的json 数组,其中包含所有数据。但图像有点不同(意思是路径)我该如何解决这个问题??

在 imageview 的 android 应用程序的 java 文件中,我得到完整路径而不是图像。任何帮助将不胜感激!

我的代码

private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setTitle(R.string.waiting);
            pDialog.setMessage(getString(R.string.get_stocks));
            pDialog.setCancelable(false);
            pDialog.show();
        }

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

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {

            ListDrwaer();
            pDialog.dismiss();
        }

    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[] { url });
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> stocksList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("name");
                String price = jsonChildNode.optString("price");
                String image = jsonChildNode.getString("image");
                //Log.i("image is valid", image);
                //String outPut =  name + price;
                //BitmapFactory.decodeFile(image);
                stocksList.add(createStockList(name, price, image));
            }


        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        }
        //byte[] image = {};
        String[] from = { "name", "price", "image" };
        //BitmapFactory.decodeByteArray(image, 50, image.length);
        int[] to = { R.id.stock_name, R.id.stock_price, R.id.dbImage };
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, stocksList,
                R.layout.list_item,
                from, to);
        listView.setAdapter(simpleAdapter);
    }

    private HashMap<String, String> createStockList(String name, String price, String image) {
        HashMap<String, String> stockNameNo = new HashMap<String, String>();
        stockNameNo.put("name", name);
        stockNameNo.put("price", price);
        stockNameNo.put("image", image);
        return stockNameNo;
    }
}

提前致谢。

【问题讨论】:

    标签: php android mysql json listview


    【解决方案1】:

    如果您的问题是您想要以http://www.spinner.bl.ee/images/ATE.png 输出的数据以http:\/\/spinner.bl.ee\/images\/ATE.png 输出,那么当org.json.JSONObject 将字符串从您的url 加载到JSONObject 时,这应该不是问题;你测试过这段代码吗?

    这是一些 AsyncTask 访问您的服务器的实现;只有一个活动,MainActivity.java,然后 StockInformation.java 作为对象。

    public class MainActivity extends Activity {
    
        ProgressDialog pDialog;
        ListView listView;
        private StockAdaptor stockAdaptor;
        String jsonResult = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_); //Just a listView, shown below
            listView = (ListView) findViewById(android.R.id.list);
            new JsonReadTask().execute("http://spinner.bl.ee/getstocks.php"); //YOUR URL JSON SERVER, IF IT IS DIFFERENT FROM THAT SUPPLIED ABOVE
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            return true; //No options
        }
    
        public void onStart() {
            super.onStart();
    
            stockAdaptor = new StockAdaptor(this); //Create a new StockAdaptor
        }
    
        public static String strFromStream(InputStream in) throws IOException { //Simple function, getting a String from an InputStream
            StringBuilder out = new StringBuilder();
            BufferedReader breader = new BufferedReader(new InputStreamReader(in));
            String cline;
            String newLine = System.getProperty("line.separator");
            while ((cline = breader.readLine()) != null) {
                out.append(cline);
                out.append(newLine);
            }
            return out.toString();
        }
    
        private class StockAdaptor extends BaseAdapter { //The stocks list adaptor
    
            class ViewHolder {
                TextView name;
                TextView price;
                ImageView image; 
            }
    
            private LayoutInflater layoutInflater;
            private StockInformation[] stocks = null; //Array of stocks
            private ListView stocksListView = null;
    
            public StockAdaptor(Context context) {
                super();
                layoutInflater = LayoutInflater.from(context);
            }
    
            public void setStockList(StockInformation[] stocksinfo) {
                this.stocks = stocksinfo;// //////////////LITERALLY THIS
    
            }
    
            @Override
            public int getCount() {
                return stocks.length;
            }
    
            @Override
            public Object getItem(int position) {
                return stocks[position];
            }
    
            public StockInformation[] getAll() { //Return the array of stocks
                return stocks;
            }
    
            @Override
            public long getItemId(int position) {
                return 0;
            }
    
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder; //New holder
                if (convertView == null) {
                    convertView = layoutInflater.inflate(R.layout.list_item,
                            null);
                    holder = new ViewHolder();
                    // Creates the new viewholder define above, storing references to the children
                    holder.name = (TextView) convertView.findViewById(R.id.name);
                    holder.price = (TextView) convertView.findViewById(R.id.price);
                    holder.image = (ImageView) convertView.findViewById(R.id.image);
    
                    stocksListView = (ListView) findViewById(android.R.id.list);
    
                    if (holder.image != null) {
                        if (holder.image.getDrawable() == null) {
                            new ImageDownloaderTask(holder.image, null)                                 .execute(stocks[position].imageurl); //Download the image using the imageurl
    
                        }
                    }
                    convertView.setTag(holder);
                } else {
                    stocksListView = (ListView) findViewById(android.R.id.list);
                    holder = (ViewHolder) convertView.getTag();
                }
    
                holder.name.setText(stocks[position].name);
                holder.price.setText(stocks[position].price);
    
                return convertView;
            }
        }
    
        private class JsonReadTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setTitle("waiting");
                pDialog.setMessage("getting stocks");
                pDialog.setCancelable(false);
                pDialog.show();
            }
    
            @Override
            protected String doInBackground(String... params) {
                if (URLUtil.isValidUrl(params[0])) {
                    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
                    final HttpGet getRequest = new HttpGet(params[0]);
                    try {
                        HttpResponse response = client.execute(getRequest);
                        final HttpEntity httpentity = response.getEntity();
                        if (httpentity != null){
                            InputStream inputStream = null;
                            try {
                                inputStream = httpentity.getContent();
                                jsonResult = strFromStream(inputStream);
                                Log.i("", jsonResult);
                                return jsonResult;
                            } catch (IllegalArgumentException e) {
                                //
                            } finally {
                                httpentity.consumeContent();
                            }
                        }
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        client.close();
                    }
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(String result) {
    
                ListDrwaer();
                pDialog.dismiss();
            }
    
        }// end async task
    
        // build hash set for list view
        public void ListDrwaer() {
    
            try {
                if (jsonResult!=null) {
                    JSONObject jsonResponse = new JSONObject(jsonResult);
                    JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
                    Vector<StockInformation> vstocks = new Vector<StockInformation>();
                    for (int i = 0; i < jsonMainNode.length(); i++) {
                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                        StockInformation stock = new StockInformation();
                        stock.name = jsonChildNode.optString("name");
                        stock.price = jsonChildNode.optString("price");
                        stock.imageurl = jsonChildNode.getString("image");
                        Log.i("StockLog", stock.name + stock.price + stock.imageurl);
                        vstocks.add(stock);
                    }
                    StockInformation[] stocks = new StockInformation[jsonMainNode.length()];
    
                    int stockscount = jsonMainNode.length();
                    for (int n = 0; n < stockscount; n++) 
                    {               
                        stocks[n] = vstocks.get(n);
                    }
                    stockAdaptor.setStockList(stocks);
                    listView.setAdapter(stockAdaptor);
                } else {
                    Toast.makeText(getApplicationContext(), "Error; jsonResult null",
                            Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    
        private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
            private final WeakReference<ImageView> imageViewReference;
    
            public ImageDownloaderTask(ImageView imageView, View view) {
                imageViewReference = new WeakReference<ImageView>(imageView);
            }
    
            @Override
            // Actual download method, run in the task thread
            protected Bitmap doInBackground(String... params) {
                // params comes from the execute() call: params[0] is the url.
                return downloadBitmap(params[0]);
            }
    
            @Override
            // Once the image is downloaded, associates it to the imageView
            protected void onPostExecute(Bitmap bitmap) {
                if (isCancelled()) {
                    bitmap = null;
                }
    
                if (imageViewReference != null) {
                    ImageView imageView = imageViewReference.get();
                    if (imageView != null) {
    
                        if (bitmap != null) {
                            imageView.setImageBitmap(bitmap);
                        } else {
                            //
                        }
                    }
    
                }
    
            }
    
            Bitmap downloadBitmap(String url) {
                if(URLUtil.isValidUrl(url)){
    
                    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
                    final HttpGet getRequest = new HttpGet(url);
                    try {
                        HttpResponse response = client.execute(getRequest);
                        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 {
                                inputStream = entity.getContent();
                                try {
                                    byte[] buffer = new byte[8192];
                                    int bytesRead;
                                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                                        output.write(buffer, 0, bytesRead);
                                    }   
                                    return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length);
                                } catch (IllegalArgumentException e) {
                                    e.printStackTrace();
                                    Log.i("IAE", "in stocks");
                                    return null;
                                }
                            } finally {
                                if (inputStream != null) {
                                    inputStream.close();
                                }
                                entity.consumeContent();
                            }
                        }
                    } catch (Exception e) {
                        getRequest.abort();
                        Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
                    } finally {
                        if (client != null) {
                            client.close();
                        }
                    }
                    return null;
    
                }
                return null;
            }
    
        }
    }
    

    单独定义:StockInformation.java;库存对象。

    public class StockInformation {
        public String name;
        public String price;
        public String imageurl; 
    }
    

    然后是xml文件:activity_.xml(只包含ListView);

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".Activity" >
    
            <ListView
            android:id="@+id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
    </RelativeLayout>
    

    还有list_item.xml(就是每只股票需要的图片和两个文字):

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        android:orientation="vertical" >
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
    
            <ImageView
                android:id="@+id/image"
                android:layout_width="70dp"
                android:layout_height="70dp" />
    
            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:lineSpacingExtra="3dp"
                android:paddingLeft="5dp"
                android:paddingTop="5dp"
                android:text="" />
    
            <TextView
                android:id="@+id/price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="5dp"
                android:paddingTop="5dp"
                android:text="" />
        </LinearLayout>
    
    </LinearLayout>
    

    【讨论】:

    • 这正是我的问题,它将路径而不是图像加载到我的 imageview 的 id 中,即 R.id.imageView1 ... 不,我还没有测试 org.json.JSONObject 如何准确实现这个??
    • 1) 使用 Log.i 打印出字符串 image 以检查它是否是有效的 url。 2)使用AsyncTask(可能)从所述url下载图像,将流解码为位图,然后setImageBitmap(downloaded_bitmap)
    • 它给了我这个错误 03-05 14:19:36.850: E/BitmapFactory(1056): Unable to decode stream: java.io.FileNotFoundException: /http:/spinner.bl.ee/图像/ALPHA.png:打开失败:ENOENT(没有这样的文件或目录)但我不知道如何修复它。图像都存在并且路径正确。图像的类型是否重要,因为我的都是 png。
    • 您是否将正确的参数传递给BitmapFactory.decodeByteArraybyte[],int(可能是0),byte[]的长度为int?
    • 我没有使用 BitmapFactory.decodeByteArray..如何使用它并传递参数???你能帮帮我吗??
    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2014-12-22
    • 1970-01-01
    相关资源
    最近更新 更多