2014-11-04 5 views
-1

여기에 많은 게시물을 보았습니다.하지만이 이미지를 MySQL에서 내 앱으로 가져올 수 없습니다. 또한 하나의 우편 번호를 사용하고 내 앱을 채택하려했지만 여전히 앱이 다운되었습니다. 이 게시물 How to JSON parse images from mysql and populate listviewandroid에서 MySQL의 JSON으로 이미지 구문 분석

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); 
      } 

UPDATE는 은 당신이 언급 한 줄 번호는 라인 (198)이다 이것은 서버 측

<?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); 
?> 
+0

같은 사항이이 행 번호 (198)를 지적 할 수 있다면? – Rohit5k2

+0

@ Rohit5k2, 물론, 내 질문을 업데이트했습니다. – Goro

+0

내 대답을 참조하십시오 – Rohit5k2

답변

1

내가 말할 미안하지만 난 생각하지 않는다 .php 파일을한다 .

내 계산 라인 nubmer에 따르면 다음 코드에서 4 s nippet는 제대로 jsonMainNode의 값을 받고하는 경우 NPE에게

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

확인을 일으키는 줄 수 이하 198이어야한다. 귀하의 logcat 및 코드를 사용하여 분석에 기초하면 jsonResponse.optJSONArray("metoxes");이 null을 반환하고 null을 확인하지 않고 for 루프에서 이것을 사용하고있는 것으로 보입니다.

for 루프 앞에 null 값 jsonMainNode을 검사하려면 null 조건을 넣습니다.

사용이

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(); 
+0

이 행의'LogCat'을 두 번 클릭하면'11-04 07 : 39 : 13.880 : E/AndroidRuntime (831) : \t, com.reserveme. 식당 번호. 식당. 목록. 레스토랑.리스트 .java : 1,98) '그것은 나를 '표시해 둡니다. RestaurantInformation stock = new RestaurantInformation stock) = – Goro

+0

중요 할지도 모르지만 MySQL에서는 이미지가 아닌 이미지의 경로 만 저장합니다. 이 문제가 될 수 있습니까? – Goro

+0

이상한 일! 하지만 성명서에 널 체크를 시도 했습니까? – Rohit5k2