我有以下代码:
public class CustomGesture extends Activity {
private static Spinner spinner1, spinner2;
private static Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_gesture);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
// list.add("peepu");
// list.add("Cheecki");
List<String> list = new ArrayList<String>();
list.add("cheeku");
list.add("matthu");
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
btn = (Button) findViewById(R.id.btnSubmit);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("MyObject", "");
List<String> list = gson.fromJson(json, null);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
}).start();
}
});
}
}
我得到的错误如下:
04-13 13:50:20.066: E/AndroidRuntime(2358): FATAL EXCEPTION: Thread-5592
04-13 13:50:20.066: E/AndroidRuntime(2358): java.lang.NullPointerException
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.google.gson.internal.$Gson$Preconditions.checkNotNull($Gson$Preconditions.java:35)
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.google.gson.reflect.TypeToken.<init>(TypeToken.java:72)
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.google.gson.reflect.TypeToken.get(TypeToken.java:296)
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.google.gson.Gson.fromJson(Gson.java:801)
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.google.gson.Gson.fromJson(Gson.java:768)
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.google.gson.Gson.fromJson(Gson.java:717)
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.google.gson.Gson.fromJson(Gson.java:689)
04-13 13:50:20.066: E/AndroidRuntime(2358): at com.winacro.Bsquares.CustomGesture$1$1.run(CustomGesture.java:60)
04-13 13:50:20.066: E/AndroidRuntime(2358): at java.lang.Thread.run(Thread.java:841)
我认为这个错误是因为我使用null作为fromJSON中的参数,但是使用什么而不是null参数我想我不能在那里使用列表?
答案 0 :(得分:1)
SharedPrefrences用于存储少量数据,例如标志和静态字符串,您需要一种解决方法来存储json格式的字符串,它适用于非常小的json对象,否则您需要使用sqlite,{{3是一个tutoial