2017-06-17 66 views
-1

我有setOnItemClickListener代碼:如何從自定義列表視圖適配器中獲取數據並傳遞給intent放置額外?

userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

     String user_name = String.valueOf(parent.getItemAtPosition(position)); 
     Log.i("data_items",user_name); 
     Toast.makeText(MainActivity.this,user_name,Toast.LENGTH_SHORT).show(); 
    } 
}); 

日誌給我:

[email protected] 

每一行點擊讓我在最後一個異數。例如

[email protected] 

它是我的SQLite的數據庫?如何閱讀我的自定義列表適配器的onClickItemListene?

任何人都可以幫助我嗎?


ArrayAdapater

private class UserListAdapter extends ArrayAdapter<UserList> { 

     private ArrayList<UserList> items; 
     public UserListAdapter(@NonNull Context context, @LayoutRes int textViewResourceId, @NonNull ArrayList<UserList> objects) { 
      super(context, textViewResourceId, objects); 
      this.items = objects; 
     } 

     @NonNull 
     @Override 
     public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { 
      View v = convertView; 
      if(v == null) 
      { 
       LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       v = layoutInflater.inflate(R.layout.user_list_item,null); 
      } 

      UserList userList = items.get(position); 
      if(userList != null) 
      { 
       TextView usernameTextView = (TextView) v.findViewById(R.id.usernameTextView); 
       TextView fullnameTextViewFeatured = (TextView) v.findViewById(R.id.fullnameTextViewFeatured); 
       if(usernameTextView != null) 
       { 
        usernameTextView.setText(userList.getUser_name()); 
       } 
       if(fullnameTextViewFeatured != null) 
       { 
        fullnameTextViewFeatured.setText(userList.getFull_name()); 
       } 
      } 

      return v; 
     } 
    } 
+0

將適配器的代碼,請 –

+0

ArrayAdapter @Blackbelt – Nere

回答

1

嗨這樣,

userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

     UserList userList = (UserList)parent.getItem(position); 

     String user_name = userList.getUser_name(); 
     Log.i("data_items",user_name); 
     Toast.makeText(MainActivity.this,user_name,Toast.LENGTH_SHORT).show(); 
    } 
}); 
+0

我喜歡你的答案.. – Nere

1

每行點擊的代碼給了我不同的數字結尾。例如

這就是Object.toString的執行。您的適配器擁有類型爲TableName的數據集,而不是String。該行

String user_name = String.valueOf(parent.getItemAtPosition(position)); 

是錯誤的。它應該是

TableName tableName = (TableName) parent.getItemAtPosition(position); 

鑄造到正確的類型後,您可以訪問TableName的字段。

編輯

看到您的適配器後,它看起來像你正在使用UserList數據對象,所以正確的投應該是UserList而不是TableName,這是不是你可以做什麼logcat的是顯示壽

+0

感謝您的回答,MUTHU給我說,我能理解.. – Nere

+0

如何將所有數據傳遞給putExtra答案嗎?例如 'i.putExtra(「userData」,parent.getItemAtPosition(position));'它是正確的嗎? – Nere

+0

只有當對象可以分組時纔可以。 [Here](https://developer.android.com/reference/android/os/Parcelable.html)示例 – Blackbelt

相關問題