2014-11-05 58 views
1

我有listView,它們顯示來自MySQL DB的圖像和文本。到目前爲止是好的,但現在我想知道如果點擊某個項目以從數據庫中打開該ID,該怎麼做。示例ListView 1與來自數據庫的id=1 .. ListView 2id=2等。當我點擊第2項從數據庫打開該ID時。任何想法我怎麼能做到這一點? 這是XML其中加載列表視圖在setOnClickListener上設置ListView燈箱ID

<?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="300dp" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:background="@drawable/buttons" 
    android:layout_marginTop="10dp" 
    > 

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

    <TextView 
     android:id="@+id/name" 
     android:layout_width="300dp" 
     android:layout_height="wrap_content" 
     android:paddingBottom="10dp" 
     android:paddingLeft="5dp" 
     android:paddingTop="15dp" 
     android:text="" /> 

</LinearLayout> 

</LinearLayout> 

這是代碼,我認爲我需要修復

public class Restaurants extends Activity { 

ListView listView; 
TextView textView, textView1; 
private StockAdaptor stockAdaptor; 
String jsonResult = null; 
ImageView image; 


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



    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(listView.getLayoutParams()); 
    lp.setMargins(10, 10, 0, 0); 
    listView.setLayoutParams(lp); 

    textView.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(Restaurants.this, RestaurantInformation.class); 
      startActivity(intent); 

     } 
    }); 
} 

@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 RestaurantStrings[] stocks = null; //Array of stocks 
    private ListView stocksListView = null; 

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

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

    } 

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

    @Override 
    public Object getItem(int position) { 
     return stocks[position]; 
    } 
    public RestaurantStrings[] 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_second, 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<RestaurantStrings> vstocks = new Vector<RestaurantStrings>(); 

      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); 
       RestaurantStrings stock = new RestaurantStrings(); 

       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); 
       vstocks.add(stock); 
      } 

      RestaurantStrings[] stocks = new RestaurantStrings[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; 
    } 

} 
} 

如果我試圖把在onCreate()一個setOnClickListener,你可以看到應用程序的一部分給"Unfortunately your app has stopped"

UPDATE

<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" 
tools:context=".Activity" 
android:background="#D3D3D3"> 

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

<ListView 
    android:id="@id/android:list" 
    android:layout_width="300dp" 
    android:layout_height="match_parent" 
    android:layout_toRightOf="@+id/image" 

    android:layout_alignParentTop="true" 
    android:divider="@android:color/transparent" 
    android:dividerHeight="5dp" > 

</ListView> 

</RelativeLayout> 

錯誤

11-05 13:37:26.498: E/AndroidRuntime(1493): FATAL EXCEPTION: main 
11-05 13:37:26.498: E/AndroidRuntime(1493): Process: com.reserveme, PID: 1493 
11-05 13:37:26.498: E/AndroidRuntime(1493): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.reserveme/com.reserveme.Restaurants}: java.lang.NullPointerException 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.ActivityThread.access$800(ActivityThread.java:135) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.os.Handler.dispatchMessage(Handler.java:102) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.os.Looper.loop(Looper.java:136) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.ActivityThread.main(ActivityThread.java:5017) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at java.lang.reflect.Method.invokeNative(Native Method) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at java.lang.reflect.Method.invoke(Method.java:515) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at dalvik.system.NativeStart.main(Native Method) 
11-05 13:37:26.498: E/AndroidRuntime(1493): Caused by: java.lang.NullPointerException 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at com.reserveme.Restaurants.onCreate(Restaurants.java:69) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.Activity.performCreate(Activity.java:5231) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
11-05 13:37:26.498: E/AndroidRuntime(1493):  ... 11 more 
+0

異常堆棧跟蹤? – 2014-11-05 18:33:33

+0

佈局文件中沒有Listview。也許這個佈局是listview項目?如果是這樣,請在您的問題中添加正確的版面如果沒有,那麼你已經知道缺少的東西 – Salem 2014-11-05 18:34:42

+0

對不起,我發佈問題時忘記添加它。我現在更新了它。 – Goro 2014-11-05 18:36:51

回答

3

我在我的項目之一使用的ListView了。爲了在我的列表視圖中獲取被觸摸/點擊的位置,我已經將一個ClickHandler註冊到ListView(而不是列表中的項目)。 在你的例子中,ID等於位置,所以我認爲你可以做同樣的事情。

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { 
      Intent intent = new Intent(Restaurants.this, RestaurantInformation.class); 
      intent.putExtra("myID", position); 
      startActivity(intent); 
     } 

    }); 

在新的活動,你可以撥打以下,以獲得ID:

Intent intent = getIntent(); 
if (intent.getExtras() != null) { 
     myID = (Integer) intent.getExtras().get("myID"); 
    } 
+0

我無法想象如何鏈接與ID上的項目點擊\ – Goro 2014-11-05 18:52:57

+0

我嘗試過'意圖意圖=新的意圖(Restaurants.this,RestaurantInformation.class); startActivity(意圖);'實際上它打開新的活動並不會崩潰。問題是如何獲取相應的ID,以及何時打開第二個活動以加載該ID的信息。該ID等於列表視圖中的位置 – Goro 2014-11-05 19:13:40

+0

您可以使用'intent.putExtra(「id」,theID)'將該ID與'if(intent.getExtras()!= null)一起獲取{ \t \t \t \t idFromIntent =(String)intent.getExtras()。get(「id」); \t \t}' – Kiki 2014-11-05 19:16:02