Returning Data Result to Parent Activity using Intents

怎甘沉沦 提交于 2019-12-22 10:24:58

问题


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();
    }
}

回答1:


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.




回答2:


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", "");


来源:https://stackoverflow.com/questions/20491764/returning-data-result-to-parent-activity-using-intents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!