2016-12-05 63 views
0

我想從ListView獲取對象。我把我的數據從一個csv文件。從Android的ListView獲取對象

我有兩列和大約100行。第一列是名字,第二列是數字。 我想要點擊一行後得到數字。

所以我必須在onCreate

listView.setClickable(true); 
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     Button btn2 = (Button) findViewById(R.id.button3); 
     btn2.setEnabled(true); 
     Object listItem = listView.getItemAtPosition(position); 
     String item = (listView.getItemAtPosition(position).toString()); 
     btn2.setText(item); 

    } 
}); 

而在此之後,當我點擊一個行(第一和第二列=得分相同),我Button文本顯示[LJAVA.LANG.STRING;@42791450,每一行有其他數字。

編輯:

listView = (ListView) findViewById(R.id.list_view2); 
    itemArrayAdapter = new ItemArrayAdapter(getApplicationContext(), R.layout.single_list_item); 

    Parcelable state = listView.onSaveInstanceState(); 
    listView.setAdapter(itemArrayAdapter); 
    listView.onRestoreInstanceState(state); 

    InputStream inputStream = getResources().openRawResource(R.raw.manager_number); 
    CSVReader csv = new CSVReader(inputStream); 
    List<String[]> scoreList = csv.read(); 


    for (String[] scoreData : scoreList) { 
     itemArrayAdapter.add(scoreData); 

    } 
+0

您留下了對象的標識符而不是對象的相應編號。你需要實現一個對象,它是相應的setter和getters,並檢索你想要的值。例如:btn2.setText(listView.getItemAtPosition(position).getNumber()); – Ricardo

+0

顯示適配器初始化代碼。 –

回答

0

如果你有辦法從你的ItemArrayAdapter檢索對象,例如itemArrayAdapter.get(index),你可以聲明它作爲一個實例屬性,並使用位置索引。像這樣:

public class myActivity extends Activity { 

    private ItemArrayAdapter itemArrayAdapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

    this.itemArrayAdapter = new ItemArrayAdapter(getApplicationContext(), R.layout.single_list_item); 

    InputStream inputStream = getResources().openRawResource(R.raw.manager_number); 
    CSVReader csv = new CSVReader(inputStream); 
    List<String[]> scoreList = csv.read(); 

    for (String[] scoreData : scoreList) { 
     itemArrayAdapter.add(scoreData); 
    }  

    ListView listView = (ListView) findViewById(R.id.list_view2); 
    listView.setClickable(true); 
    Parcelable state = listView.onSaveInstanceState(); 
    listView.setAdapter(itemArrayAdapter); 
    listView.onRestoreInstanceState(state); 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

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

     Button btn2 = (Button) findViewById(R.id.button3); 
     btn2.setEnabled(true); 
     String item = this.itemArrayAdapter.get(position);; 
     btn2.setText(item); 

    } 
    });