简体   繁体   中英

Passing values from an Activity into a ListView in another activity and saving these values

I have an app where the main screen is the list view, and then the user can click on an add button which takes the user to another activity where he/she can choose values from a spinner, and there's a button on the bottom called "Save", which when clicked saves the values from the spinners into a list item and it takes the user back to the main screen with the list view and the newly created list item.

This is my code:

package viva.inspection.com.inspectionpicker;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;

import viva.inspection.com.inspectionpicker.R;

public class ListActivity extends Activity {
    private static ArrayList<String> inspections = new ArrayList<String>();
    private static ArrayAdapter<String> inspectionAdapter;
    private static final String s = "inspection list";
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        ArrayList<String> temp = new ArrayList<String>(settings.getStringSet(s, new HashSet<String>(inspections)));
        inspections = temp;
        ListView inspectionList = (ListView) findViewById(R.id.listView);
        inspectionAdapter  = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, inspections);
        inspectionList.setAdapter(inspectionAdapter);
        if(getIntent().getStringExtra("spins") != null) {
            addItems(getIntent().getStringExtra("spins"));
        }
        System.out.println("Created");

    }

    @Override
    protected void onPause(){
        super.onPause();
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putStringSet(s, new HashSet<String>(inspections));
        System.out.println("Paused");
        editor.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putStringSet(s, new HashSet<String>(inspections));
        editor.commit();
        System.out.println("Destroyed");
    }

    @Override
    protected  void onResume() {
        super.onResume();
        inspections = temp;
        ListView inspectionList = (ListView) findViewById(R.id.listView);
        inspectionAdapter  = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, inspections);
        inspectionList.setAdapter(inspectionAdapter);
        System.out.println("Resumed");
    }

    public static void addItems(String s) {
        inspections.add(s);
        inspectionAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch(id) {
            case R.id.action_settings:
                return true;
            case R.id.action_new:
                startActivity(new Intent(this, MyActivity.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Now, I have the saving down, but it only saves one value and I want it to save multiple values. Also, as you can see I have tried implementing the SharedPreferences class to save the values of my list so that when the user comes back to it after removing the app from multitasking, it will still show the values the user had before. However, this isn't working. I have tried using onPause and onResume (as you can see in the code above), but to no avail. I'm really confused as to why this isn't working, because I have logged the values of when the activity is paused/resumed, and I can see the logged values appearing in the console. All I basically want is to save multiple values in the list and not just one, and to have the values saved so that whenever the activity is destroyed, the list view will show the saved values so no data is lost.

Any help is greatly appreciated. Thank-you in advance.

EDIT: I have solved the saving problem, but now I need to be able to save the values of the ListView so that when the user reopens the app, the values will still be there, and the won't disappear.

you have developed your Main Activity and there is a Listview , now you must develope what happens if you click an item of your ListView, a start point would be ie

ListView lv = getListView();    
lv.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        int itemPosition = position;

        String parameter1 = "Hello";
        int parameter2    = 1;   

        Intent i = new Intent(Name_of_your_Calling_Activity.this,
Name_of_your_called_Activity.class);
        i.putExtra("parameter_name1", parameter1);
        i.putExtra("parameter_name2", parameter2);
         ... // So many parameters as you want
        // Here you have 2 Possibilities, you can get return parameters or not
        // for the 1st Case you must
        startActivityForResult(i, REQUEST_CODE)  // (1) Alternative *
        startActivity(i);                        // (2)

    }
});

In your main activiy you must override the onActivityResult Method override to get the return parameters like this (If you have selected (1) Alternative!!!) where REQUEST_CODE a code to distinguish what a activity have called.(There could be many and therefore we need to distinguish if many)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
           Bundle b = data.getExtras();
           if ( b!= null ) { // Assuming you put a returnBack Param with the name "returnBack1"
              String retBack1 = b.getString("returnBack1"); 
           } 
        // Do something with the contact here (bigger example below)
    }
}

}

In your called Activity you can get these passed parameters ie in onCreate Method with the following code

Bundle b = getIntent().getExtras();
if (b!=null) { // Here we could assume i.e. we get 2 return params of typ int with this name. They were put in the called Activity like we made in above code, so, `intent.put...`
    String value  = b.getInt("param1");
    int    value2 = b.getInt("param2");
}

I find that is a good start Point, if you want to have something,that works you can see here And look at Android Developer Reference for return back parameters , there you can see detailed and with Examples what I have explained grosso modo.

I hope, that leads you to a solution

Try this way,hope this will help you to solve your problem.

private final int GET_VALUE=111;

Your List Activity Add Button

Intent intent = new Intent(yourcurrentclass.this,youraddactivityclass.class);
startActivityForResult(intent,GET_VALUE);

Your Add item Activty Save Button

Intent intent = new Intent();
intent.putExtra("NEW_VALUE","new list item");
setResult(RESULT_OK,intent);

After add item get result in List Activity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if(resultCode==RESULT_OK){
      if(requestCode == GET_VALUE){
        if(data.getStringExtra("NEW_VALUE")!=null && data.getStringExtra("NEW_VALUE").length()>0){
           addItems(data.getStringExtra("NEW_VALUE"))
        }
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM