How to send data from one activity to another listview? - android

Hey guys I'm working on an app in android studio. I have a listview and when I make a selection i would like to add that selection to another listview in a different activity. What is the easiest/best way to do this? I've tried putExtra without any luck. Any examples or ideas would be great. Thank you guys.
Thanks for the examples everyone they've helped me understand a lot better the intent system. I've been trying the different examples everyone has posted and I've kind of gotten stuck. The goal is simply to have the items I select from the listview in the Walmart.java file to show up in the listview in GiftsSelected.java I have another place to open the activity so I don't need it to immediately open the new activity.
Here is my code:
This is Walmart.java
public class Walmart extends ActionBarActivity {
private String[]giftarray = {
"Apple" ,
"Bananas",
"Bed",
"Beef",
"Bottle",
"Bread",
"Broccoli",
"Carrots",
"Cat",
"Chicken",
"Chocolate",
"Computer",
"Cow",
"Crow",
"Dog",
"Dolphin",
"Dove",
"Drawer",
"Egg",
"Fish",
"Fork",
"Fridge",
"Giraffe",
};
Intent a = new Intent(Walmart.this,GiftsSelected.class);
private ListView giftListView;
private ArrayAdapter arrayAdapter;
ArrayList<String> list = new ArrayList<String>();
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){}
public boolean onContextItemSelected(MenuItem item){
return true;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walmart);
getSupportActionBar().hide();
giftListView = (ListView) findViewById(R.id.gift_list1);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_gallery_item, giftarray );
giftListView.setAdapter(arrayAdapter);
giftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = "Item added to registry";
list.add(item2);
a.putStringArrayListExtra("list",list);
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
This is my GiftsSelected.java code:
public class GiftsSelected extends ActionBarActivity {
private ListView giftListView;
private ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
ArrayList<String> list = new ArrayList<String>();
//This makes my app crash which makes me think I did this wrong...
list = getIntent().getStringArrayListExtra("list");
String[] giftarray = new String[list.size()];
list.toArray(giftarray);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gifts_selected);
getSupportActionBar().hide();
giftListView = (ListView) findViewById(R.id.gift_list1);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_gallery_item, giftarray);
giftListView.setAdapter(arrayAdapter);
giftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = "Item added to your registry";
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}

this is the list that i use
ArrayList<String> list = new ArrayList<String>();
add elements in it like this
list.add("something");
in first Activity
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
i.putStringArrayListExtra("list",list);
startActivity(i);
in the second activity in the onCreate
list = getIntent().getStringArrayListExtra("list");

Let's say the first Activity is X and X holds a listview that updates another listview in Activity Y.
If X is tightly related to Y, that is to say Y launches X, gets data then immediately returns to Y, then you should use startActivityForResult from Y.
class ActivityY {
public static final int REQUEST_CODE = 2;
...
Intent i = new Intent(this, ActivityX.class);
startActivityForResult(i, REQUEST_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String returndata = data.getStringExtra("rowdata");
//update your listView, do notifyDataSetChanged() etc;
}
}
}
}
class ActivityX {
// in listview onItemClickListener or elsewhere that listens to row click
Intent intent = new Intent();
returnIntent.putExtra("rowdata", rowdata); // whatever data you need to transfer
setResult(RESULT_OK,intent);
finish();
}
If X and Y are loosely related, that is to say X is not necessarily launched from Y, but goes to Y then you should just use the usual startActivity(intent).
if X and Y are completely independent, that is to say X is not necessarily launched from Y, may not go to Y or wanders other Activities before arriving in Y then you should cache the data. If the data size is small then the best way is to store it in Preferences. When you Y Activity starts, get the data, update your ListView, then if needed remove the cached data from Preferences.

a)You can make the listview item object parcelable and send it between activities via intent extra.
b)You can save the selected listview item in a global variable.(Not recommended)

Related

how can i receive intent on 2 activities?

I want to receive intent on the two activity classes, but not sure how since startActivity can only start one intent to only one activity class
private void populateListView()
{
Log.d(TAG, "Populating listview");
Cursor data = dbManager.getTitle();
final ArrayList<String> listTitle = new ArrayList<>();
while (data.moveToNext())
{
listTitle.add(data.getString(1));
}
final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listTitle);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
String name = adapterView.getItemAtPosition(position).toString();
Cursor data = dbManager.getTitleID(name);
int titleID = -1;
while (data.moveToNext())
{
titleID = data.getInt(0);
}
if (titleID > -1)
{
Intent intent= new Intent(List_Title_Activity.this, MainActivity.class);
//Intent intent2= new Intent(List_Title_Activity.this, ViewListContents.class);
intent.putExtra("id", titleID);
intent.putExtra("title", name);
startActivity(edit);
}
else
{
Toast.makeText(List_Title_Activity.this, "No id associated with that name", Toast.LENGTH_SHORT).show();
}
}
});
MainActivity and ViewListContent:
Intent receiveIntent = getIntent();
selectedID = receiveIntent.getIntExtra("id",-1);
1 Activity is 1 page in android. That is, you can call/view 1 page/Activity at a time. If you want to share same data to multiple pages in use shared preference / Database. Or if you are using 1 activity and multiple fragments in it, use interface.
if you want to send data from one activity to 2nd activity you can use simple intent and pass data from first activity to second . But if you want to send the data first activity to second and get data from second activity to first activity i suggest you to use startActivityForResult. for more see here

Android studio: ListView to Tabbed Activity, save ratingbar rating on the tab pages

I'm making my first android app using android studio. In this APP I have a listview with 12 classes(12 items). After clicking on one class, it goes into a tabbed activity with 10 items of this class. On each tab page I have a rating bar to let people rate the item.
I set an activity for the listview, and 12 independent activities for those 12 tabbed activities. The code from listview to each tabbed activity is like this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0){
Intent intent = new Intent(ListViewActivity.this, TabbedActivity1.class);
intent.putExtra("styleName", STYLE_NAMES[i]);
intent.putExtra("styleExample",STYLE_EXAMPLES[i]);
startActivity(intent);
}
else if(i==1){
Intent intent = new Intent(ListViewActivity.this, TabbedActivity2.class);
intent.putExtra("styleName", STYLE_NAMES[i]);
intent.putExtra("styleExample",STYLE_EXAMPLES[i]);
startActivity(intent);
}
...... // skip the other 10 tabbed activities.
}
Now the problem is: after I finish rating on the tabbed activities, I return to the ListView activity and click into each tabbed activity again, the ratings are gone.
I guess the reason is that in my code, each time I click on the item it opens a new tabbed activity, although same layout, the contents are not saved.
So I was wondering whether I should do something on the ListView activity to save the ratings. I have searched for relevant questions, but I found in their scenarios, each list item is just a simple ratingbar. But here, my list item is a tabbed activity with 10 ratingbars.
Therefore, I have no idea how to do it. I have no experience in android studio, so I don't know where to start to solve the problem. Any idea is appreciated! Thanks a lot in advance!!
First of all if all your tab activities are similar you can just create one activity instead of that many in your case 12 and pass the specific content and states via intent.
The basic approach to your question is would be store rating states in your main activity and when you open your tab activity each time you click the list items send the rate of the relevant activity with intent. Then in your tab activity update the rate with it.
To achieve this we are going to use startActivityForResult instead of startActivity because we need tab activity to return last state of rating bars.
You can see the basic example shown below here:
public class ListViewActivity extends AppCompatActivity {
private static final int REQUEST_RATE = 1;
private SparseIntArray rates = new SparseIntArray();
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(ListViewActivity.this, TabActivity.class);
intent.putExtra("styleName", STYLE_NAMES[i]);
intent.putExtra("styleExample", STYLE_EXAMPLES[i]);
intent.putExtra("position", i);
intent.putExtra("rating", rates.get(i, 0));
startActivityForResult(intent, REQUEST_RATE);
}
}
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_RATE:
if(resultCode == RESULT_OK) {
//retrieve and save rates
Bundle extras = data.getExtras();
int position = extras.getInt("position");
int rating = extras.getInt("rating");
rates.put(position, rating);
}
break;
}
}
}
public class TabActivity extends AppCompatActivity {
private RatingBar ratingBar;
private int position;
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Bundle extras = getIntent().getExtras();
position = extras.getInt("position");
int rating = extras.getInt("rating");
ratingBar.setRating(rating);
}
#Override protected void onDestroy() {
//send current rating to list activity before we leave
setResult();
super.onDestroy();
}
private void setResult() {
Intent intent = new Intent();
intent.putExtra("position", position);
intent.putExtra("rating", ratingBar.getRating());
setResult(RESULT_OK, intent);
}
}

Replacing, updating, and saving text file for ListView Android

I am trying to update my ListView text file by replacing the word I just edited from returning from a Second Activity. Currently the output I am getting is a Toast of the word I just edited in the variable name in my onActivityResult().
How my app works.
Tap on item in ListView
Opens to Activity 2 with tapped item in EditText
edit the item and press save to return to first activity
edited item returns in variable name and is displayed in popup (toast)
I want to replace the item I just edited with the old item and save it so then when I reopen the app, the updated/edited item is in place of the old item.
I feel as though I have the parts to complete this but I am just starting on android development so I taking quite a while to figure this out. I was wondering if someone could lead me in the right direction.
Here is my Activity:
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
private final int REQUEST_CODE = 20;
//private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
//onActivityResult(REQUEST_CODE, RESULT_OK, );
}
private void launchEditItem(String item) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", item); // list item into edit text
startActivityForResult(i, REQUEST_CODE);
//startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
String text = (String) lvItems.getItemAtPosition(pos);
launchEditItem(text);
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("EditedItem");
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
//writeItems();
}
}
}
If needed, I'll post my second Activity as well but I don't think it is necessary. However ask and you shall receive!
The solution you came up with is a bit basic and really limits you if it goes about resolving problem you mentioned. What I mean is that the Adapter you're using for your ListView consists only of simple ArrayList<String>, which prevents you from knowing which element is name you're looking for.
Better solution would be to create your own Adapter where each element would have a special key or something, but I'm afraid it's a bit too complicated for you for now. Keep in mind that it's possible and often very useful to create custom Adapters though.
What I thought could be possible in your case is a little hack maybe, but it works ONLY if you're totally sure that name is always stored at n-th position, let's say at 10th position.
Then you can do this:
private final int NAME_POSITION = 10;
Now that you have this position, you should find 10th line in your file, erase it and store new value. I won't be writing this code, because it's not really related to this question. There is a lot of questions about file reading/writing in Java on Stackoverflow that you should easily find the solution if you don't know how to do it yet. Basically you have to put this in this place:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("EditedItem");
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
// Write your name to file now
}
}
The second approach would be to forget about files and use SharedPreferences for the updated name:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("EditedItem");
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
SharedPrefrences sp = getSharedPreferences("MySavedValues", 0); // Open SharedPreferences with name MySavedValues
Editor editor = sp.edit();
editor.putString("Name", name); // Store name with key "Name". This key will be then used to retrieve data.
editor.commit();
}
}
and in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
SharedPreferences sp = getSharedPreferences("MySavedValues", 0); // Open SharedPreferences with name MySavedValues
String name = sp.getString("Name", ""); // If there isn't any string stored with key "Name", it will return empty string
if(!name.isEmpty()) {
todoItems.set(NAME_POSITION, name);
}
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
//onActivityResult(REQUEST_CODE, RESULT_OK, );
}
I haven't tested it, so you have to do it yourself. Also if you find my answer a bit complicated, feel free to ask about anything.

Activity missing data on return

So I have my main activity which holds a list view and has a map which holds all my data for the list. Upon clicking on an item you are taken to a details display. When I press the back button to get back to the main activity from the detail activity, if I set a break point, my map keys are still intact, but all the strings in the objects are "" and the ints are -1. Here is what my main activity looks like:
public class MainActivity extends Activity {
private Map<String, Stunt> stunts = new LinkedHashMap<String, Stunt>();
private StuntsDao stuntsDao;
private ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stuntsDao = new StuntsDao(getApplicationContext());
stunts = stuntsDao.getAllStunts();
listAdapter = new ListAdapter(this, R.layout.list_layout, new ArrayList<Stunt>(stunts.values()));
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String stuntName = (String)((ViewHolder)view.getTag()).stuntName.getText();
Intent myIntent = new Intent(getApplicationContext(), StuntDetails.class);
getStuntDetailsIfNeeded(stuntName);
Stunt stunt = stunts.get(stuntName);
myIntent.putExtra("STUNT", stunt);
startActivity(myIntent);
}
});
}
...
}
Why would the objects in my map be basically empty?
onCreate() doesn't get called when you click back. You need to init your data again in onStart or onResume. See: http://developer.android.com/training/basics/activity-lifecycle/starting.html

Refresh ListView after updating in another Activity

I have two simple Activities -
Activity1: ListView from an Array
Activity2: EditText for editing the clicked row in Activity1
When I edit the value in Activity2 and returning to Activity1, the ListView doesn't reload the new value.
I want to refresh the ListView when I return from Activity2 or resume Activity1 or something that will update the list.
My code:
static ArrayAdapter<String> dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Loading the values to list array
String[][] fulllist = loadArrays();
String[] list = new String[fulllist.length];
for(int i = 0; i<fulllist.length; i++) {
list[i] = fulllist[i][1];
}
// --------------------------------
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
list);
setListAdapter(dataAdapter);
}
#Override
public void onResume() {
super.onResume();
// Loading the values to list array
String[][] fulllist = loadArrays();
String[] list = new String[fulllist.length];
for(int i = 0; i<fulllist.length; i++) {
list[i] = fulllist[i][1];
}
// --------------------------------
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
list);
dataAdapter.notifyDataSetChanged();
}
loadArrays() is just method that converts from SharedPreferences to String Array. Activity2 saves the new data in SharedPreferences and than Activity1 can read it (with the new data).
If I return to the "main activity" (it is not Activity1) and than come back to Activity1 - the new data is shown, but I want this data will be updated when I return from Activity2 immediately.
loadArrays() method: pastebin.com/MHwNC0jK
Thanking you in advance!
On clicking the item in your first Activity, start your second Activity with startActivityForResult()
And then in Second Activity, after entering in EditText, probably there is a button. And in onClick of that button call,
intent.putExtra("edittextvalue", findViewById(R.id.edittext).getText().toString());
setResult(RESULT_OK, intent);
finish();
Now you come back to your first Activity and here you have to implement onActivityResult() callback. You can extract data from that intent's extras and set that respective item in your array and call notifyDataSetChanged().
This is ideally how you should be doing it.
If you want more info on how to use startActivityForResult() try this link - http://manisivapuram.blogspot.in/2011/06/how-to-use-startactivityforresult.html
1) Get reference ListView
mListView = (ListView)findViewById(R.id.auto_listview);
2) Create adapter One more time with changed values
MyAdapter myAdapter = new MyAdapter(getApplicationContext(),
R.layout.locations_list_item_layout,dataArray;
mListView.setAdapter(myAdapter);
setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int i, long l) {
myAdapter = new MyAdapter(getApplicationContext(),
//pass changed values vlues array R.layout.locations_list_item_layout,dataArray;
mListView.setAdapter(myAdapter);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Declare fulllist as Globle Variable and used static arraylist .

Categories

Resources