Android - Adding item to ListView from another Activity - java

First of all, I've searched on many other posts and still not found a fix for it.
MainActivity contains a ListView and an ImageButton that takes to AddActivity.
This AddActivity has got a EditText (nameAddInput) and a Button(addButton).
Despite clicking this Button, the ListView in MainActivity remains empty... Don't understand why...
Here is the the code of MainActivity:
public class MainActivity extends AppCompatActivity {
static final int PICK_CONTACT_REQUEST = 0;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.itemsList);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(this, R.layout.listview_style1, android.R.id.text1, arrayList);
}
public void onClickAddButton(View view) {
Intent i = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(i, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
addNewItem();
}
}
}
public void addNewItem() {
Bundle addNameInfo = getIntent().getExtras();
if(addNameInfo == null)
return;
String nameInput = addNameInfo.getString("nameInput");
arrayList.add(nameInput);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
In xml file of MainActivity in the ImageButton: android:onClick="onClickAddButton"
The code of AddActivity:
public class AddActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
}
public void backToMain(View view) {
Intent i = new Intent();
EditText nameAddInput = (EditText) findViewById(R.id.nameAddInput);
String userNameText = nameAddInput.getText().toString();
i.putExtra("nameInput", userNameText);
setResult(RESULT_OK, i);
finish();
}
}
In xml file of AddActivity in the Button: android:onClick="backToMain"
Hope someone can help!!
Thank you in advance!!

getIntent() returns you the intent that launched MainActivity, not the one you set in backInMain
Try the "data" variable passed to you in onActivityResult?
Also change to
startActivityForResult(i, PICK_CONTACT_REQUEST);
I'd also suggest you rename that variable 😉

set adapter just in onCreate and just call notifyDataSetChanged in addNewItem method.

the resulting value is returned in the Intent data-Parameter of the onActivityResult function, not in the intent-member of the mainActivity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
addNewItem(data.getExtras().getString("nameInput");
}
}
}
...
public void addNewItem(String newItem)
...

Related

Transferring data from the third activity to the first

From the first activity I would like to go to the second, then from the second to the third. In the third activity I would like to enter the name in EditText, then after pressing the button, go to the first activity and at the same time send the information entered in the third activity.
Unfortunately, after pressing the button in the third activity, instead of returning to the first activity, I return to the second activity. Was the first activity killed? What could I do to ensure that the information is correct for the first activity? This is my code:
First:
public class MainActivity extends AppCompatActivity {
TextView textViewInformation;
Button button_GoToSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewInformation = findViewById(R.id.textView);
button_GoToSecond = findViewById(R.id.button);
button_GoToSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Second.class);
startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
String name = i.getStringExtra("name");
textViewInformation.setText(name);
}
}
}
Second:
public class Second extends AppCompatActivity {
Button button_GoToThird;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
button_GoToThird = findViewById(R.id.button2);
button_GoToThird.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Second.this, Third.class);
startActivity(i);
}
});
}
}
Third:
public class Third extends AppCompatActivity {
EditText editText_Data;
Button button_SendData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
editText_Data = findViewById(R.id.editText);
button_SendData = findViewById(R.id.button3);
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
just remove finish(); thats it
The reason that it goes to the second activity is because of this:
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish(); //This kills the current activity.
}
You should do:
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", name);
startActivityForResult(i, RESULT_OK, bundle);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
Bundle bundle = i.getExtras();
String name = bundle.getString("name");
textViewInformation.setText(name);
}
}
When you call finish, it just kills the current activity. If you want to go back to the first activity, just start a new activity for the first activity and pass the data in a Bundle.
If you want to have more of a stack concept, you can use Fragments.

Android, how to update ListView content from external activity?

I have a project with 4 classes: 2 activities, 1 adapter and 1 class for simple object. Names of the classes are: MainActivity, AddingItemsActivity, ItemAdapter, SimpleItem. In a layout corresponding to the MainActivity, there is a list view named SimpleListView. SimpleListView should contain SimpleItem objects. ItemAdapter is made to handle SimpleListView. Updating, adding items to SimpleListView from MainActivity is very easy. What I would like to reach is updating, adding items, which appear on the SimpleListView, from AddingItemsActivity (appear when user come back to the MainActivity). Could you tell me what should I do to reach that?
PS: I would like to ask: "how to update SimpleListView from AddingItemsActivity?" but I have read that it is not proper question, beacuse SimpleListView does not exist in AddingItemsActivity.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button toAddingActivity = findViewById(R.id.toAddingActivitybutton);
final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivity(intent);
}
});
}
}
AddingItemsActivity
public class AddingItemsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
Button addItem = findViewById(R.id.AddItembutton);
// final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
// final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// first reflex try, which does not work:
// SimpleItem item = new SimpleItem("String number 1", "String number 2");
// mAdapter.add(item);
// simpleItemsListView.setAdapter(mAdapter);
}
});
}
}
ItemAdapter
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
public ItemAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ItemAdapter(Context context, int resource, List<SimpleItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.simple_item_adapter, null);
}
SimpleItem item = getItem(position);
if (item != null) {
TextView tv1 = v.findViewById(R.id.adapterTextView1);
TextView tv2 = v.findViewById(R.id.adapterTextView2);
tv1.setText(item.getStr1());
tv2.setText(item.getStr2());
}
return v;
}
}
SimpleItem
public class SimpleItem {
private String str1;
private String str2;
public SimpleItem(String s1, String s2)
{
str1 = s1;
str2 = s2;
}
public String getStr1()
{
return str1;
}
public String getStr2()
{
return str2;
}
}
Use startActivityForResult to get the result as SimpleItem from AddingItemsActivity.
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivityForResult(intent,1);
Create a SimpleItem in AddingItemsActivity, add values to it and use setResult to give simple item instance back to MainActivity
// inside on click
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("result", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();`
In MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
SimpleItem result = (SimpleItem)data.getSerializableExtra("result");
// add result to the list, used by adapter
// notify adapter using notifyDataSetChanged
}
}
}//onActivityResult
Note : add public class SimpleItem implements Serializable and seems like you forgot to create and pass list to adapter instances, so simply create it
your adaper is not complete you must override getCount method and set your list.size() to it . then from your MainActivity you mast create a list of simle item and pass it to your adapter .
ArrayList<SimpleItem> items=new ArrayList<>();
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter,items);
then you can put your list to intent and pass it to AddingItemsActivity .
Intent intent=new Intent (this,AddingItemsActivity.class);
intent.putExtra("Key",items);
startActivityForResult(intent,your request code (exam : 14));
and in AddingItemsActivity :
Bundle bundel=getIntent().getExtras();
ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)bundle.get("Key");
change or add items to list and return it to MainActivity :
Intent returnIntent = new Intent();
returnIntent.putExtra("returnedList", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
and in onActivityResult of MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14) {
if(resultCode == Activity.RESULT_OK){
// ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
mAdapter .notifyDataSetChanged();
}
}
}
And dont forgot implemens your simpleItem class of Serializable
try this :
MainActivity :
public class MainActivity extends AppCompatActivity {
private ArrayList<SimpleItem> items = new ArrayList<>();
private Button toAddingActivity;
private ListView simpleItemsListView;
private ItemAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toAddingActivity = (Button) findViewById(R.id.toAddingActivitybutton);
simpleItemsListView = (ListView) findViewById(R.id.SimpleListView);
mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter, items);
simpleItemsListView.setAdapter(mAdapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddingItemsActivity.class);
startActivityForResult(intent, 14);
}
});
mAdapter.notifyDataSetChanged();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14 && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
SimpleItem item=(SimpleItem) bundle.get("reKey");
items.add(item);
mAdapter.notifyDataSetChanged();
}
}
}
ItemAdapter :
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
private ArrayList<SimpleItem> items =new ArrayList<>();
private Activity activity;
private int layoutResource;
public ItemAdapter(#NonNull Activity act, int resource, #NonNull ArrayList<SimpleItem> data) {
super(act, resource, data);
items =data;
activity=act;
layoutResource=resource;
}
#Override
public int getCount() {
return items.size();
}
#Override
public SimpleItem getItem(int position) {
return items.get(position);
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
View row=convertView;
if(row==null || (row.getTag()==null)){
LayoutInflater inflater=LayoutInflater.from(activity);
row=inflater.inflate(layoutResource,null);
holder=new ViewHolder();
holder.tv1=row.findViewById(R.id.adapterTextView1);
holder.tv2=row.findViewById(R.id.adapterTextView2);
row.setTag(holder);
}else {
holder=(ViewHolder)row.getTag();
}
holder.simpleItem=items.get(position);
holder.tv1.setText(holder.simpleItem.getStr1());
holder.tv2.setText(holder.simpleItem.getStr2());
return row;
}
class ViewHolder{
TextView tv1;
TextView tv2;
SimpleItem simpleItem;
}
}
AddingItemsActivity :
public class AddingItemsActivity extends AppCompatActivity{
private Button addItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
addItem=(Button)findViewById(R.id.AddItembutton);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("reKey",item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
}
you can change AddingItemsActivity onclick method

Save QR code text in memory and show it in another activity

I have an app that scans QR code. And it to show in another activity. How to pass QR Code text to another activity? Or save it in memory?
MainActivity
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView zXingScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
Toast.makeText(getApplicationContext(), result.getText(),Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
zXingScannerView.resumeCameraPreview(this);
}
}
Call method startActivityForResult(new Intent(this, YourCallbackActivity.class), 1001);
Use setResult() method for get call back in another activity.
#Override
public void handleResult (Result result) {
Intent returnIntent = new Intent();
returnIntent.putExtra("result",String.valueOf(rawResult));
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
now
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
if (resultCode == RESULT_OK && data != null) {
String result = data.getStringExtra("result");
//do whatever you want
}
}
}
I already did, hope it will help you!!

intent method (onActivityResult) wipeout previous listview stored data

I am trying to create a group of phone contacts in CreateGroup.java . So, for that purpose, I go to a new activity named ContactsView.java using an Intent. There I a get list of all contacts. When I click a contact from that list, it gets the name of that contact item and returns it back to the previous activity named CreateGroup.java. But when I try to add more contacts, it is replacing the previous added item in the listview. I am unable to add more than one contact in my list.
Please someone help me!!
CreateGroup.java
public class CreateGroup extends ActionBarActivity {
TextView textView;
ListView show;
ArrayList<String> addArray=new ArrayList<String >();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group);
ImageButton next = (ImageButton)findViewById(R.id.imgButtonAddContacts);
textView=(TextView)findViewById(R.id.textViewtst);
show= (ListView) findViewById(R.id.listView2);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), ContactsView.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (0) : {
if (resultCode == Activity.RESULT_OK) {
String newText = data.getStringExtra("CName");
addArray.add(newText);
ArrayAdapter<String>adapter=new ArrayAdapter<String> (CreateGroup.this,android.R.layout.simple_list_item_1,addArray);
show.setAdapter(adapter);
}
break;
}
}
}
}
here is ContactsView.java
public class ContactsView extends ActionBarActivity {
String namecsv="";
String phonecsv="";
String namearray[];
String phonearray[];
ListView lv1;
ArrayList<String> list_items= new ArrayList<String>();
//declare a variable for counting of selected items.
int count=0;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_view);
lv1=(ListView)findViewById(R.id.listView);
list_items.add("one");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()){
String name= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phonenumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(name!=null){
namecsv+=name + ",";
phonecsv+=phonenumber + ",";
}
}
phones.close();
namearray= namecsv.split(",");
phonearray=phonecsv.split(",");
final ArrayAdapter <String> adapter = new ArrayAdapter <String> (this,android.R.layout.simple_list_item_1,android.R.id.text1,namearray);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String msgname = namearray[position];
String msgnum = phonearray[position];
Toast.makeText(getApplicationContext(), msgname + " " + msgnum, Toast.LENGTH_SHORT).show();
Intent resultIntent = new Intent();
resultIntent.putExtra("CName", msgname);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});
}
}
I have updated my code according to the answer provided. but still facing the same problem. its only show only on last add item in the listview. previous item removes.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case (0) : {
if (resultCode == Activity.RESULT_OK) {
String newText = data.getStringExtra("CName");
textView.setText(newText);
addArray.add(newText);
adapter.notifyDataSetChanged();
show.setAdapter(adapter);
}
break;
}
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
You should not call super.onActivityResult(requestCode, resultCode, data); as very first thing, there but only when you face requestCode that is not handled by your code. In other words, this should be added to switch block, in default section. Other thing is that you should not set new adapter each time. So this:
addArray.add(newText);
ArrayAdapter<String>adapter=new ArrayAdapter<String> (CreateGroup.this,android.R.layout.simple_list_item_1,addArray);
show.setAdapter(adapter);
should be replaced by:
addArray.add(newText);
adapter.notifyDatasetChanged();
which simply adds data to your current array then notify the adapter (which you need to create in onCreate() additionally of course) about the change in dataset.

startActivityForResult returning null when back navigation to activity sending result returns

I have 3 activities that start in a sequence.With the first activity needing a result from the last activity.
I have it so that if Activity B is started for result (By activity A) then Activity B starts activity C for result. Then once the result is captured at activity C it is finished which calls Activity B's onActivityResult which sets the result and finishes and Activity A's onActivityResult gets the final result.
Activity A starts Activity B for a result which Activity C contains thus the sequence is like so
A->B->C (get result) C->B->A (result retrieved)
This works just fine if everything happens in sequence. However, If I navigate to activity C then press the toolbars back arrow and which leads me to activity B then navigate back to activity C and select the result. The result returned to activity A is null.
A->B->C->B->C(get result) C->B->A (result == null)
Activity A
public class AlertCreationActivity extends AppCombatActivity {
// OnCreate methods left out to shorten code
#OnClick(R.id.locationButton)
public void locationButtonClicked() {
Intent intent = new Intent(this, StateActivity.class);
intent.putExtra(StateActivity.IS_STARTED_FOR_RESULT, StateActivity.STARTED_FOR_RESULT);
startActivityForResult(intent, ALERT_CREATION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ALERT_CREATION_REQUEST_CODE && resultCode == RESULT_OK) {
String title = data.getStringExtra(ALERT_CREATION_REQUEST_DATA);
if ( ! title.isEmpty()) {
mLocationButton.setVisibility(View.INVISIBLE);
mLocationTextView.setText(title);
mLocationTextView.setVisibility(View.VISIBLE);
}
}
}
}
Activity B
public class StateActivity extends AppCompatActivity {
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AlertCreationActivity.ALERT_CREATION_REQUEST_CODE) {
Intent intent = new Intent();
intent.putExtra(AlertCreationActivity.ALERT_CREATION_REQUEST_DATA, data.getStringExtra(AlertCreationActivity.ALERT_CREATION_REQUEST_DATA));
setResult(RESULT_OK, intent);
finish();
}
}
}
Activity B's adapter is where the next intent happens
public class StateAdapter extends RecyclerView.Adapter<StateAdapter.StateViewHolder> {
// Other Adapter methods not shown
public class StateViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// Other View Holder methods not shown
#Override
public void onClick(View v) {
State selectedState = getStateBy(mLocationLabel.getText().toString());
// Save state ID
LocationStorage storage = new LocationStorage(mActivity);
storage.setSelectedStateId(selectedState.getId());
storage.setSelectedStateName(selectedState.getName());
Intent intent = new Intent(mActivity, SpotActivity.class);
mActivity.startActivityForResult(intent, AlertCreationActivity.ALERT_CREATION_REQUEST_CODE);
}
}
}
Activity C
public class SpotActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize actionbar and recyclerview adapter
// a click on a recyclerview's list item triggers this method
adapter.setSurfSpotSelectedListener(new SurfSpotSelectedListener() {
#Override
public void onSpotSelected(String spotName) {
Intent intent = new Intent();
intent.putExtra(AlertCreationActivity.ALERT_CREATION_REQUEST_DATA, spotName);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
What does navigate back to activity C mean?If you dont start C By startActivityForResult,you will get no result in B.
You should set your result by overriding OnBackPressed(), for example:
#Override
public void onBackPressed() {
setResult(111, new Intent().putExtra("result", "from c"));
super.onBackPressed();
}
For Actionbar, you should overriding onOptionsItemSelected(MenuItem item)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//here
setResult(111, new Intent().putExtra("result", "from c"));
this.finish();
default:
return super.onOptionsItemSelected(item);
}
}
I ended up solving it by setting the setNavigationOnClickListener for the toolbar in Acitvity B andActivity C and calling onBackPressed() to mimic back navigation. Thanks for all your help Tiny Sunlight and Good Try. Here is my Activity B & C. I hope this helps others.
Activity B
public class StateActivity extends AppCompatActivity {
#Bind(R.id.toolBar) Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spot_selection);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
// Recyclerview and Adapter left out for brevity
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AlertCreationActivity.ALERT_CREATION_REQUEST_CODE) {
Intent intent = new Intent();
intent.putExtra(AlertCreationActivity.ALERT_CREATION_REQUEST_DATA, data.getStringExtra(AlertCreationActivity.ALERT_CREATION_REQUEST_DATA));
setResult(RESULT_OK, intent);
finish();
}
}
}
Activity C
public class SpotActivity extends AppCompatActivity {
#Bind(R.id.toolBar) Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spot_selection);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
// Setting up Recyclerview and Adapter omitted
adapter.setSurfSpotSelectedListener(new SurfSpotSelectedListener() {
#Override
public void onSpotSelected(String spotName) {
Intent intent = new Intent();
intent.putExtra(AlertCreationActivity.ALERT_CREATION_REQUEST_DATA, spotName);
setResult(RESULT_OK, intent);
finish();
}
});
}
}

Categories