将值从Activity传递到另一个活动中的ListView并保存这些值

时间:2014-07-12 12:34:19

标签: android listview

我有一个应用程序,其中主屏幕是列表视图,然后用户可以单击添加按钮,该按钮将用户带到另一个活动,在那里他/她可以从微调器中选择值,并且在那里&#sa; sa底部的按钮叫做"保存",点击它时将旋转器中的值保存到列表项中,然后用户返回主屏幕,列表视图和新创建的列表项。

这是我的代码:

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

现在,我有保存,但它只保存一个值,我希望它保存多个值。另外,正如您所看到的,我已经尝试实现SharedPreferences类来保存列表的值,以便当用户从多任务处理中删除应用程序后返回到它时,它仍将显示用户之前拥有的值。但是,这不起作用。我尝试过使用onPause和onResume(正如你在上面的代码中看到的那样),但无济于事。我真的很困惑为什么这不起作用,因为我记录了活动暂停/恢复时的值,我可以看到控制台中出现的记录值。我基本上想要的是在列表中保存多个值,而不仅仅是一个,并保存值,以便每当活动被销毁时,列表视图将显示已保存的值,因此不会丢失任何数据。

非常感谢任何帮助。提前谢谢你。

编辑:我已解决了保存问题,但现在我需要能够保存ListView的值,以便当用户重新打开应用时,值仍然存在,并且胜利者消失了。

2 个答案:

答案 0 :(得分:1)

你已经开发了你的主要活动,并且有一个Listview,现在你必须开发如果你单击ListView的项目会发生什么,起点就是那样。

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)

    }
});

在你的主要活动中你必须覆盖onActivityResult方法覆盖以获得这样的返回参数(如果你选择了(1)替代!!!)其中REQUEST_CODE代码区分什么是活动已经呼叫。(可能有很多,因此我们需要区分是否很多)

@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)
    }
}

}

在您调用的Activity中,您可以获取这些传递的参数,例如在onCreate方法中使用以下代码

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

我觉得这是一个很好的开始点,如果你想拥有一些东西,那么你可以看到here 看看return back parameters的Android开发者参考,在那里你可以看到详细的和示例我解释的grosso modo。

我希望,这会引导您找到解决方案

答案 1 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

private final int GET_VALUE=111;

您的列表活动添加按钮

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

您的添加项目激活保存按钮

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

在列表活动中添加项目获取结果

@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"))
        }
      }
   }
}