I am receiving the variable from a different activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == 0) {
if (resultCode == RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// Add data to ArrayList
Array_List.add(1,returnString);
}
}
}
Expected Result:
Item Entered by user
Result:
Duplicates the last added item on the ArrayList
public class MainActivity extends AppCompatActivity {
public final String FILENAME = "example.txt";
ArrayList<String> Array_List = new ArrayList<String>();
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView lv = (ListView) findViewById(R.id.LV_Main);
Array_List.add(0,"Saved Posts");
//Ensures Add new is always at the end
Array_List.add(Array_List.size(), "Add New +");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.activity_list_item,android.R.id.text1,
rray_List );
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == 0) {
if (resultCode == RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// Add data to ArrayList
Array_List.add(1,returnString);
}
}
}
}
Thanks in advance
Edit:
Array_List.add(Array_List.size() - 1, "Add New +");
Does not work
Also, I need Add New to always be at the bottom and Saved Posts at the top
It is weird as if I remove the Array_List.add(1,returnString);
Then it works but adds the returnstring to the bottom of the ArrayList, however I need the Add New always at the bottom
The behaviour you're looking for already exists in ListView - it's called a "Header" and a "Footer". You can also just define one in xml to make your life easier:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView lv = (ListView) findViewById(R.id.LV_Main);
lv.addHeaderView(createTextView("Saved Posts"));
lv.addFooterView(createTextView("Add New +"));
//Etc. etc.
}
private TextView createTextView(String content) {
TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tv.setText(content);
return tv;
}
Now you don't need to worry about inserting the first and last elements yourself - just add the content to your list and update your adapter with it.
Edit: If you want the header and footer to have the same styling as the rest of your list elements:
private View createHeaderOrFooter(String content) {
final LayoutInflater inflater = LayoutInflater.from(this);
final View row = inflater.inflate(android.R.layout.activity_list_item, null);
((TextView)row.findViewById(android.R.id.text1)).setText(content);
return row;
}
replace
Subreddit_Array_List.add(Subreddit_Array_List.size(), "Add New +");
with
Subreddit_Array_List.add(Subreddit_Array_List.size() - 1, "Add New +");
Related
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
I created below class but numbers is coming null. The same code is working fine with activity. I have made changes in context of Fragment. What else is creating problem in the code.
public class TestFrag extends Fragment {
private static final String[] phoneProjection = new String[]{ContactsContract.CommonDataKinds.Phone.DATA};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testfrag, container, false);
TextView textView = (TextView) view.findViewById(R.id.clickme);
EditText editText = (EditText) view.findViewById(R.id.contact);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
getActivity().startActivityForResult(intent, 1);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (1):
//ContentResolver cr = getContentResolver();
Uri contactData = data.getData();
Cursor c = getActivity().getContentResolver().query(contactData, phoneProjection, null, null, null);
if (c.moveToFirst()) {
String numbers = c.getString(0);
Log.e("Hi", numbers);
}
break;
}
}
}
you are calling getActivity().startActivityForResult(intent, 1); it's response will be handled in activity's onActivityResult() method you should call startActivityForResult(intent, 1); which is fragment's method and will call the fragments onActivityResult().
you can check this link too
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)
...
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.
I am able to successfully transfer the string in my ListView in my first Activity to the EditText in my second Activity. I now want to edit the text and send it back to update my ListView in my first Activity. I basically want to have the edits be sent back to the first activity as a popup to help me test which string is being passed back
I'm not sure what Intent to put in my onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
Here is my first Activity:
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
private final int REQUEST_CODE = 20;
//private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
onActivityResult(REQUEST_CODE, RESULT_OK, /** Intent variable **/);
}
private void launchEditItem(String item) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", item); // list item into edit text
//startActivityForResult(i, REQUEST_CODE);
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
String text = (String) lvItems.getItemAtPosition(pos);
launchEditItem(text);
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
}
I thought about using the Intent from the second activity but I'm not sure how to do so.
Here is my second Activity.
public class EditItemActivity extends Activity {
private EditText etEditItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
etEditItem = (EditText)findViewById(R.id.etEditItem);
etEditItem.setText(ItemToEdit);
onSubmit(etEditItem);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_item, menu);
return true;
}
public void DoneEdit(View v) {
this.finish();
}
public void onSubmit(View v) {
EditText etName = (EditText) findViewById(R.id.etEditItem);
Intent data = new Intent();
data.putExtra("EditedItem", etName.getText().toString());
setResult(RESULT_OK, data);
finish();
}
}
To get result form an activity (child) you do as follow :
In the parent activity
startActivityForResult(myIntent, 1);
global vars of your parent activity
boolean backFromChild = false;
String aString;
then still in the parent activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// code for result
aString = getIntent().getExtras().getString("aString");
backFromChild = true;
}
if (resultCode == RESULT_CANCELED) {
// Write your code on no result return
}
}
}
in your child you do somewhere something like that
Intent returnIntent = new Intent();
//example of sending back a string to the parent.
returnIntent.putExtra("aString", aString);
setResult(RESULT_OK, returnIntent);
finish();
The thing is that onResume of your parent activity will be called when returning from your child. In there you have to perform the update, in your case it is to update the information of the edited text :
#Override
public void onResume(){
super.onResume();
if (backFromChild){
backFromChild = false;
//do something with aString here
Toast.makeText(this, aString, Toast.LENGTH_SHORT).show();
}
}
Basically, in the onActivityResult I get the info back from the intent of the child. Then in onResume I use this info.
For your concern you can utilize SharedPreferences
For ex: Put data in SP in second activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
SharedPreferences.Editor editors = spppp.edit();
editors.putString("for", "0");
editors.commit();
and fetch data for list view in first activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
String your_list_view_value = spppp.getString("for", "");