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.
Related
after select multi images from gallery on order selection the images goes to the recycle view on random order not as I select on specific order or sort. for example if I select B then A then C but the code always bring them with random sort or order like A C B and sometimes C A B. . the order seems undefined at first I thought android sort them based on date and time added to the gallery or what their name i mean alphabet letter but then I realize the order seems undefined. i'm not sure if I need to add listener with array track the user selections. any suggestion
ArrayList imagesUriArrayList;
public static final int slect_photo = 100;
Bitmap bitmap1 = null;
RecyclerView rec;
LinearLayoutManager lnm;
Adopter_Browse list;
ArrayList<MyCard> mylist;
public void Onclick_View(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, slect_photo);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data.getData() != null) {//data.getData() != null) {
imagesUriArrayList = null;
imagesUriArrayList = new ArrayList();
try{
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
imagesUriArrayList.add(data.getClipData().getItemAt(i).getUri());
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
try {
for (int i = 0; i < imagesUriArrayList.size(); i++) {
bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), (Uri) imagesUriArrayList.get(i));
mylist.add(new MyCard(count_s, bitmap1));
}
} catch (IOException e) {
e.printStackTrace();
}
lnm = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
list = new Adopter_Browse(mylist);
rec.setLayoutManager(lnm);
list.notifyDataSetChanged();
rec.setAdapter(list);
}
I found out that using onActivityResult that provided by google will always return the order of your selection on miss , so maybe a bug or need improve .
I got two option :
1- using ItemTouchHelper library ... helped me to solve my problem !
2- gradle source form githup !
I share this maybe some one can get relief !
From the given ListView in picture, I select the contact to send sms and move to another activity (second picture). And from this sms Activity picture. When I press back hardware button available on phone, I should move where I want. I don't want a default Activity to be displayed. How can I do this?
public class SendSms extends Activity{
ListView listView;
List<RowItems> rowItems;
CustomListViewAdapter adapter;
String toNumbers = "";
String separator;
int i=0,j,count=0,count1; String a[]=new String[5];
String number,val2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new4);
listView = (ListView) findViewById(R.id.list);
rowItems = new ArrayList<RowItems>();
val2=getIntent().getStringExtra("name");
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor c = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
// ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
}, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[] { rawContactId }, null);
if (c != null) {
if (c.moveToFirst()) {
String number = c.getString(0);
//int type = c.getInt(1);
String name = c.getString(1);
int photoId = c.getInt(2);
Bitmap bitmap = queryContactImage(photoId);
RowItems p=new RowItems(bitmap, number, name);
rowItems.add(p);
}
adapter = new CustomListViewAdapter(this,
R.layout.new5, rowItems);
listView.setAdapter(adapter);
c.close();
}
}
}
}
private Bitmap queryContactImage(int imageDataRow) {
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {
ContactsContract.CommonDataKinds.Photo.PHOTO
}, ContactsContract.Data._ID + "=?", new String[] {
Integer.toString(imageDataRow)
}, null);
byte[] imageBytes = null;
if (c != null) {
if (c.moveToFirst()) {
imageBytes = c.getBlob(0);
}
c.close();
}
if (imageBytes != null) {
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
} else {
return null;
}
}
public void showResult(View v) {
// String result = "";
String result1="";
for (RowItems p : adapter.getBox()) {
if (p.chck){
// result += "\n" + p.getTitle();
result1 +="\n" +p.getDesc();
a[i]=p.getTitle();
i++;
count++;
}
count1=count;
}
Toast.makeText(this, result1+"\n", Toast.LENGTH_LONG).show();
}
public void send(View v) throws IOException {
int value=a.length-count1;
for(j=0;j<a.length-value;j++){
if(android.os.Build.MANUFACTURER.equalsIgnoreCase("Samsung")){
separator = ",";
} else
separator = ";";
number = a[j];
toNumbers= toNumbers +number +separator;
}
toNumbers = toNumbers.substring(0, toNumbers.length());
Uri sendSmsTo = Uri.parse("smsto:" + toNumbers);
String smsValue = "help iam in danger..i am presently at \n"+val2;
if(val2==null){
Toast.makeText(SendSms.this, "wait.....", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", smsValue);
intent.setData(sendSmsTo);
startActivity(intent);
}
Use startAtctivityForResult, and in onActivityResult check the resultCode. If it is Activity.RESULT_CANCELLED, the user 'backed out' of the SMS activity. Due to the implementation of the SMS activity being outside of your control, this might not be the only case when the result code says it has been cancelled.
I think you should, when the Activity picture is displayed, try to call the onBackPressed method.
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// new intent to call an activity that you choose
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// finish the activity picture
this.finish();
}
If you don't want to call an external Activity, you can hide the layout calling by the Intent as below:
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// your layout with the picture is displayed, hide it
if(MySecondView.getVisibility() == View.VISIBLE)
MySecondView.setVisibility(View.Gone);
// display the layout that you want
MyDefaultView.setVisibility(View.VISIBLE);
}
As I said below, try with a boolean that you initialize to false at the beginning of your Class. When you start the Intent.ACTION_VIEW, make this boolean to true:
public class Foo extends Activity {
private boolean isSms = false;
// some stuff
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
// ...
startActivity(intent);
// make your boolean to true
isSms = true;
// create the onBackPressed method
#Override
public void onBackPressed() {
// check if the user is on the sms layout
if(isSms)
// do something
else
// do something else like finish(); your activity
}
}
Or you can try to use the onKeyDown method (see here: onKeyDown (int keyCode, KeyEvent event)) as below:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0) {
// dome some stuff
return true;
}
return super.onKeyDown(keyCode, event);
}
You can see the diffence between these two methods here: onBackPressed() not working and on the website that I talk in the comments below.
Hope this will be useful.
UPDATE:
A better way should make an startActivityForResult to start the Intent.ACTION_VIEW:
startActivityForResult(intent, 1);
And then, you return the cancel code like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != 1 && resultCode == RESULT_CANCELED) {
// do something
}
}
This is #FunkTheMonk, just above, who tells the good choice!
Add this method to the class to handle device back button.
#Override
public void onBackPressed() {
// do something
}
Please note that it requires API Level 5 or higher.
You have to overide go back behaviour of hardware back button by calling a method name onbackpressed();
#Override
public void onBackPressed() {
super.onBackPressed();
// set intent to activity where you want to move on after back press
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// also clean the current activity from stack.
youractivityname.this.finish();
}
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);
I have 2 android activity's
One where I have a room list, i.e. list of rooms.
The other the room contents. Where all the content of a selected room is displayed.
All I want is for the room id(r_id) to be passed through the room list class into the room overview class where I can retreive all its contents from the database.
I've been trying to figure out where i'm going wrong, I think its around line 94 - 101:
selectedRoom = (String) ((TextView) view).getText();
Cursor c2 = sampleDB.rawQuery("SELECT * FROM tbl_roomDesc WHERE roomName =?", new String[] {selectedRoom});
if (c2 != null ) {
if (c2.moveToFirst()) {
do {
r_id = c2.getString(c2.getColumnIndex("r_id"));
}while (c2.moveToNext());
}
}
c2.close();
Can anyone help me figure out what i'm doing wrong here?
Here is the source for the room list
Here is the source for the room overview
Thanks in advance!
To pass data between to Intents, use the putExtras() method.
Example:
Intent i = new Intent(...);
i.putExtras("roomid", "10");
startActivity(i);
final int roomId = r_id;
next = (ImageButton) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
CreateBuilding.val = "Retrieve";
sampleDB.close();
Intent intent2 = new Intent(RoomList.this, TabLayoutActivity.class);
intent2.putExtra("roomId", roomId);
setResult(RESULT_OK, intent2);
finish();
startActivityForResult(intent2, 0);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
int roomId = data. getIntExtra("roomId", 0);
}
}
}
If I have not misunderstood you put the roomId inside the Intent and retrieve it inside the onActivityResult
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.