【问题标题】:Parsing image with JSON from MySQL in android在android中使用来自MySQL的JSON解析图像
【发布时间】:2014-11-04 12:48:05
【问题描述】:

我在这里看到并阅读了很多帖子,但我仍然无法将这些图像从 mysql 获取到我的应用程序。我还使用了一个邮政编码,并尝试为我的应用采用,但应用仍然崩溃。 我用过这个帖子How to JSON parse images from mysql and populate listview

private ListView listView;
private StockAdaptor stockAdaptor;
String jsonResult = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.restaurants); //Just a listView, shown below
    listView = (ListView) findViewById(R.id.restaurants);
    new JsonReadTask().execute("http://link"); //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 menu;
        ImageView image; 
    }

    private LayoutInflater layoutInflater;
    private RestaurantInformation[] stocks = null; //Array of stocks


    public StockAdaptor(Context context) {
        super();
        layoutInflater = LayoutInflater.from(context);
    }

    public void setStockList(RestaurantInformation[] stocksinfo) {
        this.stocks = stocksinfo;// //////////////LITERALLY THIS

    }

    @Override
    public int getCount() {
        return stocks.length;
    }

    @Override
    public Object getItem(int position) {
        return stocks[position];
    }

    @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.restaurant_information, null);
            holder = new ViewHolder();
            // Creates the new viewholder define above, storing references to the children
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.menu = (TextView) convertView.findViewById(R.id.menu);
            holder.image = (ImageView) convertView.findViewById(R.id.image);



            if (holder.image != null) {
                if (holder.image.getDrawable() == null) {
                    new ImageDownloaderTask(holder.image, null)                                 
                    .execute(stocks[position].image); //Download the image using the image

                }
            }
            convertView.setTag(holder);
        } else {

            holder = (ViewHolder) convertView.getTag();
        }

        holder.name.setText(stocks[position].name);
        holder.menu.setText(stocks[position].menu);

        return convertView;
    }
}

private class JsonReadTask extends AsyncTask<String, Void, String> {

    @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();

    }

}// 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<RestaurantInformation> restaurants = new Vector<RestaurantInformation>();
            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                RestaurantInformation stock = new RestaurantInformation();
                stock.name = jsonChildNode.optString("name");
                stock.menu = jsonChildNode.optString("menu");
                stock.image = jsonChildNode.getString("image");
                Log.i("StockLog", stock.name + stock.menu + stock.image);
                restaurants.add(stock);
            }
            RestaurantInformation[] stocks = new RestaurantInformation[jsonMainNode.length()];

            int stockscount = jsonMainNode.length();
            for (int n = 0; n < stockscount; n++) 
            {               
                stocks[n] = restaurants.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;
    }

}

还有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/menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:paddingTop="5dp"
        android:text="" />
</LinearLayout>

</LinearLayout>

我在LogCat 中的错误是这样的。

11-04 07:39:13.880: E/AndroidRuntime(831): FATAL EXCEPTION: main
11-04 07:39:13.880: E/AndroidRuntime(831): Process: com.reserveme, PID: 831
11-04 07:39:13.880: E/AndroidRuntime(831): java.lang.NullPointerException
11-04 07:39:13.880: E/AndroidRuntime(831):  at com.reserveme.Restaurants.ListDrwaer(Restaurants.java:198)
11-04 07:39:13.880: E/AndroidRuntime(831):  at com.reserveme.Restaurants$JsonReadTask.onPostExecute(Restaurants.java:184)
11-04 07:39:13.880: E/AndroidRuntime(831):  at com.reserveme.Restaurants$JsonReadTask.onPostExecute(Restaurants.java:1)
11-04 07:39:13.880: E/AndroidRuntime(831):  at android.os.AsyncTask.finish(AsyncTask.java:632)
11-04 07:39:13.880: E/AndroidRuntime(831):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-04 07:39:13.880: E/AndroidRuntime(831):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-04 07:39:13.880: E/AndroidRuntime(831):  at android.os.Handler.dispatchMessage(Handler.java:102)
11-04 07:39:13.880: E/AndroidRuntime(831):  at android.os.Looper.loop(Looper.java:136)
11-04 07:39:13.880: E/AndroidRuntime(831):  at android.app.ActivityThread.main(ActivityThread.java:5017)
11-04 07:39:13.880: E/AndroidRuntime(831):  at java.lang.reflect.Method.invokeNative(Native Method)
11-04 07:39:13.880: E/AndroidRuntime(831):  at java.lang.reflect.Method.invoke(Method.java:515)
11-04 07:39:13.880: E/AndroidRuntime(831):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-04 07:39:13.880: E/AndroidRuntime(831):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-04 07:39:13.880: E/AndroidRuntime(831):  at dalvik.system.NativeStart.main(Native Method)

更新:

for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                RestaurantInformation stock = new RestaurantInformation(); <--- THIS LINE
                stock.name = jsonChildNode.optString("name");
                stock.menu = jsonChildNode.optString("menu");
                stock.image = jsonChildNode.getString("image");
                Log.i("StockLog", stock.name + stock.menu + stock.image);
                restaurants.add(stock);
            }

更新 这是服务器端.php 文件

<?php
$host="localhost"; //replace with database hostname 
$username="user"; //replace with database username 
$password="pass"; //replace with database password 
$db_name="dbname"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from Restaurants"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
    while($row=mysql_fetch_assoc($result)){
    $json['Restaurants'][]=$row;
    }
}
mysql_close($con);
echo json_encode($json); 
?> 

【问题讨论】:

  • 你能指出第 198 行吗?
  • @Rohit5k2,当然,我已经更新了我的问题。 RestaurantInformation stock = new RestaurantInformation();
  • 请看我的回答

标签: android mysql json


【解决方案1】:

很抱歉,但我认为你提到的行号不是第 198 行。

根据我的计算,以下代码 sn-p 中的第 4 行应该是导致 NPE 的第 198 行

1 JSONObject jsonResponse = new JSONObject(jsonResult);
2 JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
3 Vector<RestaurantInformation> restaurants = new Vector<RestaurantInformation>();
4 for (int i = 0; i < jsonMainNode.length(); i++) 
5 {
6    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
7    RestaurantInformation stock = new RestaurantInformation();
     .........

检查您是否正确获取了jsonMainNode 的值。根据使用您的 logcat 和代码进行的分析,jsonResponse.optJSONArray("metoxes"); 似乎返回 null 并且没有检查 null 您在 for 循环中使用它。

在 for 循环之前为 null 设置一个 if 条件以检查 jsonMainNode 的 null 值。

像这样使用 if 语句

JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
Vector<RestaurantInformation> restaurants = new Vector<RestaurantInformation>();


if(jsonMainNode == null)
{
    Log.e("Inside if", "jsonMainNode is null here");
    return;
}

for (int i = 0; i < jsonMainNode.length(); i++) 
{
   JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
   RestaurantInformation stock = new RestaurantInformation();

【讨论】:

  • 当我双击这一行上的LogCat 11-04 07:39:13.880: E/AndroidRuntime(831): at com.reserveme.Restaurants.ListDrwaer(Restaurants.java:198) 时,它标记了我这个RestaurantInformation stock = new RestaurantInformation();
  • 可能重要或不重要,但在 MySQL 中,我只保存图像的路径而不是图像。会不会是这个问题?
  • 这很奇怪!但是您是否尝试过使用空检查 if 语句?
  • 把这个空语句放在哪里?我的意思是这不是try{}catch{} 阻止这样做吗?
  • 我认为 try-catch 块不会检查空值。它会检查它是否存在以及格式(int、string、array 等)。在for循环之前使用if语句,看看它是否进入if(打印日志或其他东西)
猜你喜欢
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多