使用SharedPreferences </item>中的ArrayList <item>中的两个字符串保存自定义项

时间:2014-08-27 11:39:43

标签: android android-intent arraylist sharedpreferences

我不知道如何在共享首选项中使用ArrayList中的两个字符串保存自定义项目。在你告诉我putExtra(String key,String value)之前我回答:我需要像putExtra(String key,String value,String value),或者至少我想是这样。

以下是需要更多代码块的代码块:

items = new ArrayList<Item>();      
items.add(new Item("Item 1", "First Item on the list"));

items.add()最终会在onClick上调用。

这是MyAdapter.java代码:

    import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MyAdapter extends ArrayAdapter<Item> {

        private final Context context;
        private final ArrayList<Item> itemsArrayList;

        public MyAdapter(Context context, ArrayList<Item> itemsArrayList) {

            super(context, R.layout.row, itemsArrayList);

            this.context = context;
            this.itemsArrayList = itemsArrayList;
        }

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

            // 1. Create inflater 
            LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 2. Get rowView from inflater
            View rowView = inflater.inflate(R.layout.row, parent, false);

            // 3. Get the two text view from the rowView
            TextView labelView = (TextView) rowView.findViewById(R.id.label);
            TextView valueView = (TextView) rowView.findViewById(R.id.value);

            // 4. Set the text for textView 
            labelView.setText(itemsArrayList.get(position).getTitle());
            valueView.setText(itemsArrayList.get(position).getDescription());

            // 5. retrn rowView
            return rowView;
        }}

和Item.java

public class Item {

private String title;
private String description;

public Item(String title, String description) {
    super();
    this.title = title;
    this.description = description;
}
// getters and setters...   

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

}

对于任何,特别容易实施的解决方案 - 祝福你:)


编辑:Lista.java类可以添加更多透明度。它是应用程序的主要活动:

public class Lista extends Activity {

ArrayList<String> list;
ListView listview;
// StableArrayAdapter adapter;
int i = 0;
ArrayList<Item> items;
MyAdapter adapter;
String date_result, what_result;
SharedPreferences preferences;
Map<String,String> map;

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

    preferences = getPreferences(MODE_PRIVATE);

    items = new ArrayList<Item>();      
    items.add(new Item("Item 1", "First Item on the list"));

    adapter = new MyAdapter(this, items);

    listview = (ListView) findViewById(R.id.listView1);

    listview.setAdapter(adapter);
    listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent,
                final View view, int position, long id) {

            final Item item = (Item) parent.getItemAtPosition(position);
            view.animate().setDuration(2000).alpha(0)
                    .withEndAction(new Runnable() {
                        @Override
                        public void run() {
                            items.remove(item);
                            adapter.notifyDataSetChanged();
                            view.setAlpha(1);
                        }
                    });
            return true;
        }
    });
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int arg2,
                long arg3) {
    Intent i = new Intent(Lista.this, MainActivity.class);
//              startActivityForResult(i, 1);
                // Toast.makeText(getApplicationContext(),
                // "this is my Toast message!!! =)",
                // Toast.LENGTH_SHORT).show();
        }

    });
}

private ArrayList<Item> generateData() {
    //pętla przywracająca cele w razie czego tutaj może być

    items.add(new Item("Item 1", "First Item on the list"));
    items.add(new Item("Item 2", "Second Item on the list"));
    items.add(new Item("Item 3", "Third Item on the list"));

    return items;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
    case R.id.action_add:           
        Intent i = new Intent(Lista.this, MainActivity.class);
        startActivityForResult(i, 1);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {
            date_result = data.getStringExtra("date");
            what_result = data.getStringExtra("what");
            items.add(new Item(String.valueOf(what_result), String.valueOf(date_result)));
            adapter.notifyDataSetChanged();
        }
        if (resultCode == RESULT_CANCELED) {
            // Write your code if there's no result
        }
    }
}

public void doThis() {
    items.add(new Item(String.valueOf(what_result), String.valueOf(date_result)));
    adapter.notifyDataSetChanged();
}

public void save() {
    preferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();

    editor
    .putStringSet("myTitles",map.KeySet())
    .putStringSet("myDescriptions", new HashSet(map.Values()))
    .commit();
}}

1 个答案:

答案 0 :(得分:0)

一种简单的方法是将其另存为JSON字符串

JSONObject js=new JSONObject();
JSONArray list=new JSONArray();
JSONObject element=new JSONObject();
element.put("title", "Item 1");
element.put("description", "This is the first item.");
list.put(element);
js.put("list", list);
String saveString=js.toString(); //TODO save this string to pref

然后将其检索为

String fetchString=sp.get("myelementlist"); //Mock code to retrieve String from SP
JSONObject js=new JSONObject(fetchString);
JSONArray list=js.getJSONArray("list"); //Iterate through a for loop on this. and fetch those elements

希望这有帮助。