【问题标题】:Load data from SharedPreferences and populate listview从 SharedPreferences 加载数据并填充列表视图
【发布时间】:2016-07-16 11:42:46
【问题描述】:

我已经为此工作了很长时间,但仍然无法做到正确。我正在尝试创建一个简单的应用程序,允许用户手动将项目添加到列表中,并使用 SharedPreferences 永久存储这些项目。但我一直做错了(顺便说一句,我真的是个编程菜鸟)。任何人都可以提出任何建议吗?非常感谢!

public class Mainmemo extends Activity {
public ArrayList<User> arrayOfUsers = User.getUsers();
public ListView listView;
public CustomUsersAdapter adapter;
public SharedPreferences sharedpref;
public Bundle extra;
public static final String PREFERENCES_TODO = "TODO_List_Shared_Preferences";



@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_list);
    populateUsersList();
}


private void populateUsersList() {


    adapter = new CustomUsersAdapter(this, arrayOfUsers);


    listView = (ListView) findViewById(R.id.lvUsers);
    final TextView textview = (TextView) findViewById(R.id.empty);
    final Button manualaddmemo = (Button) findViewById(R.id.addmemo);
    listView.setEmptyView(textview);
    listView.setAdapter(adapter);
    listView.setItemsCanFocus(false);
    listView.setClickable(true);


    extra = getIntent().getExtras();

    if (extra != null) {
        String text = extra.getString("text");
        String date = extra.getString("dateoftext");
        extra = null;
        savestringtopreferences(text, date);

    }



    manualaddmemo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent newIntent = new Intent(Mainmemo.this, add_memo_to_list.class);
            startActivityForResult(newIntent, 0);
        }
    });
}

private void savestringtopreferences(String text, String date) {


    sharedpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = sharedpref.edit();
    JSONObject obj = new JSONObject();

    try {
        obj.put("Name", text);
        obj.put("Category", date);


    } catch (JSONException e) {
        e.printStackTrace();

    }
    editor.putString("JSON", obj.toString());
    editor.apply();
}
}

所以在这里,我正在尝试使用自定义数组适配器创建一个列表视图,并且在按下按钮 ManualAddDemo 后,它将导航到另一个页面,用户可以在该页面中输入他们想要的任何内容,并且他们输入的任何内容都将被解析回主要活动(连同日期作为另一个字符串)。这样做之后,我尝试将两个字符串都放入 JSONObject 中,然后将其保存在共享首选项中。然后我在 customarrayadapter 中检索数据,以便每次加载列表视图时都会检索数据。

public class CustomUsersAdapter extends ArrayAdapter<User> {
public CustomUsersAdapter(Context context, ArrayList<User> users) {
    super(context, 0, users);
}




@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    User user = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.memolist, parent, false);
    }
    // Lookup view for data population
    TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
    TextView tvdate = (TextView) convertView.findViewById(R.id.date);
    TextView indexview = (TextView) convertView.findViewById(R.id.indexnumber);

    // Populate the data into the template view using the data object
    int sequence = position +1;
    user.index = String.valueOf(sequence);

    SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getContext());
    String name = sharedpref.getString("JSON", "");


        try {

                JSONObject object = new JSONObject(name);


               user.name = object.getString("Name");
                user.date= object.getString("Category");
                indexview.setText(user.index);
                tvName.setText(user.name);
                tvdate.setText(user.date);




        } catch (JSONException e) {
            e.printStackTrace();

        }



    // Return the completed view to render on screen
    return convertView;
}

}

我的用户类:

public class User {
public String name;
public String date;
public String index;

public User( String index, String name, String date) {
    this.index = index;
    this.name = name;
    this.date = date;

}

public static ArrayList<User> getUsers() {
    ArrayList<User> users = new ArrayList<>();





    return users;
}

}

有什么建议吗? Tqvm!

【问题讨论】:

  • 请提及您面临的问题是什么?您是否无法检索存储的项目或究竟是什么问题?
  • 我可以保存我想要的数据,但我无法在我的 customarrayadapter 中检索它...因此,每当我的列表视图运行时,我添加的项目将不会被检索
  • 请检查 JSON 对象的调试集,并检查它是否真的获得了您需要的值。你可以在两个地方检查这个 - 你写作的地方和你尝试阅读的地方。
  • 我检查了一下,似乎我可以正确保存 JSON 对象并在我的 Main Activity 中获取我需要的值,但是我无法在我的自定义数组适配器中加载它

标签: java android listview android-studio


【解决方案1】:
  1. 我相信您正在覆盖共享首选项中的对象。您可能可以存储一个 JSON 数组。添加到它时,您应该首先检索最后一个 写入数组并附加最新的对象。
  2. 您应该使用 sqllite 来存储数据,共享首选项不适用于此类用途。

【讨论】:

    【解决方案2】:

    如评论中所述:

    首先,在你的自定义适配器类中声明构造函数,

        public customAdapter(Context context, List<String> info){
    
    // do whatever you want to do
    
    }
    

    并在 MainActivity 中调用构造函数为:

    CustomAdapter adapter = new CustomAdapter(this, infoList);
    

    【讨论】:

    • 我试过了,但我仍然面临同样的问题。我的 customarrayadapter 似乎无法检索我保存在 sharedpreference 中的数据,这意味着每次加载列表视图时都没有发生任何事情
    • 您是否检查过数据是否插入到首选项中??
    • 我检查了,看来我可以毫无问题地将数据保存到首选项中。我通过尝试在我的主要活动中检索数据进行检查,它工作得非常好。但现在我的问题是我无法在我的自定义阵列适配器上检索它。当我尝试在我的自定义数组适配器上检索首选项数据时,什么都没有发生...
    • 在 MainActivity 中检索您的数据并将列表传递给自定义适配器....将列表作为参数传递给自定义适配器的构造函数并使用该列表显示项目....
    • 你能给我一个示例代码吗?谢谢!
    猜你喜欢
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多