How do I replace an item in a listview? - android

I have a listview which is populated by an array adpater. A user starts on activity a and after clicking an item in the listview is taken to activity b where they can edit the item they clicked. The edited item from B is sent back to A through an intent after the user returns to A. I want the original item clicked in A to be replaced with the data received from the intent from B.
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
// setListAdapter(adapter);
final ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;
Bundle fromedit = getIntent().getExtras();
if (fromedit != null) {
String edit = fromedit.getString("BENG");
int ps = fromedit.getInt("POSITION");
}
//onclicklistener for the listview
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Notes.this, EditNote.class);
intent.putExtra("KEY", values.get(position).toString());
intent.putExtra("POSITION", position);
startActivity(intent);
}
});
Thanks!

In your original activity you need to keep an int variable referring to the selected item index on the list. So your onItemClick() would look like that:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentSelected = position;
Intent intent = new Intent(Notes.this, EditNote.class);
intent.putExtra("KEY", values.get(position).toString());
intent.putExtra("POSITION", position);
startActivity(intent);
}
When you return from the activity where you modify the data you need to update the item of your values list and call adapter.notifyDataSetChanged().

Have you tried to update your list by calling mList.set(index, Object); and then refreshing the Adapter to update ListView displayed data?

You can use the ArrayList#set() method, thus if your 'values' dataset is an ArrayList.
The java.util.ArrayList.set(int index, E element) replaces the element at the specified position in this list with the specified element.
modify your code as follows:
//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;
Bundle fromedit = getIntent().getExtras();
if (fromedit != null) {
String edit = fromedit.getString("BENG");
int ps = fromedit.getInt("POSITION");
values.set(ps, edit);
adapter.notifyDataSetChanged();
}

Related

SQLite row IDs do not match the ListView row IDs

I have an SQLite database and a ListView displaying in the main activity. In the ListView, I display the details of each list number and upon pressing the list item, a new activity opens up which displays the details in a TextView.
I have a delete function for each of these ListViews and they are not working properly. Essentially, a unique ID is given to each created ListView, which is how the SQLite databases should work. However, upon deleting a row within the ListView, the unique ID increases but the row ID deletes that number and moves everything up. This means that after you delete an item, the row IDs and the database IDs no longer match up and when trying to select an item within the ListView, it crashes. This is an extract from my database adapter class:
public Integer deleteStat(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(STATS_TABLE, "id = ? ", new String[]{Integer.toString(id)});
}
This is my first attempt in the main activity. I got some information from this post but a failed to get the correct integer and received syntax errors:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView pos = (TextView) findViewById(R.id.editTitle);
displayText(Integer.parseInt(pos.getText().toString()));
}
});
}
public void displayText(int pos)
{
pos++;
String s = "";
s += pos;
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtra("id", s);
startActivity(intent);
}
This is my second attempt in the main activity. I used this tutorial to help me. The code I used from that website ruined the entire delete functionality:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int id_To_Search = arg2 + 1;
int id_To_Search = arg0.getCount() - arg2;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
How do I get the database IDs to match up with the row IDs? Any suggestions on how to do that?
EDIT: Added in Hashmap Code. When I press on a ListView Item, nothing happens
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mydb = new StatisticsDbAdapter(this);
ArrayList array_list = mydb.getAllStats();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
/*
New code starts here
*/
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
//means this is the view part not the add contact part
Cursor cursor = mydb.getData(Value);
hashMap.put(cursor.getString(1), cursor.getInt(0));
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int arg2, long arg3) {
TextView textView = (TextView) view.findViewById(R.id.editTitle);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", hashMap.get(textView.getText().toString()));
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
}
}
You should never pass a ListView position to delete a row in a database. I have done that many times before. First of all, within the class you are managing the click events, create a new HashMap. This HashMap will be used to store our row IDs from the database and we'll refer to that rather than the ListView item position. To create it, type this code:
public HashMap<String, Integer> hashMap = new HashMap<>();
Once you have done that, in the function where you display all of the rows in the ListView, you must also load up the same items into the HashMap like this:
hashMap.put(cursor.getString(1), cursor.getInt(0));
Please note that cursor.getString(1) might not be what you used. Please replace the 1 with your appropriate column number that has the name stored within it. cursor.getInt(0) gets the row ID from the database and the column number might be different for you, too. Now, within our OnClickListener function, we can type:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view) {
TextView textView = (TextView) view.findViewById(R.id.editTitle);
Bundle bundle = new Bundle();
bundle.putInt("id", hashMap.get(textView.getText().toString()));
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
Please note that the hashMap variable needs to be within the same class where you manage the click events of your ListView or you will get mistakes. Some of the parametres that you originally passed were removed since you don't need them. Also, I found this to work much better using a RecyclerView but that's now up to you. If you're having problems, please don't hesitate to comment below and I'll try to answer as soon as possible.

App is passing wrong text from list items textview

My app is passing text taken from TextView in list item. I know that text in this text views is right cause I can see that it's ok. Text taken from TextView is pid of photo in MySql database.
My onItemClick code :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (((ImageView) findViewById(R.id.reviewImageView)).getBackground() != null) {
String pid = ((TextView) findViewById(R.id.reviewListPid)).getText().toString();
Intent i = new Intent(getApplicationContext(), photoActivity.class);
i.putExtra("pid", pid);
i.putExtra("database", database_name);
startActivity(i);
}
}
});
I'm sure that text in every list item is right and I can see that text passed to next activity is wrong, cause I can see variable value in log and it's wrong.
Two things:
This won't fix your issue but instead of using getApplicationContext() in your Intent intialization use <YourActivityName>.this instead.
The way you are getting your String is a little unusual, and unnecessary. Most likely, you are loading your adapter for your listview with some sort of array that contains the "pid", correct? So then just get the value from that array in your onItemClickListener callback.
It would look like this:
String[] items = {"..."};
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (((ImageView) findViewById(R.id.reviewImageView)).getBackground() != null) {
String pid = items[position];
Intent i = new Intent(MyActivity.this, photoActivity.class);
i.putExtra("pid", pid);
i.putExtra("database", database_name);
startActivity(i);
}
}
});

How to transfer the clicked item in listview to editText in another activity in android

I want to get the item on list view to edit Text in another activity.
When clicked on list view item, I want to transfer the item in another activity in edit Text.
You have to make onItemClickListner of listview like that.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
}
});
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
And finally set Value to editText like this
editText.setText(value);
Hope this will help you.
lstView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("text", text want to transfer);
startActivity(intent);
}
});
You can make use of SharedPreferences. And when you pass the content of the ListView to the next activity, you can use editText.setText("Your Text").
You can also pass your data through intents from which you are calling your new activity.
create onClick method like this.
ListView list = (ListView) findViewById(R.id.newsList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long offset) {
NewsItem item = (NewsItem) adapter.getItem(position);
Intent intent = new Intent(getApplicationContext(), NewsDetailsActivity.class);
intent.putExtra(KEY, item.getHeadline());
startActivity(intent);
}
});
In next activity
Intent intent = getIntent();
headline = intent.getStringExtra(KEY);
have a look here

Passing a variable from a listview to another activity

I have been struggling using some tutorial for passing a listview option to a new activity and make it the title (I will do other stuff with it later). I have set up a OnClickListener by what is best to put inside it
ListView listView1 = (ListView) findViewById(R.id.sportslist);
String[] items = { "Archery", "Badminton", "Cricket", "Dodgeball", "Equestrian", "Football", "Golf", "Handball", "Ice Hockey", "Ju Jitsu", "Karate", "Lacrosse", "Mountain Biking", "Netball" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
?????
}
});
Thanks
EDIT:Extra code
final TextView changetitle = (TextView) findViewById(R.id.detailedsocietyname);
changetitle.setText(name);
For of all you will need to get the item that was selected:
final String selected = items[position];
Or as doctoror drive has suggested
final String selected = (String) parent.getSelectedItem();
Then you will need to pass that string as an extra to your new activity
Intent i = new Intent(getApplicationContext(), MyClass.class);
i.putExtra("name", selected);
startActivity (i);
And then finally in your next activity
Intent in = getIntent();
String name = in.getStringExtra(("name"));//gets name from intent
public void onItemClick(AdapterView parent, View view,int position, long id)
String str = items[position];
Intent in = new Intent(getApplicationContext(), NextClass.class);
in.putExtra("itemkey", str);
startActivity (in);
}
in public void onItemClick(AdapterView<?> parent, View view,int position, long id) add this code.
Intent i = new Intent(getApplicationContext(), NextClass.class);
i.putExtra("selectedItem", items[position]);
startActivity (i);
for getting value in NextClass Activitiy :
String SelectedItem = getIntent().getStringExtra("selectedItem");
Add the following to you Activity where you have listview
following is the variable that will contain the value that you want to pass to other activity
Declare it before Oncreate statement
// Activity_1
public final static String send_to_other_activity="ListViewSelected_ID";
Add the following code to the listView1.setOnItemClickListener
Intent i= new Intent(Recipe_List.this,Recipe_View.class);
i.putExtra(send_to_other_activity, string.valueof(position));
// itz (key-value) pair on the left key thru which u will access it on other place. on the right value that you want to pass
// Iam passing posiion to other activity here
startActivity(i);
Now on other activity extract this value from the key by adding following statement to the oonCreate of other activity
//Activity_2
getdata_from_list =getIntent().getStringExtra(Activity_1.send_to_other_activity);
now you have teh desired value in getdata_from_list

How to interact with Android ListView

I have created a ListView where I have to add different items. Now, when I click on a particular item it displays another window. On that window, I want to display the name of that item which I click on the ListView.
My code:
private ListView contactList;
private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.contact_activity);
contactList=(ListView)findViewById(R.id.ListView01);
contactList.setAdapter(new ArrayAdapter<String (this,android.R.layout.simple_list_item_1 , lv_arr));
contactList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/*Intent myIntent = new Intent(view.getContext(), CallActivity.class);
startActivity(myIntent);*/
}
});
}
you have to get the name of the item on itemclick event. pass it to the activity which will be called. in in the calling activity get the name of item and display
contactList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selecteditem = lv_arr[position];
Intent myIntent = new Intent(view.getContext(), CallActivity.class);
intent.putExtra("item", selecteditem);
startActivity(myIntent);
}
});
In CallActivity.java
write the following to get the selected item name
String selectedItem=getIntent().getStringExtra("item");
Instead of starting a new activity, use AlertDialog. You already have the position of the list item clicked. So displaying it on the dialog shouldn't be a problem if you follow the article linked.
EDIT :
As per your requirement, you have to launch a new activity to display a string
In the sending list activity
intent.putExtra(String key, String value)
In receiving activity,
String value = getIntent().getStringExtra(key);

Categories

Resources