无法使用共享偏好添加收藏列表

时间:2016-07-01 15:57:36

标签: android android-studio android-studio-2.0

这是错误

  

处理:com.example.sonu.travelfreak,PID:15374                                                                                 显示java.lang.NullPointerException                                                                                     在com.example.sonu.travelfreak.PlaceView $ 1.onClick(PlaceView.java:42)                                                                                     在android.view.View.performClick(View.java:4438)                                                                                     在android.widget.CompoundButton.performClick(CompoundButton.java:100)                                                                                     在android.view.View $ PerformClick.run(View.java:18422)                                                                                     在android.os.Handler.handleCallback(Handler.java:733)                                                                                     在android.os.Handler.dispatchMessage(Handler.java:95)                                                                                     在android.os.Looper.loop(Looper.java:136)                                                                                     在android.app.ActivityThread.main(ActivityThread.java:5001)                                                                                     at java.lang.reflect.Method.invokeNative(Native Method)                                                                                     在java.lang.reflect.Method.invoke(Method.java:515)                                                                                     在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:785)                                                                                     在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)                                                                                     在dalvik.system.NativeStart.main(本地方法)

添加收藏的课程

public class PlaceView extends AppCompatActivity{
TextView textView1;
TextView textView2;
ToggleButton toggleButton;
SharedPreference sharedPreference;
@Override
protected void onCreate(final Bundle savedInstanceState) {

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

    textView1= (TextView) findViewById(R.id.textViewActivity);
    textView2= (TextView) findViewById(R.id.detail);
    Intent intent=getIntent();
    final Bundle bundle=intent.getExtras();
    textView1.setText(bundle.getString("Activity"));
    textView2.setText(bundle.getString("Detail"));
   toggleButton= (ToggleButton) findViewById(R.id.toggleButton1);

    toggleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(toggleButton.isChecked()){
                Log.d("check",bundle.getString("position name"));
                Toast.makeText(getApplicationContext(),
                        "Added as favorites",
                        Toast.LENGTH_SHORT).show();
                sharedPreference.addFavorite(getApplicationContext(),bundle.getString("position name"));

        }
            else{

                }

            }


    });

}

}

为recyclerview的每一行设置值的类

public class fav_info {
String string;
public String getname(){
    return string;
}
public void setname(String name){
    this.string=name;
}}

共享优先级类,用于处理添加,删除,保存收藏夹

 import android.content.Context;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import com.google.gson.Gson;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";

public SharedPreference() {
    super();
}


public void saveFavorites(Context context, List<fav_info> favorites) {
    SharedPreferences settings;
    Editor editor;

    settings = context.getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    editor = settings.edit();

    Gson gson = new Gson();
    String jsonFavorites = gson.toJson(favorites);

    editor.putString(FAVORITES, jsonFavorites);

    editor.commit();
}

public void addFavorite(Context context, String string) {
    fav_info fi=new fav_info();
    fi.setname(string);
    List<fav_info> favorites = getFavorites(context);
    if (favorites == null)
        favorites = new ArrayList<fav_info>();
    favorites.add(fi);
    saveFavorites(context, favorites);
}

public void removeFavorite(Context context, fav_info fav_info) {
    ArrayList<fav_info> favorites = getFavorites(context);
    if (favorites != null) {
        favorites.remove(fav_info);
        saveFavorites(context, favorites);
    }
}

public ArrayList<fav_info> getFavorites(Context context) {
    SharedPreferences settings;
    List<fav_info> favorites;

    settings = context.getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    if (settings.contains(FAVORITES)) {
        String jsonFavorites = settings.getString(FAVORITES, null);
        Gson gson = new Gson();
        fav_info[] favoriteItems = gson.fromJson(jsonFavorites,
                fav_info[].class);

        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList<fav_info>(favorites);
    } else
        return null;

    return (ArrayList<fav_info>) favorites;
}}

1 个答案:

答案 0 :(得分:0)

您必须在使用它之前实例化SharedPreference类的对象

所以在访问sharedPreference对象之前添加这一行,

SharedPreference sharedPreference = new SharedPreference();

我想你忘记添加这一行..

注意:在您的代码中,您已将SharedPreference声明为类属性,因此跟随行可以正常,

sharedPreference = new SharedPreference();

由于