将SharePreference字符串保存到ListView

时间:2017-12-26 04:10:11

标签: java android sharedpreferences

我有两项活动。让我们说" A"和" B",活动" A"有一个名为" Get"每次单击后生成一个新字符串,并一次显示一个。活动" A"还有一个按钮"发送"这会将生成的字符串发送到另一个活动" B"。当活动" B"接收数据后,它必须将数据填充到ListView中。

这是一步一步的简单机器步骤:

In Activity "A"
1 - Generate 1 string by pressing the generate button
2 - text will be displayed in textView
3 - "send" button will send the text from textView to another activity "B" ( I'm using sharedPreference)

In Activity "B"
4 - receive the data sent by Activity "A" ( I'm using sharedPreference)
5 - populate string into a listview
6 - go to step 1 again.  

我的麻烦在于每当我点击发送按钮时,它都会将字符串发送到Activity" B"但是当我再次执行相同的任务时,它只会填充最后生成的字符串。换句话说,我的代码只填充一个字符串。

到目前为止,我已尝试过以下代码,我们将不胜感激。

@Override
    public void onClick(View view) {


        switch(view.getId()) {
            case R.id.generateButton:
                generateString();
                break;

            case R.id.send:

                //displayText is a textView
                String text = displayText.getText().toString(); 

                // data sharing using sharedPref
                SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("lado", MODE_PRIVATE).edit();
                editor.putString("mug",text);
                editor.apply();
                break;


        }

---------

活动B

ListView textList = (ListView) findViewById(R.id.list);

        SharedPreferences prefs = getSharedPreferences("lado", MODE_PRIVATE);
        final String text = prefs.getString("mug", "No name defined");

       String[] list = new String[]{name};


        // Create a List from String Array elements
        final List<String> fav_list = new ArrayList<>(Arrays.asList(list));



        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,list);

        // Assign adapter to ListView
        textList.setAdapter(adapter);

3 个答案:

答案 0 :(得分:1)

我不会为此使用共享首选项,而是我只是将列表作为A活动的intent中的额外传递。像这样:

List<String> list = new ArrayList<String>();
list.add("hello");
list.add("good");
list.add("bye");
JSONArray array = new JSONArray(list);
Intent goToNextActivity = new Intent(getApplicationContext(), YourActivity.class);
goToNextActivity.putExtra("words", array.toString());
startActivity(goToNextActivity);

然后在B活动中,您可以访问此数据:

String words = getIntent().getStringExtra("words");
JSONArray array = new JSONArray(words);

答案 1 :(得分:0)

您可以使用以下解决方案

    @Override
public void onClick(View view) {


    switch(view.getId()) {
        case R.id.generateButton:
            //declare a public list
            list.add(generateString());
            break;

        case R.id.send:

            //displayText is a textView
            JSONArray data=new JSONArray(list);

            // data sharing using sharedPref
            SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("lado", MODE_PRIVATE).edit();
            editor.putString("mug",data.toString());
            editor.apply();
            break;


    }

活动B

    ListView textList = (ListView) findViewById(R.id.list);
    // receiving data from MapsActivity
    SharedPreferences prefs = getSharedPreferences("lado", MODE_PRIVATE);
    final String text = prefs.getString("mug", "No name defined");

    JSONArray data=new JSONArray(text);


    // Create a List from String Array elements
    final List<String> fav_list = new ArrayList<>();


     if (data != null) { 
      for (int i=0;i<data.length();i++){ 
         fav_list.add(data.getString(i));
      } 
     } 



    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1,fav_list );

    // Assign adapter to ListView
    textList.setAdapter(adapter);

答案 2 :(得分:0)

添加以下型号:

<强> Dictionary.java

class Dictionary implements Serializable {
    private List<Words> wordsList = new ArrayList<>();


    List<Words> getWordsList() {
        return wordsList;
    }

    void setWordsList(List<Words> wordsList) {
        this.wordsList = wordsList;
    }
}

<强> Words.java

public class Words implements Serializable {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

活动A

@Override
    public void onClick(View view) {


        switch(view.getId()) {
            case R.id.generateButton:
                generateString();
                break;

            case R.id.send:

                //displayText is a textView
                String text = generateButton.getText().toString(); 

               SharedPreferences pref = this.getSharedPreferences("lado", Context.MODE_PRIVATE);



                Words words = new Words();
                words.setName(text);
                List<Words> wordsList = new ArrayList<>();

                Gson gson = new Gson();
                Dictionary dictionary = gson.fromJson(pref.getString("word", ""), Dictionary.class);
                if (dictionary != null && dictionary.getWordsList() != null) {
                    wordsList.addAll(dictionary.getWordsList());
                    dictionary.setWordsList(wordsList);
                    wordsList.add(words);
                } else {
                    dictionary = new Dictionary();
                    wordsList.add(words);
                    dictionary.setWordsList(wordsList);
                }
                SharedPreferences.Editor editor = pref.edit();
                editor.putString("word", new Gson().toJson(dictionary));
                editor.commit();

                break;


        }

活动B

SharedPreferences pref = getSharedPreferences("lado", MODE_PRIVATE);

 List<String> list = new ArrayList<>();
Gson gson = new Gson();
Dictionary dictionary = gson.fromJson(pref.getString("word", ""), Dictionary.class);
if (dictionary != null)
    for (Words words : dictionary.getWordsList()) {
        list.add(words.getName());
    }
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, list);

// Assign adapter to ListView
textList.setAdapter(adapter);

//**Remove when click on item**
textList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Gson gson = new Gson();
        Dictionary dictionary = gson.fromJson(pref.getString("word", ""), Dictionary.class);
        for (Words words :
                dictionary.getWordsList()) {
            if (words.getName().equalsIgnoreCase(list.get(i))) {
                dictionary.getWordsList().remove(words);
                list.remove(i);
                break;
            }
        }
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("word", new Gson().toJson(dictionary));
        editor.commit();

        adapter.notifyDataSetChanged();
    }
});