单击收藏夹按钮时更新列表视图

Posted

技术标签:

【中文标题】单击收藏夹按钮时更新列表视图【英文标题】:update listview when click favorites button 【发布时间】:2015-07-31 11:28:39 【问题描述】:

我想在单击ListViewAdapter 类中的按钮 btn 时,更新我的 sqlite 并更改 background of btn ,当 MainActivity 启动并首先单击按钮时,是正确的。但是当我滚动列表时,btn 的背景会恢复到原来的状态,此外,当第二次单击按钮时,不会进行任何更改。 换句话说,不要更新我的列表视图。如何解决?

我在哪里以及如何使用adapter.notifyDataSetChanged();

点击ListViewAdapter 之后?如何在 myListViewAdapter 上获取 adapter at MyActivity

public class ListViewAdapter extends BaseAdapter 

// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<myitems> worldpopulationlist = null;
private ArrayList<myitems> arraylist;
int myfavorit =0;
DataBaseHelper myDbHelper;
SQLiteDatabase db;
Cursor mCursor;

public ListViewAdapter(Context context, List<myitems> worldpopulationlist) 
    mContext = context;
    this.worldpopulationlist = worldpopulationlist;
    inflater = LayoutInflater.from(mContext);
    this.arraylist = new ArrayList<myitems>();
    this.arraylist.addAll(worldpopulationlist);


public class ViewHolder 
    TextView rank;
    TextView country;
    TextView population;
    Button btn;



@Override
public int getCount() 
    return worldpopulationlist.size();


@Override
public myitems getItem(int position) 
    return worldpopulationlist.get(position);


@Override
public long getItemId(int position) 
    return position;


public View getView(final int position, View view, ViewGroup parent) 
    final ViewHolder holder;
    if (view == null) 
        holder = new ViewHolder();

    view = inflater.inflate(R.layout.myitems_list, null);
        // Locate the TextViews in listview_item.xml
        holder.rank = (TextView) view.findViewById(R.id.txt25);
        holder.btn=(Button) view.findViewById(R.id.btnfavor);
        holder.country = (TextView) view.findViewById(R.id.txt26);


        view.setTag(holder);
     else 
        holder = (ViewHolder) view.getTag();
    

    holder.rank.setText(worldpopulationlist.get(position).gettitle());
    holder.country.setText(worldpopulationlist.get(position).getshomare()+"-");

    myfavorit=worldpopulationlist.get(position).getfavoir();


    if(myfavorit==0)
        holder.btn.setBackgroundResource(R.drawable.ic_launcher);
    

    else
        holder.btn.setBackgroundResource(R.drawable.star);

    




    holder.btn.setOnClickListener(new OnClickListener() 

        @Override
        public void onClick(View v) 
            myDbHelper = new DataBaseHelper(mContext.getApplicationContext());
            myDbHelper = new DataBaseHelper(mContext);

            try 
                myDbHelper.createDataBase();                   

            catch (IOException ioe) 
                throw new Error("Unable to create database");
                    
            try myDbHelper.openDataBase();        
            catch (SQLException sqle) sqle.printStackTrace();

            

            String rr=worldpopulationlist.get(position).getprimaryid();
            db = myDbHelper.getWritableDatabase();

        switch (worldpopulationlist.get(position).getfavoir()) 
        case 0:

                mCursor= db.rawQuery("UPDATE khotbe SET favorites = 1 WHERE my_id ="+rr+"  ;",null);
                mCursor.moveToFirst();
                holder.btn.setBackgroundResource(R.drawable.star);              
                Toast.makeText(mContext, "به لیست علاقه مندی ها اضافه شد", Toast.LENGTH_SHORT).show();

            break;
            case 1:
                mCursor= db.rawQuery("UPDATE khotbe SET favorites = 0 WHERE my_id ="+rr+"  ;",null);
                mCursor.moveToFirst();
                holder.btn.setBackgroundResource(R.drawable.ic_launcher);
                Toast.makeText(mContext, "از لیست علاقه مندی های حذف گردید", Toast.LENGTH_SHORT).show();
                break;

        default:
            break;
        

        
    );

和类myitems

public class myitems 

    private String title;
    private String field_translation_id;
    private String shomare;
    private String primaryid;

    private int favorit;


    public myitems(String title,String field_translation_id,String shomare,String primaryid,int favorit)
        this.title=title;
        this.field_translation_id=field_translation_id;
        this.shomare=shomare;
        this.primaryid=primaryid;
        this.favorit=favorit;

    

    public String gettitle()


        return this.title;

    

public String get_field_translation_id()


        return this.field_translation_id;

    

    public String getshomare()
    


    return this.shomare;


    
    public String getprimaryid()


    return this.primaryid;



    public int getfavoir()

        return this.favorit;


    




和 MainActivity

public class towkhotbe extends ActionBarActivity   
    DataBaseHelper myDbHelper;

    ListView mylist;
    ArrayList<String> iran,arr_intityid,arrshomare,primarykeyarrlist;
    String[] fa,mysid,myshomare,primarykeyarr;
    SQLiteDatabase db;
    Cursor mCursor;
    int translate;
    EditText mysearch;
    int [] favorit;



    ArrayList<Integer> favor;

    ListViewAdapter adapter;


    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    @SuppressWarnings("deprecation")
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    android.support.v7.app.ActionBar actionbar;
    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter sadapter;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tow_khotbe);


            Intent myintent=getIntent();
            translate=myintent.getExtras().getInt("translate");

        mylist=(ListView)findViewById(R.id.mylist);
        mysearch=(EditText)findViewById(R.id.edtxtsearch);

        iran=new ArrayList<String>();
        arr_intityid=new ArrayList<String>();
        arrshomare=new ArrayList<String>();
        primarykeyarrlist=new ArrayList<String>();
        favor=new ArrayList<Integer>();


    


    @Override
    protected void onResume() 
        // TODO Auto-generated method stub
        super.onResume();
        myDbHelper = new DataBaseHelper(this.getApplicationContext());
        myDbHelper = new DataBaseHelper(this);

        try 

            myDbHelper.createDataBase();
        //  contentLog.append("Database Created\n");
                           

        catch (IOException ioe) 
            throw new Error("Unable to create database");
                


        try 
                                myDbHelper.openDataBase();

               


        catch (SQLException sqle) 

            sqle.printStackTrace();

        

        ArrayList<myitems> arraylist = new ArrayList<myitems>();
        db = myDbHelper.getReadableDatabase();

        mCursor= db.rawQuery("SELECT field_translation_id_value,title,translate,my_id,favorites  FROM khotbe"
                + " WHERE translate ="+translate+" ORDER BY field_translation_id_value ASC   ;",null);

        int i = 1;

        mCursor.moveToFirst();

        while (mCursor.isAfterLast() == false) 

    //  contentLog.append("(" + i++ + ")\t\t" + mCursor.getString(1) + "\n");

            iran.add(mCursor.getString(1));
            arr_intityid.add(mCursor.getString(0));
            primarykeyarrlist.add(mCursor.getString(3));
            favor.add(mCursor.getInt(4));
            arrshomare.add(""+i++);
            mCursor.moveToNext();

    

         fa= new String [iran.size()];
         fa=iran.toArray(fa);

           mysid= new String [arr_intityid.size()];                     
           mysid=arr_intityid.toArray(mysid);

           primarykeyarr= new String [primarykeyarrlist.size()];                        
           primarykeyarr=primarykeyarrlist.toArray(primarykeyarr);



           myshomare=new String[arrshomare.size()];
           myshomare=arrshomare.toArray(myshomare);

           favorit =new int[favor.size()];
           for (int t= 0; t < favor.size(); t++) 

               favorit[t]=favor.get(t).intValue();

        

           mCursor.moveToPosition(0);
         for (int j = 0; j < fa.length; j++) 

               myitems qqq= new myitems(fa[j],mysid[j],myshomare[j],primarykeyarr[j],favorit[j]);

               arraylist.add(qqq);

           

           adapter=new ListViewAdapter(this, arraylist);
           mylist.setAdapter(adapter);


           Button btn=(Button)findViewById(R.id.btnfavor);
           btn.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View v) 

                Toast.makeText(towkhotbe.this, "11111111", Toast.LENGTH_SHORT).show();

            
        );



    

【问题讨论】:

使用 notifyDatasetChanged 方法 @Nilesh 可以进一步解释一下 【参考方案1】:

在您喜欢的按钮的onClick() 中使用adapter.notifyDataSetChanged();

示例

Button favoriteButton = (Button) findViewById(R.id.bFavButton);
favoriteButton.setOnClickListener(new View.OnClickListener()
    @Override
    public void onClick(View view)
        //Add or remove items to list
        ..............

        //Hey, adapter! Data set updated!
        adapter.notifyDataSetChanged();
    
);

【讨论】:

@Shifar Shifz 如何将 MainActivity 中的适配器放入 ListViewAdapter? 您可以在Activity 的方法之外声明ListViewAdapter,并且可以从类的任何位置调用。您必须阅读此luan-itworld.blogspot.in/2013/08/… @ Shifar Shifz 当我在 MainActivity 中使用 onclick 时,应用程序无法运行,但在 ListViewAdapter 中的 onclick 可以。为什么? 我认为您在按钮的onClick() 中犯了一些错误。发布您的完整活动。 @Shifar Shifz 我要更改 MainActiviyt 请再看一遍

以上是关于单击收藏夹按钮时更新列表视图的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI 列表未使用 ForEach 正确更新

列表视图中的收藏按钮问题 Flutter/Dart

SwiftUI CoreData - 如何更新获取请求和列表

使用 SharedPreferences 保存字符串

单击时所有按钮同时触发

单击按钮时如何更新列表视图?