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?
Related
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
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);
}
});
I created a listview using an adapter. the listview contains the distinct values of a particular field in a table. now,when the listview item is clicked, it should retrieve all items which have the id of that particular data. i manage to get the data from the listview but when the items are not fetched properly.
row.xml
<ImageView
android:id="#+id/img"
android:src="#mipmap/ic_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txtid"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sd"
/>
Tab2.java
ListView list;
final ArrayList<HashMap<String, String>> mylist;
ListAdapter adapter;
HashMap<String, String> map2;
final TextView a1;
list = (ListView) v.findViewById(R.id.listView2);
a1 = (TextView) v.findViewById(R.id.txt1);
mylist = new ArrayList<HashMap<String, String>>();
DatabaseHandler db = new DatabaseHandler(getActivity());
final List<Product> sent = db.getSentProducts();
for (Product s : sent) {
map2 = new HashMap<String, String>();
map2.put("txtid", s.getMsg_id());
mylist.add(map2);
Log.d("msgid", s.getMsg_id());
}
for (Product s : sent) {
}
try {
adapter = new SimpleAdapter(getActivity(),mylist,R.layout.sent_row, new String[]{"txtid"}, new int[]{R.id.txtid});
list.setAdapter(adapter);
} catch (Exception e) {
}
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView a = (TextView)v.findViewById(R.id.txtid);
String content1 = a.getText().toString();
DatabaseHandler db = new DatabaseHandler(getActivity());
List<Product> sentinfo = db.getSentProductInfo(content1);
for (Product si : sentinfo){
Log.d("asdsd", si.getStorCode()+" "+si.getCode()+" "+si.getBstock()+" "+si.getDeliveries()+" "+si.getSpoilage()+" "+ si.getEstock()+" ");
}
return true;
}
});
return v;
}
db
android ui
When i click 20150824070159 in the listview, it should fetch two rows in the table, however, it only fetches one and it is the data of the other id, 20150820162104.
How will i be able to answer this?
To get the text from the item clicked on the list view you should do this:
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String clickedText = list.getItemAtPosition(position).toString();
}
});
Just make sure that your list variable is declared on the global scope, outside of any method, because this function will be called after the onCreate or any other method has already ended.
I've populated a Listview, adapting data from database. And of course per list item have same layout. Inside this layout there are some buttons, checkboxs and other widgets.
Now I want to set onClickListenser. How to achieve that?
Here is the overview:
What I have:
private void populateListView(){
DatabaseHandler db = new DatabaseHandler(this);
Cursor alarms = db.getAllAlarms();
startManagingCursor(alarms);
String[] time = new String[]{DatabaseHandler.KEY_TIME};
int[] toViewIDs = new int[]{R.id.timeTitle};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.per_alarm_activity,
alarms,
time,
toViewIDs
);
ListView listView = (ListView) findViewById(R.id.allAlarmsView);
listView.setAdapter(adapter);
mTimeView = (TextView) findViewById(R.id.timeTitle);
mAmPmTextView = (TextView) findViewById(R.id.amPmTextView);
mAlarmOnOff = (Switch) findViewById(R.id.alarmOnOff);
mRepeatCheck = (CheckBox) findViewById(R.id.repeatCheckBox);
mDrop = (ImageView) findViewById(R.id.arrowDown);
mUp = (ImageView) findViewById(R.id.arrowUp);
}
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
CheckBox mRepeatCheck =((CheckBox)view.findViewById(R.id.repeatCheckBox));
//same code goes for othe buttons, imageview etc
}
});
I managed to show a list from sqllite, now I want that when the user click on the item, the item will be deleted. the problem is that the item's ID number from the sql is different from the listview's ID. so how can I delete the selected item?
I mean this id:
public void onItemClick(AdapterView parent, View view,int position, long id)
is different from the item's ID from the sqllite.
thank you for help
Cursor resultSet = db.rawQuery("Select * from list ORDER BY `ID` DESC",null);
resultSet.moveToFirst();
final ListView listview = (ListView) findViewById(R.id.listView1);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnames = new String[] {"C1", "C2", "C3"};
int[] columnsR = new int[] {R.id.column1, R.id.column2, R.id.column3};
int x=0;
while(resultSet.moveToNext()){
HashMap<String,String> map = new HashMap<String, String>();
String d_weight = resultSet.getString(resultSet.getColumnIndex("weight"));
String d_date = resultSet.getString(resultSet.getColumnIndex("date"));
String d_id = resultSet.getString(resultSet.getColumnIndex("ID"));
x=0;
map.put(columnames[x],d_weight);
x++;
map.put(columnames[x],d_date);
x++;
map.put(columnames[x],d_id);
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(this, mylistData, R.layout.row,columnames , columnsR);
listview.setAdapter(arrayAdapter);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// how to delete? =[
}});
Would it not be easier to make an object that you fill with the data from your sql query for each entry? Then you just populate the listview with a list of these objects, which means that when one of the objects get clicked on the id will be stored inside the object. Then int position would have the same value as the position in your list of objects.
How does that sound?