将字符串保存到数组列表以创建收藏夹列表

时间:2018-10-28 08:51:46

标签: android

我有一个项目,可以显示故事的网格视图。 我想将喜欢的网格视图添加到我的项目中。在我的gridview的项目中,我添加了一个imageview来处理此操作(如&不同),如下所示: 首先,我检查我的名称是否存在于我的数组中,然后设置标记,然后在imageview的onclick中将其添加到我的数组字符串中: 我的问题是,当我喜欢我的故事时,它会添加到我的数组中并轻松显示在我最喜欢的故事中,但是当我再次单击imageview以使其不喜欢该故事时,它再次添​​加到数组列表中两次,并在if中运行我的代码。它永远都不会消失。

public class BinderData extends BaseAdapter {

// XML node keys
static final String KEY_TAG = "data"; // parent node
static final String KEY_ID = "id";
static final String KEY_STORYNAME = "stroryName";
static final String KEY_STORYDESC = "stroryDesc";
static final String KEY_STORYPIC = "stroryPic";
static final String KEY_STORYMUSIC = "stroryMusic";
BinderData bindingData;
LayoutInflater inflater;
List<HashMap<String, String>> DataCollection;
ViewHolder holder;
Context context;


public BinderData(Context act, List<HashMap<String, String>> map) {

    this.DataCollection = map;
    this.context = act;
    inflater = (LayoutInflater) act
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


public int getCount() {
    // TODO Auto-generated method stub
    return DataCollection.size();
}

public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

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

    View vi = convertView;
    if (convertView == null) {

        vi = inflater.inflate(R.layout.grid_item, null);
        holder = new ViewHolder();
        holder.namestory = (TextView) vi.findViewById(R.id.display_name);
        holder.imgstory = (ImageView) vi.findViewById(R.id.img);
        holder.fav_btn = (ImageView) vi.findViewById(R.id.favbtn);

        vi.setTag(holder);
    } else {
        holder = (ViewHolder) vi.getTag();
    }






    holder.namestory.setText(DataCollection.get(position).get(KEY_STORYNAME));
    Typeface type = Typeface.createFromAsset(context.getAssets(), "fonts/myfont.ttf");
    holder.namestory.setTypeface(type);



    String json = StoryApp.prefs.getString("name", null);
    if ((json != null ? json.length() : 0) == 0) {

        holder.fav_btn.setTag("unlike");
        holder.fav_btn.setImageResource(R.drawable.unlike);
    } else {

        Gson gson1 = new Gson();
        Gson gson2 = new Gson();
        Gson gson3 = new Gson();
        Gson gson4 = new Gson();
        String json1 = StoryApp.prefs.getString("name", null);
        String json2 = StoryApp.prefs.getString("desc", null);
        String json3 = StoryApp.prefs.getString("pic", null);
        String json4 = StoryApp.prefs.getString("music", null);

        Type type1 = new TypeToken<ArrayList<String>>() {
        }.getType();
        My_array.stroryName_ = gson1.fromJson(json1, type1);
        My_array.stroryDesc_ = gson2.fromJson(json2, type1);
        My_array.stroryPic_ = gson3.fromJson(json3, type1);
        My_array.stroryMusic_ = gson4.fromJson(json4, type1);
    }



    if (My_array.stroryName_.contains(DataCollection.get(position).get(KEY_STORYNAME))) {
        Log.i("mahsa",My_array.stroryName_+"\n"+DataCollection.get(position).get(KEY_STORYNAME));
        holder.fav_btn.setImageResource(R.drawable.likee);
       holder.fav_btn.setTag("like");

    } else {
        holder.fav_btn.setImageResource(R.drawable.unlike);
        holder.fav_btn.setTag("unlike");

    }


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

            if (holder.fav_btn.getTag().equals("like")){

                My_array.stroryName_.remove(DataCollection.get(position).get(KEY_STORYNAME));
                My_array.stroryDesc_.remove(DataCollection.get(position).get(KEY_STORYDESC));
                My_array.stroryPic_.remove(DataCollection.get(position).get(KEY_STORYPIC));
                My_array.stroryMusic_.remove(DataCollection.get(position).get(KEY_STORYMUSIC));
                holder.fav_btn.setImageResource(R.drawable.unlike);
                Log.i("mm4","like"+holder.fav_btn.getTag());
                Log.i("mm5", My_array.stroryName_ + "\n" + My_array.stroryDesc_ + "\n" + My_array.stroryPic_ + "\n+" + My_array.stroryMusic_);

                SharedPreferences.Editor editor = StoryApp.prefs.edit();
                Gson gson1 = new Gson();
                Gson gson2 = new Gson();
                Gson gson3 = new Gson();
                Gson gson4 = new Gson();
                String json1 = gson1.toJson(My_array.stroryName_);
                String json2 = gson2.toJson(My_array.stroryDesc_);
                String json3 = gson3.toJson(My_array.stroryPic_);
                String json4 = gson4.toJson(My_array.stroryMusic_);
                editor.putString("name", json1);
                editor.putString("desc", json2);
                editor.putString("pic", json3);
                editor.putString("music", json4);
                editor.apply();


                holder.fav_btn.setTag("unlike");
                Log.i("mm6","like"+holder.fav_btn.getTag());



            }else {

                My_array.stroryName_.add(DataCollection.get(position).get(KEY_STORYNAME));
                My_array.stroryDesc_.add(DataCollection.get(position).get(KEY_STORYDESC));
                My_array.stroryPic_.add(DataCollection.get(position).get(KEY_STORYPIC));
                My_array.stroryMusic_.add(DataCollection.get(position).get(KEY_STORYMUSIC));
                holder.fav_btn.setImageResource(R.drawable.likee);
                Log.i("mm1","unlike"+holder.fav_btn.getTag());
                Log.i("mm2", My_array.stroryName_ + "\n" + My_array.stroryDesc_ + "\n" + My_array.stroryPic_ + "\n+" + My_array.stroryMusic_);
                holder.fav_btn.setTag("like");
                SharedPreferences.Editor editor = StoryApp.prefs.edit();
                Gson gson1 = new Gson();
                Gson gson2 = new Gson();
                Gson gson3 = new Gson();
                Gson gson4 = new Gson();
                String json1 = gson1.toJson(My_array.stroryName_);
                String json2 = gson2.toJson(My_array.stroryDesc_);
                String json3 = gson3.toJson(My_array.stroryPic_);
                String json4 = gson4.toJson(My_array.stroryMusic_);
                editor.putString("name", json1);
                editor.putString("desc", json2);
                editor.putString("pic", json3);
                editor.putString("music", json4);
                editor.apply();
                Log.i("mm3","like"+holder.fav_btn.getTag());

            }

            bindingData = new BinderData(StoryApp.context, DataCollection);
            gridView.setAdapter(bindingData);

        }


    });


    // Setting an image
    InputStream is = null;
    AssetManager assetManager = vi.getContext().getAssets();

    try {
        is = assetManager.open("img/" + DataCollection.get(position).get(KEY_STORYPIC));
    } catch (IOException e) {
        e.printStackTrace();
    }

    final Bitmap bitmap = BitmapFactory.decodeStream(is);
    holder.imgstory.setImageBitmap(bitmap);
    long itemId = getItemId(position);


    return vi;
}

static class ViewHolder {
    TextView namestory;
    ImageView imgstory;
    ImageView fav_btn;
}

这是我的活动:

 public class StoryList_Activity extends Activity {

// XML node keys
static final String KEY_TAG = "data";
static final String KEY_ID = "id";
static final String KEY_STORYNAME = "stroryName";
static final String KEY_STORYDESC = "stroryDesc";
static final String KEY_STORYPIC = "stroryPic";
static final String KEY_STORYMUSIC = "stroryMusic";

// List items 
public static GridView gridView;
public static List<HashMap<String, String>> DataCollection;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_storylist);

    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(getAssets().open("data.xml"));
        DataCollection = new ArrayList<HashMap<String, String>>();
        // normalize text representation
        doc.getDocumentElement().normalize();
        NodeList placeList = doc.getElementsByTagName("data");
        HashMap<String, String> map = null;
        for (int i = 0; i < placeList.getLength(); i++) {
            map = new HashMap<String, String>();
            Node firstplaceNode = placeList.item(i);
            if (firstplaceNode.getNodeType() == Node.ELEMENT_NODE) {
                Element firstplaceElement = (Element) firstplaceNode;

                NodeList idList = firstplaceElement.getElementsByTagName(KEY_ID);
                Element firstIdElement = (Element) idList.item(0);
                NodeList textIdList = firstIdElement.getChildNodes();
                map.put(KEY_ID, ((Node) textIdList.item(0)).getNodeValue().trim());

                NodeList story_name = firstplaceElement.getElementsByTagName(KEY_STORYNAME);
                Element story_nameElement = (Element) story_name.item(0);
                NodeList txtstory_name = story_nameElement.getChildNodes();
                map.put(KEY_STORYNAME, ((Node) txtstory_name.item(0)).getNodeValue().trim());

                NodeList story_desc = firstplaceElement.getElementsByTagName(KEY_STORYDESC);
                Element story_descElement = (Element) story_desc.item(0);
                NodeList txtstory_descElement = story_descElement.getChildNodes();
                map.put(KEY_STORYDESC, ((Node) txtstory_descElement.item(0)).getNodeValue().trim());

                NodeList story_pic = firstplaceElement.getElementsByTagName(KEY_STORYPIC);
                Element story_picElement = (Element) story_pic.item(0);
                NodeList txtstory_picElement = story_picElement.getChildNodes();
                map.put(KEY_STORYPIC, ((Node) txtstory_picElement.item(0)).getNodeValue().trim());

                NodeList story_music = firstplaceElement.getElementsByTagName(KEY_STORYMUSIC);
                Element story_musicElement = (Element) story_music.item(0);
                NodeList txtstory_musicElement = story_musicElement.getChildNodes();
                map.put(KEY_STORYMUSIC, ((Node) txtstory_musicElement.item(0)).getNodeValue().trim());

                //Add to the Arraylist
                DataCollection.add(map);
            }
        }

        gridView = (GridView) findViewById(R.id.gridview);
        gridView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent i = new Intent();
                i.setClass(StoryList_Activity.this, StoryShow_Activity.class);
                i.putExtra("position", String.valueOf(position));
                i.putExtra("name", DataCollection.get(position).get(KEY_STORYNAME));
                i.putExtra("pic", DataCollection.get(position).get(KEY_STORYPIC));
                i.putExtra("desc", DataCollection.get(position).get(KEY_STORYDESC));
                i.putExtra("music", DataCollection.get(position).get(KEY_STORYMUSIC));
                startActivity(i);
            }
        });

    } catch (IOException ex) {
        Log.e("Error", ex.getMessage());
    } catch (Exception ex) {
        Log.e("Error", "Loading exception");
    }
}


@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
protected void onResume() {
    BinderData bindingData = new BinderData(this, DataCollection);
    gridView.setAdapter(bindingData);
    bindingData.notifyDataSetChanged();
    super.onResume();
}

这是我最喜欢的活动:

  public class Favorite_list extends Activity {

static GridView gridView;
static Adaptor adaptor;
static String[] names, des, pic,music;

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

    gridView = (GridView) findViewById(R.id.gridview);

    names = My_array.stroryName_.toArray(new String[0]);
    des = My_array.stroryDesc_.toArray(new String[0]);
    pic = My_array.stroryPic_.toArray(new String[0]);
    music = My_array.stroryMusic_.toArray(new String[0]);
    adaptor = new Adaptor(getApplicationContext(), names);
    gridView.setAdapter(adaptor);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {


        }

    });
}

public static class Adaptor extends ArrayAdapter<String> {

    private final Context context;

    private final String[] names;


    public Adaptor(Context context, String[] names) {
        super(context, R.layout.grid_item);
        this.context = context;
        this.names = names;

    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rowView = inflater.inflate(R.layout.grid_item2, parent, false);

        TextView name = (TextView) rowView.findViewById(R.id.display_name);
        ImageView img= (ImageView) rowView.findViewById(R.id.img);
        ImageView del= (ImageView) rowView.findViewById(R.id.delbtn);
        // Setting an image
        InputStream is = null;
        AssetManager assetManager = rowView.getContext().getAssets();

        try {
            is = assetManager.open("img/" + pic[position]);
        } catch (IOException e) {
            e.printStackTrace();
        }

        final Bitmap bitmap = BitmapFactory.decodeStream(is);
        img.setImageBitmap(bitmap);
        name.setText(names[position]);

        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                My_array.stroryName_.remove(names[position]);
                My_array.stroryDesc_.remove(des[position]);
                My_array.stroryPic_.remove(pic[position]);
                My_array.stroryMusic_.remove(music[position]);
                notifyDataSetChanged();
                SharedPreferences.Editor editor = StoryApp.prefs.edit();
                Gson gson = new Gson();
                String json = gson.toJson(My_array.stroryName_);

                editor.putString("name", json);
                editor.apply();
                refresh();

            }
        });

        return rowView;
    }

}

public static void refresh() {

    names = My_array.stroryName_.toArray(new String[0]);
    des = My_array.stroryDesc_.toArray(new String[0]);
    pic = My_array.stroryPic_.toArray(new String[0]);
    music = My_array.stroryMusic_.toArray(new String[0]);
    adaptor = new Adaptor(StoryApp.context, names);
    gridView.setAdapter(adaptor);

}

@Override
public void onBackPressed() {

    super.onBackPressed();
}

@Override
protected void onResume() {
    if ((My_array.stroryName_ != null ? My_array.stroryName_.size() : 0) == 0) {

    } else {
        Gson gson1 = new Gson();
        Gson gson2 = new Gson();
        Gson gson3 = new Gson();
        Gson gson4 = new Gson();
        String json1 = StoryApp.prefs.getString("name", null);
        String json2 = StoryApp.prefs.getString("desc", null);
        String json3 = StoryApp.prefs.getString("pic", null);
        String json4 = StoryApp.prefs.getString("music", null);
        Type type1 = new TypeToken<ArrayList<String>>() {
        }.getType();
        My_array.stroryName_ = gson1.fromJson(json1, type1);
        My_array.stroryDesc_ = gson2.fromJson(json2, type1);
        My_array.stroryPic_ = gson3.fromJson(json3, type1);
        My_array.stroryMusic_ = gson4.fromJson(json4, type1);
    }

    refresh();
    super.onResume();
}

}

1 个答案:

答案 0 :(得分:0)

请像这样holder.fav_btn.setTag("Unlike");进行更改,您将其表示为“喜欢” 在if (holder.fav_btn.getTag().equals("like")){....}

还要更改其他部分holder.fav_btn.setTag("like");,您在这些情况下错误地添加了错误的标签