2014-11-04 2 views
0

여기에서 모든 해결책을 시도했지만 도움이되지 않았습니다. 이미지는 텍스트 만 목록보기에 표시되지 않습니다. 나는이 코드이미지가 ImageView에 표시되지 않습니다.

public class Restaurants extends Activity { 

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

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.restaurants); 
    listView = (ListView) findViewById(android.R.id.list); 
    image = (ImageView) findViewById(R.id.image); 
    new JsonReadTask().execute("http://link/GetRestaurants.php"); 

} 

@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 
    private ListView stocksListView = null; 

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

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

    } 

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

    @Override 
    public Object getItem(int position) { 
     return stocks[position]; 
    } 
    public RestaurantInformation[] 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.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() { 
    //Log.d("data from server", "data: " + jsonResult.toString()); 
    try { 
     if (jsonResult!=null) { 
      JSONObject jsonResponse = new JSONObject(jsonResult); 
      JSONArray jsonMainNode = jsonResponse.optJSONArray("Restaurants"); 
      Vector<RestaurantInformation> vstocks = new Vector<RestaurantInformation>(); 

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

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

       stock.image = jsonChildNode.getString("image"); 
       stock.name = jsonChildNode.optString("name"); 
       stock.menu = jsonChildNode.optString("menu"); 

       //stock.imgPath = jsonChildNode.getString("imgPath"); 

       Log.e("err", stock.image + " " + stock.name + " " + stock.menu); 
       vstocks.add(stock); 
      } 

      RestaurantInformation[] stocks = new RestaurantInformation[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(); 

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

} 
} 

내가 그렇게 자바 + 안드로이드에 경험이 정말 문제가 될 수있는 아무 생각이 아니에요이다 LogCat

11-04 14:46:29.319: I/(1225): {"Restaurants":[{"id":"1","name":"Restaurant- 1","menu":"Restaurant-1","image":"rest1.jpg"},{"id":"2","name":"Restaurant-2","menu":"Restaurant-2","image":"rest2.jpg"},{"id":"3","name":"Restaurant-3","menu":"Restaurant-3","image":"rest3.jpg"},{"id":"4","name":"Restaurant-4","menu":"Restaurant-4","image":"rest4.jpg"}]} 
11-04 14:46:29.329: E/err(1225): rest1.jpg Restaurant-1 Restaurant-1 
11-04 14:46:29.329: E/err(1225): rest2.jpg Restaurant-2 Restaurant-2 
11-04 14:46:29.329: E/err(1225): rest3.jpg Restaurant-3 Restaurant-3 
11-04 14:46:29.329: E/err(1225): rest4.jpg Restaurant-4 Restaurant-4 

만이되었다. 이는 restaurants.xml

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


    <ImageView 
     android:id="@+id/image" 
     android:layout_width="70dp" 
     android:layout_height="70dp" /> 

    <ListView 
     android:id="@id/android:list" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_alignLeft="@+id/image" 
     android:layout_alignParentTop="true" > 
    </ListView> 

</RelativeLayout> 

UPDATE 목표는이 같은입니다. 가능하다면 나는 텍스트와 서브 텍스트를 가지고 그 옆 왼쪽에있는 이미지를로드 할 및

enter image description here

UPDATE restaurant_information.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> 

+0

당신이 당신의 R.layout.restaurant_information 레이아웃을 게시하시기 바랍니다 수 :

이 사용 해보세요? – JML

+0

질문에 추가되었지만 여전히 listview'restaurant.xml'에 onclick을 넣지 않았기 때문에 작동하지 않습니다 – Goro

답변

1

ListView는 layout_width = "fill_parent"및 layout_height = "fill_parent로 정의됩니다 ". 따라서 부모의 전체 영역을 차지할 것이고 레이아웃에서 마지막으로 정의 된 이후 z 순서의 맨 위에 있으므로 ImageView가 가려집니다.

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

    <ImageView 
     android:id="@+id/image" 
     android:layout_width="70dp" 
     android:layout_height="70dp" 
     android:layout_alignParentLeft="true" 
     android:layout_centerVertical="true"/> 

    <ListView 
     android:id="@id/android:list" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_toRightOf="@+id/image" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentTop="true" > 
    </ListView> 

</RelativeLayout> 
+0

죄송하지만이 문제를 해결하는 방법을 모르겠습니다. 마진과 패딩과 같은 수동으로 목록의 위치를 ​​수정하려면 어떻게해야합니까? – Goro

+0

도와 드릴 수는 있지만 목록보기를 기준으로 이미지보기를 원하는 위치를 알아야합니다. 사진은 훌륭하지만, 그렇지 않은 경우 좋은 설명이 효과적입니다. –

+0

내 질문에 내가 작성한 이미지가 편집되었습니다. – Goro

1

당신이하려는 그림을 "rest1.jpg"에서 다운로드하십시오. 완전한 URL이 필요합니다. 전체 URL을 json 응답 내에 보내거나 코드 내에 추가 할 수 있습니다 (파일 이름 앞에 오는 부분이 고정되어있는 경우)

+0

나는'http : // web.com/rest1.jp'와 같이 BD 전체 경로를 넣으려고했지만 여전히 같은. json 응답을 내부로 보내거나 내부 코드를 추가하려면 어떻게해야합니까? – Goro

관련 문제