无法使用Arraylist的共享首选项

时间:2015-09-03 18:57:15

标签: android listview arraylist sharedpreferences

这是我的NewList.class中的歌曲列表:http://postimg.org/image/uieab0wuv/我希望在另一个活动中有一个最喜欢的列表,其中包含我在长按星形按钮时获得的歌曲。 我使用本教程(http://androidopentutorials.com/android-how-to-store-list-of-values-in-sharedpreferences/)来调整我的项目,但它不适用于ArrayList

**生成列表的活动**:

    public class NewList  extends Activity implements
    AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

       public static final String ARG_ITEM_ID = "product_list";

           Activity activity;
         ListView productListView;
          ArrayList<Track> tracks;

         SharedPreference sharedPreference;
          private ListView newListView;
          private EditText inputSearch;
          private int TRACK_POSITION;
          private  AdapterExploreListView adapterExploreListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_explore_music);



    newListView = (ListView) findViewById(R.id.newListView);
    Bundle extras = getIntent().getExtras();
    int temp = extras.getInt("id");
    TextView mTextView = (TextView) findViewById(R.id.title_genre);
    mTextView.setText(Consts.genresArray[temp]);
    fillListWithStyle(Consts.genresArray[temp]);
    newListView.setOnItemClickListener(this);
    newListView.setOnItemLongClickListener(this);
    Toast.makeText(getApplicationContext(),
            "Position :" + temp, Toast.LENGTH_LONG)
            .show();


}
private void fillListWithStyle(final String style)
{
    new AsyncTask<Void,Void,ArrayList<Track>>()
    {


        @Override
        protected ArrayList<Track> doInBackground(Void... voids) {
            JsonParser parser = new JsonParser();
            String encodedURL="";
            try {
                encodedURL = URLEncoder.encode(style, "utf-8");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");

        }

        @Override
        protected void onPostExecute(ArrayList<Track> tracks) {
            super.onPostExecute(tracks);

            DataHolder.getInstance().setTracks(tracks);

             adapterExploreListView = new AdapterExploreListView(NewList.this, tracks);
            newListView.setAdapter(adapterExploreListView);
        }
    }.execute();
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    Intent intent = new Intent(this, PlayerActivity.class);
    intent.putExtra(PlayerActivity.TRACK_POSITION, i);
    startActivityForResult(intent, 1);
    TRACK_POSITION=i;

}

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
                               int position, long arg3) {
    ImageView button = (ImageView) view.findViewById(R.id.favbutton);

    String tag = button.getTag().toString();
    if (tag.equalsIgnoreCase("grey")) {
        sharedPreference.addFavorite(activity, tracks.get(position));
        Toast.makeText(activity,
                activity.getResources().getString(R.string.add_favr),
                Toast.LENGTH_SHORT).show();

        button.setTag("red");
        button.setImageResource(R.drawable.favoritespic);
    } else {
        sharedPreference.removeFavorite(activity, tracks.get(position));
        button.setTag("grey");
        button.setImageResource(R.drawable.favoritespicg);
        Toast.makeText(activity,
                activity.getResources().getString(R.string.remove_favr),
                Toast.LENGTH_SHORT).show();
    }

    return true;
}

}

适配器

             public class AdapterExploreListView extends        ArrayAdapter<Track> {
private Context context;
ArrayList<Track> tracks;
SharedPreference sharedPreference;

public AdapterExploreListView(Context context, ArrayList<Track> tracks) {
    super(context, R.layout.row_list_explore, tracks);
    this.context = context;
    this.tracks = new ArrayList<>();

    this.tracks = tracks;
    sharedPreference = new SharedPreference();
}


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

@Override
public Track getItem(int position) {
    return tracks.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}


@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View rowView = view;
    // reuse views
    if (rowView == null) {
        LayoutInflater inflater = LayoutInflater.from(context);
        rowView = inflater.inflate(R.layout.row_list_explore, null);
        // configure view holder
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.title = (TextView) rowView.findViewById(R.id.titleTextView);
        viewHolder.userName = (TextView) rowView.findViewById(R.id.userNameTextView);
        viewHolder.favoriteImg = (ImageView) rowView.findViewById(R.id.favbutton);
        rowView.setTag(viewHolder);
    }

    // fill data
    final ViewHolder holder = (ViewHolder) rowView.getTag();
    Track track = tracks.get(i);
    holder.title.setText(track.getTitle());
    holder.userName.setText(track.getUsername());

    if (checkFavoriteItem(track)) {
        holder.favoriteImg.setImageResource(R.drawable.favoritespic);
        holder.favoriteImg.setTag("red");
    } else {
        holder.favoriteImg.setImageResource(R.drawable.favoritespicg);
        holder.favoriteImg.setTag("grey");
    }


    return rowView;
}
static class ViewHolder {
    TextView title;
    TextView userName;
    ImageView favoriteImg;
}


/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Track checkProduct) {
    boolean check = false;
    List<Track> favorites = sharedPreference.getFavorites(context);
    if (favorites != null) {
        for (Track track : favorites) {
            if (track.equals(checkProduct)) {
                check = true;
                break;
            }
        }
    }
    return check;
}

@Override
public void add(Track track) {
    super.add(track);
    tracks.add(track);
    notifyDataSetChanged();
}

@Override
public void remove(Track track) {
    super.remove(track);
    tracks.remove(track);
    notifyDataSetChanged();
}

}

** SharedPreference类**

           public class SharedPreference {

public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";

public SharedPreference() {
    super();
}

// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, ArrayList<Track> 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, Track track) {
    ArrayList<Track> favorites = getFavorites(context);
    if (favorites == null)
        favorites = new ArrayList<Track>();
    favorites.add(track);
    saveFavorites(context, favorites);
}

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

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

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

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

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

    return (ArrayList<Track>) favorites;
}

}

以及我想要生成收藏列表的活动

    public class ForthActivity extends Activity {
      SharedPreference sharedPreference;
       ArrayList<Track> favorites;
     ListView favoriteList;
     AdapterExploreListView  adapterExploreListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.forthact);
    // Get favorite items from SharedPreferences.
    sharedPreference = new SharedPreference();
    favorites = sharedPreference.getFavorites(ForthActivity.this);

    if (favorites == null) {

    } else {

        if (favorites.size() == 0) {

        }

        favoriteList = (ListView) findViewById(R.id.forthlistview);
        if (favorites != null) {
            adapterExploreListView = new AdapterExploreListView(ForthActivity.this, favorites);
            favoriteList.setAdapter(adapterExploreListView);

            favoriteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View arg1,
                                        int position, long arg3) {

                }
            });

            favoriteList
                    .setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

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

                            ImageView button = (ImageView) view
                                    .findViewById(R.id.favbutton);

                            String tag = button.getTag().toString();
                            if (tag.equalsIgnoreCase("grey")) {
                                sharedPreference.addFavorite(ForthActivity.this,
                                        favorites.get(position));
                                Toast.makeText(
                                        ForthActivity.this,
                                        ForthActivity.this.getResources().getString(
                                                R.string.add_favr),
                                        Toast.LENGTH_SHORT).show();

                                button.setTag("red");
                                button.setImageResource(R.drawable.favoritespic);
                            } else {
                                sharedPreference.removeFavorite(ForthActivity.this,
                                        favorites.get(position));
                                button.setTag("grey");
                                button.setImageResource(R.drawable.favoritespicg);
                                adapterExploreListView.remove(favorites
                                        .get(position));
                                Toast.makeText(
                                        ForthActivity.this,
                                        ForthActivity.this.getResources().getString(
                                                R.string.remove_favr),
                                        Toast.LENGTH_SHORT).show();
                            }
                            return true;
                        }
                    });
        }
    }

}

}

请帮助我。谢谢你!

2 个答案:

答案 0 :(得分:0)

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
                               int position, long arg3) {
    ImageView button = (ImageView) view.findViewById(R.id.favbutton);
    sharedPreference = new SharedPreference();
    String tag = button.getTag().toString();
    if (tag.equalsIgnoreCase("grey")) {
        sharedPreference.addFavorite(NewList.this, tracks.get(position));
        Toast.makeText(NewList.this,
                NewList.this.getResources().getString(R.string.add_favr),
                Toast.LENGTH_SHORT).show();

        button.setTag("red");
        button.setImageResource(R.drawable.favoritespic);
    } else {
        sharedPreference.removeFavorite(NewList.this, tracks.get(position));
        button.setTag("grey");
        button.setImageResource(R.drawable.favoritespicg);
        Toast.makeText(NewList.this,
                NewList.this.getResources().getString(R.string.remove_favr),
                Toast.LENGTH_SHORT).show();
    }

    return true;
}

和此代码

private void fillListWithStyle(final String style)
{ 
new AsyncTask<Void,Void,ArrayList<Track>>()
{ 


    @Override 
    protected ArrayList<Track> doInBackground(Void... voids) {
        JsonParser parser = new JsonParser();
        String encodedURL="";
        try { 
            encodedURL = URLEncoder.encode(style, "utf-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } 
        return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");

    } 

    @Override 
    protected void onPostExecute(ArrayList<Track> trackss) {
        super.onPostExecute(trackss);

        DataHolder.getInstance().setTracks(trackss);

         adapterExploreListView = new AdapterExploreListView(NewList.this,     trackss);
   tracks = trackss;
        newListView.setAdapter(adapterExploreListView);
      } 
   }.execute();
} 

答案 1 :(得分:0)

我解决了我的问题,这些是编辑。我希望它会帮助别人!

在新列表.class

                  @Override
       public boolean onItemLongClick(AdapterView<?> arg0, View view,
                               int position, long arg3) {
    TextView textView4 = (TextView)view.findViewById(R.id.titleTextView);
    TextView textView5 = (TextView)view.findViewById(R.id.userNameTextView);
     n =textView4.getText().toString();
     m=textView5.getText().toString();
     MyObject=new CustomObject(n,m);


    sharedPreference = new SharedPreference();

        sharedPreference.addFavorite(NewList.this, MyObject);
        Toast.makeText(NewList.this,
                NewList.this.getResources().getString(R.string.add_favr),
                Toast.LENGTH_SHORT).show();



    return true;
}

}

  • 收藏活动*

          public class FavActivity extends Activity {
        ListView lv;
      SharedPreference sharedPreference;
      List<CustomObject> favorites;
        ProductListAdapter productListAdapter;
          Activity context = this;
         public static final String FAVORITES = "Favorite";
    
      @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.forthact);
    sharedPreference = new SharedPreference();
    favorites = sharedPreference.getFavorites(context);
    lv = (ListView) findViewById(R.id.forthlistview);
    
    
    fillFavoriteList();
    
    
     }
    
      private void fillFavoriteList() {
    
           if (favorites != null) {
        productListAdapter = new ProductListAdapter(ForthActivity.this, favorites);
        lv.setAdapter(productListAdapter);
        productListAdapter.notifyDataSetChanged();
    
    
      }
    }
    

    }

    SharedPreferences类

     public class SharedPreference {
    
        public static final String PREFS_NAME = "PRODUCT_APP";
       public static final String FAVORITES = "Product_Favorite";
    
      public SharedPreference() {
     super();
      }
    
    // This four methods are used for maintaining favorites.
     public void saveFavorites(Context context, List<CustomObject> favorites) {
    SharedPreferences settings;
    SharedPreferences.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, CustomObject product) {
       List<CustomObject> favorites = getFavorites(context);
      String s=product.getProp1();
    if (favorites == null)
        favorites = new ArrayList<CustomObject>();
    favorites.add(product);
    saveFavorites(context, favorites);
    

    }

      public void removeFavorite(Context context, CustomObject product) {
       ArrayList<CustomObject> favorites = getFavorites(context);
       if (favorites != null) {
        favorites.remove(product);
          saveFavorites(context, favorites);
          }
           }
    
    public ArrayList<CustomObject> getFavorites(Context context) {
       SharedPreferences settings;
       List<CustomObject> favorites;
    
       settings = context.getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    
      if (settings.contains(FAVORITES)) {
        String jsonFavorites = settings.getString(FAVORITES, null);
        Gson gson = new Gson();
        CustomObject[] favoriteItems = gson.fromJson(jsonFavorites,
                CustomObject[].class);
    
        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList<CustomObject>(favorites);
    } else
        return null;
    
    return (ArrayList<CustomObject>) favorites;
    }
    

    }