Transfer two listview data on click of one listview - android

In my activity I have two listviews with some data. On first listview selected row will be highlighted on click and on click on 2nd listview new activity starts.
I want to send the highlighted row data of first listview and clicked row of 2nd listview data on next activity. How can Iachieve that?

supposing your lists are named list1 & list2, add to your list2 onItemClickListener that should looks something like this :
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
String highlightedItem = (String)list1.getSelectedItem();
String clickedItem = (String)list2.getItemAtPosition(position);
Intent intent = new Intent(FirstAcivity.this, SecondActivity.class);
intent.putExtra("highlightedItem", highlightedItem);
intent.putExtra("clickedItem", clickedItem);
startActivity(intent);
}
and then in your Second Activity you can receive the items like this :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
if (intent != null){
String highlightedItem = intent.getStringExtra("highlightedItem");
String clickedItem = intent.getStringExtra("clickedItem");
}
}
I have assumed your list items are of type String but you can apply the same logic for any other type.
In case your want to send object not just primitives you need to make your objects implements Serializable or Parcelable interface.

Related

New arraylist item overwrites previous listview item

Currently I'm trying to send intent data from user input to display onto my custom adapter. The intent data from user input from the detailspage.java class will be sent to the listview page with custom Arrayadapter. However each time i add a new item it overwrites my previous entries. Hope some kind souls can help someone new to android.
Below are snippets of my code.
// Set a click listener on that button
btnAddData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveExercise(exerciseName);
}
});
}
private void saveExercise(String name) {
// Read from input fields
// Use trim to eliminate leading or trailing white space
String setString = mSetEditText.getText().toString().trim();
String repString = mRepEditText.getText().toString().trim();
String nameString = name;
Intent intent = new Intent(ExerciseDetailActivity.this, WorkoutSetActivity.class);
intent.putExtra("name", nameString);
intent.putExtra("set", setString);
intent.putExtra("rep", repString);
startActivity(intent);
}
The intent data will be sent to the activity page to initiate the custom ArrayAdapter.
public class WorkoutSetActivity extends AppCompatActivity {
ArrayList<WorkoutSet> workout = new ArrayList<WorkoutSet>();
/** Adapter for the ListView */
WorkoutSetAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise_list);
adapter = new WorkoutSetAdapter(this, workout);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
Intent intent = this.getIntent();
String name = intent.getExtras().getString("name");
String set = intent.getExtras().getString("set");
String rep = intent.getExtras().getString("rep");
adapter.add(new WorkoutSet(name,set,rep));
Toast.makeText(WorkoutSetActivity.this, "Workout added.", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
Lastly the custom ArrayAdapter code. This is where I set the custom listview.
public class WorkoutSetAdapter extends ArrayAdapter<WorkoutSet> {
public WorkoutSetAdapter(Activity context, ArrayList<WorkoutSet> workout) {
super(context, 0, workout);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.activity_workout_set, parent, false);
}
WorkoutSet currentWorkout = getItem(position);
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) listItemView.findViewById(R.id.workout_name);
TextView setTextView = (TextView) listItemView.findViewById(R.id.workout_set);
TextView repTextView = (TextView) listItemView.findViewById(R.id.workout_rep);
nameTextView.setText(currentWorkout.getName());
setTextView.setText("Sets: "+ currentWorkout.getSet());
repTextView.setText("Reps: "+ currentWorkout.getRep());
return listItemView;
}
}
each time i add a new item it overwrites my previous entries
There are no "previous entries". startActivity loads an empty adapter each time and you only add one element.
What you want is a SQLite database (or any persistent storage layer, but SQLite is provided without more libraries).
On the plus side, your Intent and Adapter code look fine.
Every time,you call startActivity (), you open a new WorkoutSetActivity, it's a new WorkoutSetActivity object instance, so the arrayAdapter is also new one, it will only display the data you send this time.
If you want to display all the data, you must save the previous data to database or file. At WorkoutSetActivity onCreate (), you should get the previous data, put them and current data to the adapter.

ListView item gets destroyed while moving to other activity

My first activity contains a listview with textviews in each cell and uses a custom adapter. So if you click on any of the items, it will open up a form activity containing textfields. The user can fill up the details and once they press the save form button the details appear on the listview. Now I am trying to add items to the list dynamically. I have created a button which when clicked adds a new instance item so that more users can register the same way. I have been able to implement these functions. However, my problem now is when i click on the newly added item and go to the form activity and click save, i am not able to see the newly added entry after i come back to the listview activity.All I see is the first entry alone. So i am guessing it gets destroyed as soon as i leave the activity. How to ensure all newly added items are not destroyed when i keep moving between these two activities.
Here is my code of the ListView Activity:
public class FormTableActivity extends Activity {
private PassengerListAdapter adapter;
Button add_passenger;
String mrzdata,ic_data,name_data;
SharedPreferences nPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final_display_listview);
nPref = PreferenceManager.getDefaultSharedPreferences(this);
mrzdata = nPref.getString("MRZ", "");
name_data = nPref.getString("resultData", "");
ic_data = nPref.getString("icdata", "");
final ListView lv1 = (ListView) findViewById(R.id.custom_list);
adapter = new PassengerListAdapter(this);
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
add_passenger = (Button) findViewById(R.id.add_user);
add_passenger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// mrzdata = "";
// name_data = "";
// ic_data = "";
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
}
});
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent intent = new Intent(v.getContext(), FirstActivity.class);
startActivity(intent);
}
});
}
The easiest way to pass data between Intent is
Intent intent = new Intent(getBaseContext(), your_list_view_activity.class);
intent.putExtra("String_Key", data1);
//data1 could be an array of string where you have hold the values previously
startActivity(intent);
now on your list_view_activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String [] value = extras.getString("String_Key");
}
This way you won't get any exception but you get to populate your listView if there is data.
Another way to get data is via SharedPreference but I won't recommend it as it increases the size of the app.
You have to save these newly added items somewhere , e.g. to a SQLite database and retrieve them on create to populate the listview
You can see here if You want, the code is commented ,
here I have a listview with custom adapter with two items
the feed's name and it's url
i add URL and name using a text input dialog (with two edit text), save to DB, and retrieve them on create to populate the listview
https://github.com/enricocid/iven-feed-reader/blob/master-as/project/app/src/main/java/com/iven/lfflfeedreader/mainact/ListActivity.java

Listview and data

I have a ListView where I have some elements. Every item has one ListViewand two TextBoxes. Here is my question: When I clock on element from the list a new activity starts, where I have one ListView and two TextBoxes. How I can do this if I click first element in the new activity in ListView will be ListViewfrom this item and in TextBoxeswill be data from TextBoxes from the list.
You can pass extras to the Intent you use when starting the new Activity.
Let's say your current activity is MyActivity, and the one you want to start by clicking on a list item is MyNewActivity; Then in your MyActivity class, inside the list item click listener should be modified as:
Intent intent = new Intent(MyActivity.this, MyNewActivity.class);
intent.putExtra("my.picture.id", images[itemPosition]);
intent.putExtra("my.header.id", headers[itemPosition]);
intent.putExtra("my.text.id", texts[itemPosition]);
startActivity(intent);
and in your MyNewActivity class' onCreate method you are able to retrieve the passed extras, and fill the proper fields with the correct values:
final Intent intent = getIntent();
final int pictureId = intent.getIntExtra("my.picture.id", 0);
final int headerId = intent.getIntExtra("my.header.id", 0);
final int textId = intent.getIntExtra("my.text.id", 0);
((ImageView)findViewById(R.id.my_image)).setImageResource(pictureId);
((TextView)findViewById(R.id.my_header)).setText(headerId);
((TextView)findViewById(R.id.my_text)).setImageResource(textId);
the images, headers and texts arrays -I suppose- contain the resource ids for the images and strings you want to display. They are probably accessible via the data of your current item's renderer.
I would go about it a bit differently (in retrieving the information at least) than rekaszeru.
In your first activity you would use onListItemClick and put the information into the extras bundle to be passed with the intent to start the second activity. In this method, you use the view passed in to retrieve the info, so it doesn't matter what kind of adapter you are using and the position in the adapter doesn't matter.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent myIntent = new Intent(FirstClass.this, SecondClass.class);
myIntent.putExtra("ImageRef", v.findViewById(R.id.imageview)).getTag());
myIntent.putExtra("Text1", v.findViewById(R.id.TextView1).getText().toString());
myIntent.putExtra("Text2", v.findViewById(R.id.TextView2).getText().toString());
FirstClass.this.startActivity(myIntent);
}
Then in the second activity retrieve the info to be used:
private TextView NewTextView1;
private TextView NewTextView2;
private ImageViewView NewImageView;
Bundle extras = getIntent().getExtras();
NewTextView1 = (TextView)findViewBYId(R.id.newtextview1).setText(extras.getString("Text1"));
NewTextView2 = (TextView)findViewBYId(R.id.newtextview2).setText(extras.getString("Text2"));
NewImageView = (ImageView)findViewBYId(R.id.newimageview).setImageResource(extras.getInt("ImageRef"));

Passing listView row positions through Intents to another class

I'm wondering how to pass a row position(pos) value from, say, a CHOICE_MODE_SINGLE list Activity(A) to another Activity(B) using Intents? (I want to change ActivityB to show another list depending on what row in ActivityA is clicked). Here's my code:
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(
new android.widget.AdapterView.OnItemClickListener(){
#Override
public final void onItemClick(AdapterView<?> listView, View cell, int position, long id) {
Intent Courses = new Intent(this, ExpandableList.class);
Courses.putExtra(//I'm not sure what to put in here//)
});
private static final String[] GENRES = new String[] {"Barre","Buffumville","Hodges","Newton Hill"};
}
THANKS :)
Courses.putExtra("position",position);
Then to get the position in the next activity:
getIntent.getExtras().getInt("position");
You can pass the position through the intent putExtra.
please see below Code.
Intent Courses = new Intent(this, ExpandableList.class);
Courses.putExtra("position",position)
startActivity(Courses);
Now you can get this value in another activity like this.
getIntent.getExtras().getInt("position");
It will return the integer position you passed from the first activity.

How to view detailed data of a specific list view item

Let's say i have a list of cities from a country.
If the user clicks one of them, i want a new screen to be displayed, with the detailed infos for that list element.
Also, that screen will have others buttons ( eg: Write Review, Post Picture )
How can i achieve this ?
The City class should implement Parcelable. Its toString() method should return the name of the city. (Rather than simply having the city as a String.)
When you populate your ListView, use an ArrayAdapter<City> instead of an ArrayAdapter<String> (this code assumes that the cities are kept in List<City> list):
City[] cities = new City[list.size()];
list.toArray(cities);
mListView = (ListView) findViewById(R.id.citylist);
mListView.setAdapter(new ArrayAdapter<City>(this,
R.layout.listitem, cities));
In your onItemClick handler, get the selected city and add it as an extra on the intent you use to launch your details activity:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a,
View v, int position, long id) {
City city = (City) a.getItemAtPosition(position);
Intent intent = new Intent(v.getContext(), DetailsActivity.class);
intent.putExtra("com.example.cities.City", city);
startActivity(intent);
}
});
In your details activity, get the city from the extras on the intent:
Bundle bundle = getIntent().getExtras();
City city = bundle.getParcelable("com.example.cities.City");

Categories

Resources