从共享首选项对象检索数据,然后将其显示在ListView上

时间:2015-10-09 20:44:43

标签: android arraylist hashmap sharedpreferences

我使用共享首选项对象保存用户的数据,然后将该数据复制到HashMap对象中。将数据复制到Hasmap对象后,我使用Arraylist对象在ListView中显示我的所有数据。

当我仅使用Textview而不是ListView进行测试时,它可以正常工作。我可以显示数据,但它只显示一条记录(键/值对)。我想使用ListView,以便显示存储在共享首选项对象中的所有数据。

下面是将数据从共享首选项对象复制到HashMap然后使用arrraylist在ListView上显示它的类:

public class DisplayMyTestsActivity extends Activity {

    String STName;    
    TextView STNameTextView, STValueTextView;
    ListView STListView;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.displaymytests);

        //Use SharedPreferences to save the key/value pairs
        SharedPreferences sharedPref = getSharedPreferences("STData", Context.MODE_PRIVATE);

        //save "special test name" in String 'testName'
        String testName = sharedPref.getString("specialTestName", STName);

        //save special test Value in String 'testValue'
       boolean testValue = sharedPref.getBoolean("specialTestValue", false);
       //save the boolean value in a String so that it can be displayed on an edit text
       String testValueStr = String.valueOf(testValue);

       //here I tested if I can display my data on a textView instead of a ListView and it works
       // Display the Name of the Special Test on a TextView 
       STNameTextView = (TextView) findViewById(R.id.STNameView1);
       STNameTextView.setText(testName);

       //Display the Value (positive or negative) of the Special Test on a TextView
       STValueTextView = (TextView) findViewById(R.id.STValueView1);
       STValueTextView.setText(testValueStr);

       //to edit the data or add data inside my file "STData"
       SharedPreferences.Editor editor = sharedPref.edit();

       //Define a HashMap object
       Map<String, String> map = new HashMap<String, String>();

       //Store key/value pair data from shared pref in HashMap object
       for (Map.Entry<String, String> entry : map.entrySet())
       {
          editor.putString(entry.getKey(), entry.getValue());
          editor.commit();
       }

       //Pass hashmap object "map" to adapter
       //MyAdapter constructor creates an ArrayList then adds all the data in map to the ArrayList
       //The object "adapter" is now an arraylist that contains all the hashmap data (I created a seperate adapter class)
      MyAdapter adapter = new MyAdapter(map);

      //Point to the listView where data to be displayed - in layout file (displaymytests)
      STListView = (ListView) findViewById(R.id.ST_ListView);

      //Populate the listView with the data from The ArrayList ('adapter')
      STListView.setAdapter(adapter);

     }

 }

这是我的适配器类:

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Map;

public class MyAdapter extends BaseAdapter {
    private final ArrayList mData;

    public MyAdapter(Map<String, String> map) {
        mData = new ArrayList();
        mData.addAll(map.entrySet());
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Map.Entry<String, String> getItem(int position) {
        return (Map.Entry) mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO implement you own logic with ID
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View result;

        if (convertView == null) {
            result = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_adapter_item, parent, false);
        } else {
            result = convertView;
        }

        Map.Entry<String, String> item = getItem(position);

        // TODO replace findViewById by ViewHolder
        ((TextView) result.findViewById(android.R.id.text1)).setText(item.getKey());
        ((TextView) result.findViewById(android.R.id.text2)).setText(item.getValue());

        return result;
    }
}

这是我的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"

    android:weightSum="1"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_weight="0.06">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="STName"
            android:id="@+id/STNameView1"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="40dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="STValue"
            android:id="@+id/STValueView1"
            android:layout_marginLeft="140dp"
            android:layout_marginTop="20dp" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_weight="0.94">

        <ListView
            android:layout_width="wrap_content"
            android:layout_height="387dp"
            android:id="@+id/ST_ListView" />
    </LinearLayout>

</LinearLayout>

我修改了我的代码如下,但仍然给出了错误:“此行不兼容的错误”map = sharedPref.getAll();“”

    //Define a HashMap object
    Map<String, String> map = new HashMap<String, String>();

    // Store key/value pair data from shared pref in HashMap object
    map = sharedPref.getAll();
    //Retrieve the the keys with keySet() and the key/value mappings with entrySet()
    for (Map.Entry<String, ?> entry : map.entrySet())
    for (Map.Entry<String, String> entry : map.entrySet())
    {
        editor.putString(entry.getKey(), entry.getValue());
        editor.commit();
    }

FYI,getAll()返回一个Map(String,?)类型的对象,但我的是Map(String,String)b / c我需要将它传递给 MyAdapter ,并且应该是类型Map(String,String)

1 个答案:

答案 0 :(得分:1)

现在您正在创建一个空Map并将其用于适配器。因此,map.entrySet()上的循环永远不会执行,并且您有一个空列表。

SharedPreferences有一个名为getAll()的方法,可将您的偏好设置为Map。你可能只能使用它。

相关问题