Passing Array To new Activity - android

Ok so, I have my app which so far opens a new Activity from the SplashScreen. Once this Activity is open there is a button to add players which opens up a new Activty. In this Activty I have an Array which will be populated by a EditText box.
Once the players have been added the play button will be clicked which will got back to the previous Activity.
My question is when the play button is clicked and you go back to the previous Activty I need the Array to be carried over and populate a String.
CODE UPDATED - No force close now but the array dosent seem to be carrying over and populating strArray
I have this button to carry the Array once players have been added:
Button play = (Button) findViewById(R.id.playnow);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent( demo.AddRemove.this, demo.play.class);
Bundle extras = new Bundle();
extras.putStringArrayList( "KEY", playerList );
i.putExtras( extras );
startActivity( i );
}});
}
And this to show the Array that was carried over:
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (extras == null) {
strArray = new String[0];
} else {
ArrayList<String> myStrings = extras.getStringArrayList("KEY");
if (myStrings == null) {
strArray = new String[0];
} else {
strArray = (String[]) myStrings.toArray();
}
}
setContentView(R.layout.passw_layout);
initWheel(R.id.passw_1, strArray);
But as I said before When I try to open the first Activty play.java from the SplashScreen it force closes with java.lang.NullPointerException. Which I think is because the extras is empty.

Try this:
String[] strArray;
Intent intent = getIntent();
Bundle extras = intent.getExtras(); //Added this
if (extras == null) {
strArray = new String[0];
} else {
ArrayList<String> myStrings = extras.getStringArrayList("KEY");
if (myStrings == null) {
strArray = new String[0];
} else {
strArray = (String[]) myStrings.toArray();
}
}

Add a simple check for null, and create an empty array:
String[] strArray;
if (extras == null) {
strArray = new String[0];
} else {
ArrayList<String> myStrings = extras.getStringArrayList("KEY");
if (myStrings == null) {
strArray = new String[0];
} else {
strArray = (String[]) myStrings.toArray();
}
}
If you don't like such a deeply nested if statement, you could also create a method to extract the array, and use early return to return the array as soon as you find a null value.

Related

How can I get integer value from activity-launcher to activity-default

I want to get value from user in launcher activity and use it in default activity for loop.
To pass values from your "LauncherActivity:"
Intent i = new Intent(getApplicationContext(), DefaultActivity.class);
i.putExtra("cycles",5);
startActivity(i);
Then retrieve those values in the "DefaultActivity":
Bundle extras = getIntent().getExtras();
int cycles = 0;
if (extras != null) {
cycles = extras.getInt("cycles");
}
for (int i = 0; i < cycles: i++) {
//do stuff
}

Not able to get String array in onActivtyResult method Android

In my case there are two activities Activity A and B
in Activty A i am calling startActivtyForResult and starting Activty B.
In activty B i am putting String array as extra as below,
// set selected contacts on DONE button press
private void setSelctedcontacts() {
ArrayList<Contact> selectedListWithPhoneNo = new ArrayList<Contact>();
ArrayList<Contact> selectedListWithEmail = new ArrayList<Contact>();
ArrayList<String> emailAddressList=new ArrayList<String>();
String[] ToAdress=new String[100];
int j=0;
Intent intent = new Intent();
ArrayList<Contact> contactList = contactAdapter.originalList;
for (int i = 0; i < contactList.size(); i++) {
Contact contact = contactList.get(i);
if (contact.isSelected()) {
if(contact.getContactNumber()!=null)
selectedListWithPhoneNo.add(contact);
if(contact.getContactEmail()!=null)
{
ToAdress[j]=contact.getContactEmail();
emailAddressList.add(contact.getContactEmail());
selectedListWithEmail.add(contact);
//Toast.makeText(ContactManager.this, "email:"+contact.getContactEmail(), Toast.LENGTH_SHORT)
//.show();
j++;
}
}
}
if (selectedListWithPhoneNo.size() > 0) {
intent.putParcelableArrayListExtra("SELECTED_CONTACTS_NUMBER", selectedListWithPhoneNo);
setResult(RESULT_OK, intent);
} else if(selectedListWithEmail.size() > 0){
intent.putParcelableArrayListExtra("SELECTED_CONTACTS_EMAIL", selectedListWithEmail);
intent.putStringArrayListExtra("EMAIL_ADDRESS_LIST", emailAddressList);
intent.putExtra("TO_ADDRESS", ToAdress);
//intent.put
setResult(RESULT_OK, intent);
}else {
setResult(RESULT_CANCELED, intent);
}
finish();
//System.out.println("selected contacts:"+selectedList.size());
// Tip: Here you can finish this activity and on the Activty result of the calling activity you fetch the Selected contacts
}
onActivtyResult code in Activity A is,
if(data.getExtras().containsKey("SELECTED_CONTACTS_NUMBER")){
ArrayList<Contact> selectedList =(ArrayList<Contact>) data.getExtras().getSerializable("SELECTED_CONTACTS_NUMBER");
Toast.makeText(ScringoFindFriendsSub.this, "email:"+data.getStringArrayListExtra("EMAIL_ADDRESS_LIST"), Toast.LENGTH_SHORT)
.show(); //i am alwasys getting null here
}
i am always getting null in data.getStringArrayListExtra("EMAIL_ADDRESS_LIST")..
SELECTED_CONTACTS_NUMBER & SELECTED_CONTACTS_EMAIL is coming in onActivityResult but EMAIL_ADDRESS_LIST is not coming, i mean its null
At a glance, I don't think you want an 'else if' here:
} else if(selectedListWithEmail.size() > 0){
If a Contact has a phone and an email, you add him to both lists. But if there's anyone on the phone list, you won't put the email list into the result.

how do i get intent extra bundle value in different tabs of tab activity?

In my application there are some values in list view and on clicking the list Item am getting values from database and passing it using intent in an array list
ArrayList<String> s = new ArrayList<String>();
s = mDbHelper.fetchDetails(appName);
// s.add(app_formno);
/*
* for(int i =0; i<Data.size();i++){ s.add(Data.get(position));
* System.out.println(Data.get(position)+"*****"+i); }
*/
prefEditor.putBoolean("gotobundle", true);
prefEditor.commit();
startActivity(new Intent(ListViewDetails.this,
ApplicationManagement.class).putExtra("list", s));
I am getting the array list in e bundle which is in Tab widget(TAB 1).
protected void onResume() {
super.onResume();
settings = getSharedPreferences("LandTshare", MODE_PRIVATE);
prefEditor = settings.edit();
boolean bool = settings.getBoolean("gotobundle", false);
if (bool == true) {
Bundle b = getParent().getIntent().getExtras();
// ArrayList<String> bundlevalue = new ArrayList<String>();
bundlevalue = new ArrayList<String>();
if (b != null) {
bundlevalue = b.getStringArrayList("list");
this code prints the respective values in tab 1 but when i go to tab 2 the value in the bundle is empty and my application force closes..
Below is the code in TAB 2
protected void onResume() {
super.onResume();
boolean bool = settings.getBoolean("gotobundle", false);
if(bool == true){
if (Applicant.bundlevalue.size() > 124 == true){
for (int i = 125; i <= 146; i++)
System.out.println(Applicant.bundlevalue.get(i));
if (Applicant.bundlevalue.get(125).equalsIgnoreCase("Yes")) {
rg_existin1.check(R.id.rYes);
} else {
rg_existin1.check(R.id.rNo);
}
what is the issue here?? i cant seem to figure out!
Please help!

Saving the checked list item continuously when after coming back to the activity and select

Hi I am new to the android & doing some simple examples. Exactly, i'm using two activities & it contains a list view on both. In that first list view (Activity1) is empty, the second list view(Activity2) has some list item with a checkbox. Now getting the selected item from the 2nd activity & listed in the first activity. It's fine but exactly what i want is again click 'add' button from the 1st activity it launches the second activity then select some item & save. This newly selected item not adding to the existing list value used in 1st activity. Can anybody help me out.
SecondActivity.java
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkedContactList = adapter.getSelectedItemArrayList();
}
Intent returnIntent = new Intent(v.getContext(),MainActivity.class);
returnIntent.putParcelableArrayListExtra("result", checkedContactList);
startActivity(returnIntent);
}
});
In MainActivity.java
private ArrayList<SelectedListModel> selectedArrayList = new ArrayList<SelectedListModel>();
List<Map<String, String>> dataList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataList = new ArrayList<Map<String, String>>();
Bundle data = getIntent().getExtras();
selectedArrayList = data.getParcelableArrayList("result");
Iterator<ArrayList<SelectedListModel>> it = selectedArrayList.iterator();
while (it.hasNext()){SelectedListModel selectedModel = (SelectedListModel)it.next();
SelectedListModel selectedModel = (SelectedListModel)it1.next();
String name1 = selectedModel.getName();
String number1 = selectedModel.getNumber();
Map<String, String> dict = new HashMap<String, String>(2);
dict.put("name", name1);
dict.put("number", number1);
dataList.add(dict);
//listdata.add(dataList);
}
SimpleAdapter adpt = new SimpleAdapter(this, dataList, android.R.layout.two_line_list_item, new String[] {"name", "number"}, new int[] {android.R.id.text1, android.R.id.text2});
selectedList.setAdapter(adpt);
}
You can use startActivityForResult()
Api Document
Call in activity 1
startActivityForResult( Activity2, Activity2RequestCode)
In Activity 2
int result = "Some message here";
output.putExtra(name , result);
setResult(RESULT_OK, output);
finish();
In Activity 1 get return value
onActivityResult (int requestCode, int resultCode, Intent data)
if (requestCode == ActivityTwoRequestCode && resultCode == RESULT_OK && data != null)
num1 = data.getIntExtra(Number1Code);
num2 = data.getIntExtra(Number2Code);

creating array list and passing it from one activity to another

I am a student and new to programming. It might be a simple error, can anybody help me fix it.I have to pass an array list from one activity to another. In this activity i have 5 radio buttons RB1, RB2.... and i want to pass the content of news[] it to another activity called display.
public void onClick(View v) {
String[] news;
news = new String[5];
news[0] = "bbc";
news[1] = "guardian";
news[2] = "yahoo";
news[3] = "sky";
news[4] = "fox news";
final ArrayList<String> arr = new ArrayList<String>();
if (RB1.isChecked() == true)
arr.add(news[0]);
if (RB2.isChecked() == true)
arr.add(news[1]);
if (RB3.isChecked() == true)
arr.add(news[2]);
if (RB4.isChecked() == true)
arr.add(news[3]);
if (RB5.isChecked() == true)
arr.add(news[4]);
if (v == Done)
{
Button done = (Button) findViewById(R.id.DONE);
done.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
Intent myIntent = new Intent(Read.this, display.class);
myIntent.putExtra("pass",arr);
startActivity(myIntent);
}
});
}
the codes for next activity is as follows
Intent myintent = getIntent();
String[] Array = myintent.getStringArrayExtra("pass");
for (int i = 0; i < Array.length; i++)
Log.v(LOG_TAG, "THE website Is :" +Array[i]);
I am geting a java.lang.NullPointerException in the above two line i.e
for (int i = 0; i < Array.length; i++)
Log.v(LOG_TAG, "THE website Is :" +Array[i]);
can u pls tell me why ?
thanks in advance
First of all, some conventions: Start names of variables lowercase, so array instead of Array. This will save you from some confusion later.
Try it as follows, from this thread:
Bundle b=new Bundle();
b.putStringArray(key, new String[]{value1, value2});
Intent i=new Intent(context, Class);
i.putExtras(b);
and
Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);
Use Bundle like this:
Bundle bundle = new Bundle();
bundle.putStringArray(key, news);
myIntent.putExtra("pass",bundle);
startActivity(myIntent);

Categories

Resources