0

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.

Vishwa Iyer
  • 841
  • 5
  • 14
  • 33
  • StartActivityForResult and get newly added value from Result and try to add this value to your list and notify. – Haresh Chhelana Jul 12 '14 at 12:44
  • @Haresh Why would I use StartActivityForResult? When you click on the save button to save the spinner values, it brings you back to the ListView Activity – Vishwa Iyer Jul 12 '14 at 12:45

2 Answers2

0

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"))
        }
      }
   }
}
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
  • Now, how exactly do I save the values so that when you remove the app from multitasking and re-open it, it will still show you saved values in the listview? – Vishwa Iyer Jul 12 '14 at 13:06
  • then you have to store your list data in database. – Haresh Chhelana Jul 12 '14 at 13:08
  • also the add button is in the action bar and it's in the mainactivity with the listview, so where do I put the onActivityResult-my Main Activity with the list view or the Activity with the spinner and save button? – Vishwa Iyer Jul 12 '14 at 13:09
  • never mind, I figured it out. Could you explain to me why though, my listview doesn't save values even though I overrided the onpause and onresume methods and tried to save the data there? – Vishwa Iyer Jul 12 '14 at 13:14
  • Vishwa, look at how haresh does, he just needs an 'adapter.notifyDataSetChanged()' below `addItems(...)` in order the `ListView` get updated – Gödel77 Jul 12 '14 at 15:18
  • @Haresh When I click save, it doesn't go back to my listview activity. Should I change the code to this? `Intent intent = new Intent(MyActivity.this, ListActivity.class); intent.putExtra("NEW_VALUE", roomSpinner.getSelectedItem().toString()); setResult(RESULT_OK, intent);` – Vishwa Iyer Jul 12 '14 at 16:16
0

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 i.e.

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 i.e. 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

Gödel77
  • 839
  • 3
  • 15
  • 27
  • My main activity is a listview with an add button in the action bar. When you click on the add button, it takes you to another activity where you choose values from a spinner, and there's a button on the bottom called "Save". When you click on the save button, it's supposed to take you back to the activity with the listview and display a list item with the value of the spinner value you chose before. – Vishwa Iyer Jul 12 '14 at 13:05
  • 1
    In `onClick` Method of this "Save" Button you can go back to your first Activity with the properly values you got it, in this case a value of a Spinner, just write a `intent.putExtra("example", strName);` assuming the selected value of spinner is a String, of course. – Gödel77 Jul 12 '14 at 13:13
  • 1
    Above I meant "just" write..., of course you need call properly calling activity when you pass your return params. Here There is an example like you want http://www.vogella.com/tutorials/AndroidListView/article.html – Gödel77 Jul 12 '14 at 13:17
  • Ok, but do you know how to save the values of the listview so even if the activity is destroyed when for example, the user removes the app from multitasking, then the listview will still have the same values it did before the activity got destroyed? – Vishwa Iyer Jul 12 '14 at 13:20
  • To update you must notify the Change, look at reference of ListView and adapter and update properly, so `your_adapter_variable.notifyDataSetChanged()` i.e. – Gödel77 Jul 12 '14 at 14:40
  • No, I know how to do that, I mean how to save the values of the list view and store it, so I can access it later. – Vishwa Iyer Jul 12 '14 at 14:47
  • 1
    You have an ArrayList inspections, haven't you? There you must update/add with the properly position with the properly return value(s), you can do that with a and then you write `inspections` with a `set` Method if you update an existing position and `add` if you add a new item and then `your_adapter_variable.notifyDataSetChanged()` – Gödel77 Jul 12 '14 at 14:57
  • The problem is that when the activity gets destroyed (meaning onDestroy() is called), my ArrayList becomes empty and the listview becomes empty. I don't want this to happen. I want the ArrayList to contain the values that you saved no matter what. Meaning even after the activity is destroyed, I want the values to still show up and not to have the view empty. – Vishwa Iyer Jul 12 '14 at 15:21
  • In Method `onResume` you reset your ListView to original State, then it's clear, you can't see any Change. Try to do nothing there! And say me if you get any change. – Gödel77 Jul 12 '14 at 15:26
  • It didn't work. The ListView becomes blank when I reopen the app. – Vishwa Iyer Jul 12 '14 at 16:21
  • 1
    Take a look here http://stackoverflow.com/questions/5630589/shared-preferences-data-remains-stored-if-phone-is-switched-off-or-battery-is-ta and here http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values . You don't have to do anything extra in onDestroy or other Methods, all what you did in `onCreate` remains until you uninstall that app, you opened your SharedPreferences there and you should set/add in your `onActivityResult` this updated ArrayList(inspection) in SharedPreferences or better said, just the new Item. – Gödel77 Jul 12 '14 at 16:37
  • Could you update your answer as to show me what to do with my code? – Vishwa Iyer Jul 12 '14 at 16:49
  • 1
    Vishwa I must go but I recommend you, you consider to use ContentProviders/DB for you want to do it. Here is very clear how you could use http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html or you remain with S'preferences but you don't do it anything in onResume, onDestroy, etc, just create your preferences in onCreate and update in onActivityResult (There you will have to make obviously a commit in your s'preferences and in your ListView a properly setAdapter and notify ). – Gödel77 Jul 12 '14 at 16:56
  • Your idea worked! I sincerely thank-you for the idea. Thank you very very much. – Vishwa Iyer Jul 12 '14 at 17:18