重新打开应用程序后如何检索editText保存的值?

时间:2014-04-15 23:03:08

标签: android listview sharedpreferences

我创建了一个listview活动,可以在项目点击时打开对话框。在对话框中,用户可以在同一列表视图项中输入保存在textView中的不同值。这是完美的,问题是如果我关闭应用程序,当我再次打开它时,保存的值不再存在。关闭申请后如何保持价值?谢谢!!!

NoteAdapter.java

        package com.cngcnasaud.orar;

import java.util.Arrays;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class NoteAdapter extends BaseAdapter {

    String[] result;
    Context context;
    int[] imageId;
    private static LayoutInflater inflater = null;
    private Dialog dialog;
    String[] savedEntries;
    String[] saved = null;

    public NoteAdapter(Note note, String[] prgmNameList, String[] saved) {
        // TODO Auto-generated constructor stub
        result = prgmNameList;
        context = note;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (saved == null) {
            savedEntries = new String[result.length];
            Arrays.fill(savedEntries, "");
        } else
            savedEntries = saved;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return result.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return savedEntries[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder {
        TextView tv;
        ImageView img;
        public TextView text;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        final Holder holder = new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.note_items, null);
        holder.tv = (TextView) rowView.findViewById(R.id.textView1);
        holder.text = (TextView) rowView.findViewById(R.id.textView2);
        holder.text.setText(savedEntries[position]);
        holder.img = (ImageView) rowView.findViewById(R.id.imageView1);

        rowView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog = new Dialog(context);
                dialog.setContentView(R.layout.dialog);
                dialog.setTitle("Materie:" + result[position]);

                final EditText txtMode = (EditText) dialog
                        .findViewById(R.id.dialog);
                Button btnSave = (Button) dialog.findViewById(R.id.bsave);

                btnSave.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        String data = txtMode.getText().toString();
                        holder.text.setText(data);

                        savedEntries[position] = data;

                        dialog.dismiss();
                        Log.d("data", data);
                    }
                });
                dialog.show();
            }

        });
        return rowView;
    }

}

Note.java

    package com.cngcnasaud.orar;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;

import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Note extends Activity {

    public static final ListAdapter NoteAdapter = null;
    ListView lv;
    Context context;
    ArrayList<?> prgmName;
    TextView text;

    public static String[] prgmNameList = { "Romana   - ", "Matematica   - ",
            "Lb. Engleza   - ", "Lb. Germana/Franceza - ", "Istorie   - ",
            "Geografie   - ", "Biologie   - ", "Fizica   - ", "Ed. Fizica   - " };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_listview);

        text = (TextView) findViewById(R.id.textView2);

        context = this;

        lv = (ListView) findViewById(R.id.listView);
        lv.setAdapter(new NoteAdapter(this, prgmNameList, null));

    }

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

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub

        NoteAdapter adapter = (NoteAdapter) lv.getAdapter();

        // Variable is public for clarity.
        String toSave = EncodeDecode.encode(adapter.savedEntries);
        SharedPreferences.Editor editor = getSharedPreferences("LV Data",
                MODE_PRIVATE).edit();
        editor.putString("TVEntries", toSave);
        editor.commit();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub

        SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
        String encoded = prefs.getString("TVEntries", "");

        String[] entries;
        if (encoded.equals(""))
            entries = null;
        else
            entries = EncodeDecode.decode(encoded);

        NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
        adapter.savedEntries = entries;
        lv.setAdapter(adapter);

        super.onResume();
    }

}

1 个答案:

答案 0 :(得分:1)

这是一个涉及SharedPreferences的建议解决方案:

  • 首先,将一个String[]实例变量添加到Adapter类中。这将包含您要保存的内容(TextViews中的字段。初始化此构造函数。

    public NoteAdapter(Note note, String[] saved, String[] prgmNameList, int[] prgmImages) {
      result=prgmNameList;
      context=note;
      imageId=prgmImages;
      inflater = ( LayoutInflater )context.
             getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
      /**********INSERTED CODE********/
      if(saved == null) {
        savedEntries = new String[result.length];`
        Arrays.fill(savedEntires, "");
      }
      else
        savedEntries = saved;
      /****************************/
    
    
    }
    
  • 同时修改您的覆盖getItem()方法以返回savedEntires中的相应元素:

    @Override
    public Object getItem(int position) {
     return savedEntries[position];
    }
    
  • 每当您更新TextView时,请相应地更新列表:

    @Override
    public void onClick(View v) {
    
      String data = txtMode.getText().toString();
      holder.text.setText(data);
    
      /***INSERTED CODE****/  
      savedEntries[position] = data;
      /*******************/
    
      dialog.dismiss();
      Log.d("data", data);
    
    }
    
  • 我们将使用String-String对将此数组保存在SharedPreferences中。由于字符串可能包含任何字符,因此找到单个分隔符很困难/效率低下。我实现了一个名为EncodeDecode的类,它可以将String数组编码为单个格式化的String,并在此处将其解码回String数组:https://gist.github.com/liangricha/10759438。我将使用此课程转换/转换savedEntries

  • 每当您想保存savedEntries(在onStop()中)时,只需执行以下代码:

    ListView lv = //... get reference
    NoteAdapter adapter = (NoteAdapter)lv.getAdapter();
    
    //Variable is public for clarity.
    String toSave = EncodeDecode.encode(adapter.savedEntries);
    SharedPreferences.Editor editor = getSharedPreferences("LV Data", MODE_PRIVATE).editor();
    editor.putString("TVEntries", toSave);
    editor.commit();
    
  • 如果要检索TextView条目的String数组(在onResume()中),请执行:

    SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
    String encoded = prefs.getString("TVEntries", "");
    
    String[] entries
    if(encoded.equals(""))
      entries = null;
    else
      entries = EncodeDeocde.decode(encoded);
    
    NoteAdapter adapter = (NoteAdapter)lv.getAdapter();
    adapter.savedEntries = entries;
    lv.setAdapter(adapter);
    

    然后,在&#39; NoteAdapter&#39;的getView()方法中,将TextView的字段设置为savedEntries中的相应条目:

     holder.text.setText(savedEntries[position]);