How to pass arrays to a subactivity (android)? - android

My program is basically a list of items, and when you click the items it sends you to an expandable list. The problem is, my list of items is hundreds of items long, so it becomes tedious to have to make a different expandable list class for each one. Instead, I want to send different arrays to one subactivity depending on which list option was pressed.
Here's the part of my code in my main activity that is supposed to send the info:
if ((String) ((TextView) view).getText() == "Name of List Item") {
Intent myIntent = new Intent(view.getContext(),
SubActivity.class);
myIntent.putExtra("parents", new String[] { "bunch of parents" });
myIntent.putExtra("children", new String[][] {
{ "bunch" },
{ "of" },
{ "children"} });
startActivityForResult(myIntent, 0); }
Here's the part of my code that is supposed to receive it:
String[] parents; //declared outside onCreate() so they can be used by methods like createParentList()
String[][] children;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = this.getIntent().getExtras();
moves = b.getStringArray("parents");
parents = (String[][]) b.getSerializable("children");
I go on to try to use createParentList()/createChildList(), etc for my expandable list. It compiles perfectly fine. However, whenever I run it and try to click on the list item, it says that the process has stopped unexpectedly. Does anyone know what is wrong?

i think you should see http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/ ,or Transferring object data from one activity to another activity .you should do yourself Serializable

Related

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

Displaying updated ArrayList items properly within a fragment

basically my problem is this. I am trying to display a list view within a fragment set within the xml file, this list view gets its data from an ArrayList that gets its data from a form I created in another activity using Edit Texts which are put into an ArrayList and passed as a Parcelable Array List to the fragment class.
At the start of the fragment activity there of course are no values stored so I bring up the form activity for data input upon checking that there is no intent stored with the id I specify the passed Parcelable ArrayList as. The problem I have is that whenever I try populate the list view with more than one item (having the first item showing up, returning to the form to add another item in), it seems to only display the one item I add each time and not the items I added previously.
public class MasterFragment extends ListFragment {
private DetailFragment ingredDetails;
private ArrayList<Ingrediants> ingredList = new ArrayList<Ingrediants>();
private ArrayList<String> test2 = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getActivity().getIntent();
Bundle extras = intent.getExtras();
if (extras != null) { //If extras are present
boolean data = extras.getBoolean("ingrediant", true);
if (data) {//Data present from form, retrieve from ArrayList<Ingrediants> and populate the ArrayList<String>
ingredList = getActivity().getIntent().getParcelableArrayListExtra("ingrediant");
test2.add(ingredList.get(i).ingrediantName);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, test2));
}//END OF IF DATA
}//END OF IF EXTRAS
else {//No data found, bring up the FormActivity
Intent intent3 = new Intent(getActivity(), FormActivity.class);
startActivity(intent3);
}//END OF ELSE
}//END OF onCreate()
I think it has something to do with how I am creating the list view and populating it with the ArrayList with the data got from the Parcelable ArrayList intent as it could be recreating the list view each time and only displaying the data supplied to it which in this case will be one item at a time. I've been stuck on this for a while now and was wondering if anyone has any ideas ? Thanks much.
The ArrayList you use (test2) to keep the data does not persist. You can either save the ingredients in sqlite db and call all items onCreate in your fragment, or move the test2 to the main activity and populate items before passing it with Intent bundle.

ListView items not getting populated when activity is launched

Here is my scenario:
I have a MainActivity and a CustomListViewActivity. In my MainActivity, I have 1 button and 1 spinner. On click of the button, I pass the selected spinner value to the CustomListViewActivity via Bundle and using Intents.
Now, in my CustomListViewActivity, I have a ListView that uses ArrayAdapter for populating it. I send a ArrayList from MainActivity, say for example
items = [abc]
In my CustomListViewActivity, I receive the same and use it to populate my ListView. The first time I do this, my value gets populated. The second time I do the same, the value existing is now replaced with the new one and the ListView shows one item instead of showing two.
So basically the problem is that the ListView is not updating and not showing both the items. Instead it shows me a single item always.
Here are snippets of my code
MainActivity.java
//code inside button click
..
{
items.add(spinner1.getSelectedItem().toString());
Bundle bundle =new Bundle();
bundle.putStringArrayList("data",items);
Intent i = new Intent(MainActivity.this,MyListViewActivity.class);
i.putExtras(bundle);
startActivity(i);
finish();
}
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
Log.i("App","onSave");
icicle.putStringArrayList("data",items);
}
#Override
protected void onRestoreInstanceState(Bundle icicle2) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(icicle2);
Log.i("App","onRestore");
icicle2.putStringArrayList("data",items);
}
MyListViewActivity.java
private ArrayList<String> myItems;
private static String[] titles;
CustomListViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
listView = (ListView) findViewById(R.id.list1);
rowItems = new ArrayList<RowItem>();
adapter = new CustomListViewAdapter(this,R.layout.list_item, rowItems);
listView.setAdapter(adapter);
b=getIntent().getExtras();
if(b!=null)
{
myItems=b.getStringArrayList("data");
titles= new String[myItems.size()];
titles = myItems.toArray(myItems);
}
...
int i=0;
while(i<titles.length) {
item = new RowItem(titles[i]);
//rowItems.add(item);
Log.i("ROW", ""+rowItems.size());
i++;
adapter.add(item);
listView.setAdapter(adapter);
}
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
}
}
How to make the ListView maintain the current data as well reflect the added data?
Thanks in advance
EDIT : Forgot to mention one more thing. In my MyListViewActivity class I have a button above the ListView that on clicked takes me to my MainActivity so that I can add a new Item again. So when I go back to MainActivity and try and add a new Item , it's the new Item that get displayed rather than showing both the previous and the new one
You need to persist and restore your items list in MainActivity's onSaveInstanceState and onRestoreInstanceState methods.
You also probably don't need to close the MainActivity by calling finish() every time you start the ListView activity but that depends on your application.
Basically, the problem you are having is that items is being recreated with each new instance of MainActivity. Since you finish MainActivity, a new instance is used every time you access that activity (and I assume you thought that items would just keep getting items added to it).

Android show single item from a list in next page

I am new to android and developing a mail like application. In the application, from a JSON string from server creating a list ( creating rows in a table view, which is embedded in a scroll view ). Now I am trying to show a single item in detail on clicking an item.
On click, getting the id of the corresponding item and load new page using the following page. My code looks like
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("id", 124);
b.putInt("message", "Message");
intent.putExtras(b);
startActivity(intent);
finish();
But my problem is the listing page get cleared on return back from that page.
ie, on click delete button in the child page, I want to delete the same item in the list page also. But after I deleted the item from the child page, using this code to redirect to the parent page.
Intent intent = new Intent(SecondActivity.this, FirstActivity.class);
Bundle b = new Bundle();
b.putInt("id", 124);
intent.putExtras(b);
startActivity(intent);
finish();
How to delete the single item with out page refresh if coming from the child view and load the fresh page if coming directly.
Thank you for your time
Please help
Thanks in advance
Well you just remove the desired item from the list using the remove() method of your ArrayAdapter.
A possible way to do that would be:
Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);
Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.
arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();
There is another option you can use singleton class object .
Just declare a list in singleton class and use it wherever you want like following example it will be updated for everyplace
public class Singleton {
private static Singleton instance;
private static List<Product> itemInfos = new ArrayList<Product>();
Singleton() {
}
}
when you comming to back activity just notify the adapter in onResume()

"Tracking" ListView with Multiple choices

I have a list view set to multiple choices, my question is is there a way to track what was "checked" by its name?
Intent formed = new Intent(this, formedlist.class);
SparseBooleanArray sp=getListView().getCheckedItemPositions();
String str="";
for(int i=0;i<sp.size();i++) {
str+=names[sp.keyAt(i)]+",";
formed.putExtra("strings", str);
if(names[sp.keyAt(i)].toString().equals(<String>))
startActivity(formed);
}
is this how I should be iterating through the string? and is the code for the next class that supposed to show the newly formed list is
if(names[sp.keyAt(i)].toString().equals(<String>))
//get the Listview from the previous class (this is in a new class seperate from other methods
Intent formed = getIntent();
String [] needed = formed.getStringArrayExtra("strings");
//ArrayAdapter will makes strings appear in the ListView
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2, needed));`
the way to see what is inside of the list of checked items?
I don't see a problem using this approach. Are you having a problem doing it this way?
You are not creating the intent correctly. To create an Intent for navigating to a separate Activity, use this format
Intent formed = new Intent(this, OtherActivity.class);
If you are never executing inside the if statement, try logging what values you are comparing, or stepping through with the debugger to see where things go awry.

Categories

Resources