Get object from ListView in android - android

I want to get object from ListView. I put my data from a csv file.
I have two column and around 100 rows. First column is Name, second is number.
I want get number after clicking on a row.
So I have in 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);
}
});
And after that when I click on a row (first and second column= the same score), my Button text shows [LJAVA.LANG.STRING;#42791450, every row have other numbers.
EDIT:
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);
}

If you have a way to retrieve the object from your ItemArrayAdapter, for example itemArrayAdapter.get(index), you could declare it as an instance attribute and use the position as index. Like so:
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);
}
});

Related

Is it possible to get data from my listview onclick

Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method

set textview onload and not on itemclick in a listview

I have a listview populated from a table with a simple adapter. Now, I can change the value of a textview if I click the list item, like this:
ArrayList<HashMap<String, String>> userList = controller.getOld();
// If users exists in SQLite DB
if (userList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(OldTips.this, userList, R.layout.old_tips, new String[] {
"userId", "tara","ora_meci" ,"echipa_acasa","echipa_deplasare","cota","pronostic","explicatii","rezultat"}, new int[] { R.id.userId, R.id.tara , R.id.ora_meci, R.id.echipa_acasa, R.id.echipa_deplasare, R.id.cota,R.id.pronostic,R.id.explicatii,R.id.rezultat});
final ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Object obj = myList.getAdapter().getItem(position);
// String value= obj.toString();
TextView textView = (TextView) view.findViewById(R.id.echipa_acasa);
// String nume_campanie = textView.getText().toString();
textView.setText("value of header text");
}
});
Question: is it possible to change the textview value onload or something like this and not onclick of the item from the listview?

Android Studio ListView - null pointer exception when trying to extract text from selected item

I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);

get spinner position and use it in button onclick

I am trying to make app with one text view, one button and one spinner. I make button work showing random values from string array, but i have a lot different string arrays(list1, list2 etc). Now my question is when change spinner position, how to get button get another string array(from spinner) and show it to textview.
How to pass value from spinner when something is selected in spinner to button.
Any help is appreciated.
Here is my code:
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
Button btn;
public String[] myString,myString1;
public static final Random rgenerator = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//textview
final TextView tv = (TextView) findViewById(R.id.textureView);
final Resources res = getResources();
//string
myString = res.getStringArray(R.array.World_War_I);
myString1 = res.getStringArray(R.array.World_War_II);
//button
btn = (Button) findViewById(R.id.buttonxx);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
//i am missing code here, spinner position, and pass spinner position to if statement.
if (==0){
myString = res.getStringArray(R.array.list1);
String q = myString[rgenerator.nextInt(myString.length)];
tv.setText(q);
}
if (==1){
myString1 = res.getStringArray(R.array.list2);
String q1 = myString1[rgenerator.nextInt(myString.length)];
tv.setText(q1);
}
}
});
//drop list
Spinner spinner = (Spinner) findViewById(R.id.spinnerrrr);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.kategorije, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
// when some cat selected
public void onItemSelected(AdapterView<?> parent, View view,
final int pos, long id) {
// An item was selected. You can retrieve the selected item using
parent.getItemAtPosition(pos);
parent.setSelection(0);
parent.getSelectedItemPosition();
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
Use this
// when some cat selected
public void onItemSelected(AdapterView<?> parent, View view,
final int pos, long id) {
// An item was selected. You can retrieve the selected item using
btn.setTag(pos+""); // Passing as string
parent.getItemAtPosition(pos);
parent.setSelection(0);
parent.getSelectedItemPosition();
}
and then
btn.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
//i am missing code here, spinner position, and pass spinner position to if statement.
int index = Integer.parseInt(btn.getTag().toString());
if (index==0){
myString = res.getStringArray(R.array.list1);
String q = myString[rgenerator.nextInt(myString.length)];
tv.setText(q);
}
if (index==1){
myString1 = res.getStringArray(R.array.list2);
String q1 = myString1[rgenerator.nextInt(myString.length)];
tv.setText(q1);
}
}
});

how to display text view without bracket

I have an OnItemClick(), after that I wanted to get the ItemClicked name's and display it in a TextView.I do it normally, but the problem is that I get the ItemClicked name's inside a bracket! How do I avoid this?Here is the output:
{titre=hello}
I want only in my TextView:
hello.
Here is the code:
public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
displayTextViewTitle = (TextView)findViewById(R.id.text_view_title);
Object item = parent.getItemAtPosition(position);
String value = item.toString();
displayTextViewTitle.setText(String.valueOf(value));
}
Try this :
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
TextView item = (TextView) parent.getItemAtPosition(position);
String value = item.getText();
displayTextViewTitle.setText(value);
}
or even better try :
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
ListView lv = (ListView) findViewById(yourListViewName);
String value = lv.get(position).tostring();
displayTextViewTitle.setText(value);
}
If you are getting your String {titre=hello} like this after click on ListView. then you should use this:
String[] no = item.split("=");
String m = no[0];
String k = no[1];
String name = k.substring(0, k.length() - 1);
name is your final result String .
value is already a String, you don't have to use String.valueOf(value).
The listener method works fine, check this:
public class SplashActivity extends Activity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ListView lv = (ListView)findViewById(R.id.lv);
ArrayList<String> members = new ArrayList<String>();
members.add("titre=hello");
members.add("world");
ArrayAdapter s = new ArrayAdapter(this, android.R.layout.simple_list_item_1, members);
lv.setAdapter(s);
lv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
Object item = parent.getItemAtPosition(position);
String value = item.toString();
displayTextViewTitle.setText(String.valueOf(value));
}
}
Recheck the values inside your listview, the problem might be there

Categories

Resources