如何在android中刷新列表视图

时间:2015-05-16 05:38:25

标签: android listview refresh

我正在创建一个Android应用程序,它包含一个由数据库中的数据填充的列表视图。

这里我需要删除数据库中的数据以及列表视图并刷新列表视图。

我同时使用了notifyOnDataSetChanged()notifyOnDataSetInvalidated()

它不适合我,请帮助我

package com.developer.milanandroid;

import android.app.ActionBar;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.gc.materialdesign.widgets.Dialog;
import com.milan.emptylayout.EmptyLayout;
import com.milan.lib.progressgenarator.lib.ProgressGenerator;
import com.milan.lib.progressgenarator.lib.ProgressGenerator.OnCompleteListener;
import com.milan.swipemenulistview.SwipeMenu;
import com.milan.swipemenulistview.SwipeMenuCreator;
import com.milan.swipemenulistview.SwipeMenuItem;
import com.milan.swipemenulistview.SwipeMenuListView;
import com.milan.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.processbutton.lib.milan.ActionProcessButton;

public class DatabaseListView extends Activity implements OnCompleteListener {
    MediaPlayer media_player;
    ActionProcessButton fetch_database;
    SwipeMenuListView database_results;
    LoginDataBaseAdapter logindatabase_adapter;
    SimpleCursorAdapter cursoradapter;
    Cursor cursor;
    TextView username_txt,password_txt;
    String user_name_string,password_string;
    String text;
    Dialog dialog;
    private EmptyLayout empty_layout;
    View.OnClickListener emptyClickListener;

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

        View.OnClickListener mErrorClickListener = new OnClickListener() {          
            @Override
            public void onClick(View v) {
                    fetch_database.setText("Checking...");
                    empty_layout.showLoading();
                    ProgressGenerator pg = new ProgressGenerator(DatabaseListView.this);
                    pg.start(fetch_database);


            }
        };

        emptyClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(DatabaseListView.this, "Try again button clicked", Toast.LENGTH_LONG).show();

            }
        };

        ActionBar actionbar = getActionBar();
        actionbar.hide();
        View v;

        LinearLayout linear = (LinearLayout)findViewById(R.id.linearLayout1);
        username_txt = (TextView)linear.getChildAt(0);
        password_txt = (TextView)linear.getChildAt(0);
        user_name_string = username_txt.getText().toString();
        password_string = password_txt.getText().toString();
        fetch_database = (ActionProcessButton)findViewById(R.id.Button_Fetch_from_Database);
        database_results = (SwipeMenuListView)findViewById(R.id.listview_database);
        final ProgressGenerator progressGenerator = new ProgressGenerator(DatabaseListView.this);
        logindatabase_adapter = new LoginDataBaseAdapter(DatabaseListView.this);

        empty_layout = new EmptyLayout(DatabaseListView.this, database_results);
        empty_layout.setErrorButtonClickListener(mErrorClickListener);

        fetch_database.setMode(ActionProcessButton.Mode.PROGRESS);
        fetch_database.setOnClickListener(new View.OnClickListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {

                progressGenerator.start(fetch_database);
                fetch_database.setText("Checking...");
                fetch_database.setEnabled(false);
                empty_layout.showLoading();
                media_player = MediaPlayer.create(DatabaseListView.this, R.raw.retrievingfromdatabase);
                media_player.start();

                String[] from = {LoginDataBaseAdapter.USER_NAME,LoginDataBaseAdapter.USER_PASSWORD};
                int[] to = {R.id.txt_username,R.id.txt_pasword};
                cursor = logindatabase_adapter.feching_Data();
                cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);
                cursoradapter.notifyDataSetChanged();
                //registerForContextMenu(database_results);





            }
        });


        SwipeMenuCreator swipe_list_view = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem open_swipemenu = new SwipeMenuItem(DatabaseListView.this);
                open_swipemenu.setBackground(new ColorDrawable(Color.rgb(0x9B,0x33,0xF0)));
                open_swipemenu.setWidth(dp2px(90));
                open_swipemenu.setIcon(R.drawable.databasedelete);
                menu.addMenuItem(open_swipemenu);
            }
        };

        database_results.setMenuCreator(swipe_list_view);
        database_results.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {

            switch(index)   {
            case 0:

                dialog = new Dialog(DatabaseListView.this, "Delete Record", "Do you want to delete Record from database");
                dialog.setCancelable(false);
                dialog.setOnAcceptButtonClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        cursor  = (Cursor) database_results.getItemAtPosition(position);
                        final int item_id = cursor.getInt(cursor.getColumnIndex(LoginDataBaseAdapter.ID));
                        cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_NAME));
                        cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_PASSWORD));
                        logindatabase_adapter.deleteEntry(item_id);
                        //database_results.removeViewAt(position);
                        //cursoradapter.notifyDataSetChanged();
                        database_results.invalidateViews();
                    }
                });

                dialog.show();      

            }

                return false;
            }

        });


    }

    protected int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.database_list_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    @Override
    public void onComplete() {
        if(cursor!=null && cursor.getCount()>0){
        database_results.setAdapter(cursoradapter);
        fetch_database.setEnabled(false);
        fetch_database.setText("SUCCESS");
        }
        else{
            /*fetch_database.setEnabled(false);
            fetch_database.setText("OOPS");
            fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
            final Dialog dialog_database = new Dialog(DatabaseListView.this, "Database Records", "No Records was found in the database");
                                    dialog_database.setOnAcceptButtonClickListener(new View.OnClickListener() {

                                        @Override
                                        public void onClick(View v) {
                                            dialog_database.cancel();
                                        }
                                    });
                                    dialog_database.show();*/
            fetch_database.setText("OOPS");
            fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
            empty_layout.showError();



        }


    }


    }

这是我的LoginDatabase adpater:

package com.developer.milanandroid;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;

public class LoginDataBaseAdapter 
{
        //Database name
        static final String DATABASE_NAME = "MilanloginRegistration.db";
        static final int DATABASE_VERSION = 1;
        public static final int NAME_COLUMN = 1;
        // TODO: Create public field for each column in your table.
        // SQL Statement to create a new database.
        public static final String TABLE_NAME="MilanLoginregistration";
        public static final String ID="_id";
        public static final String USER_NAME="USERNAME";
        public static final String USER_PASSWORD ="PASSWORD";


        static final String DATABASE_CREATE = "create table "+ TABLE_NAME +
                                     "( " +ID+" integer primary key autoincrement,"+"USERNAME text not null,"+USER_PASSWORD+" text not null); ";
        // Variable to hold the database instance
        public  SQLiteDatabase db;
        // Context of the application using the database.
        private final Context context;
        // Database open/upgrade helper
        private DataBaseHelper dbHelper;
        public  LoginDataBaseAdapter(Context _context) 
        {
            context = _context;
            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        public  LoginDataBaseAdapter open() throws SQLException 
        {
            db = dbHelper.getWritableDatabase();
            return this;
        }
        public void close() 
        {
            db.close();
        }

        public  SQLiteDatabase getDatabaseInstance()
        {
            return db;
        }
        public LoginDataBaseAdapter opentoRead() throws android.database.SQLException{

            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
            db = dbHelper.getReadableDatabase();
            return this;
        }
        public LoginDataBaseAdapter opentoWrite() throws android.database.SQLException{

            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
            db = dbHelper.getWritableDatabase();
            return this;
        }

        public void Close(){
            dbHelper.close();
        }


        public void insertEntry(String username,String password)
        {
           ContentValues newValues = new ContentValues();

            newValues.put("USERNAME",username);
            newValues.put("PASSWORD",password);

            // Insert the row into your table
            db.insert("MilanLoginregistration",null,newValues);
            ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
        }


        public int deleteAll(){
            return db.delete(TABLE_NAME, null, null);
        }

        public void deleteEntry(int id){
            //String id=String.valueOf(ID);
            db.delete(TABLE_NAME, ID+"="+id, null);
           // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();

        }

        public Cursor queue_all(){
            String[] columns = new String[]{ID,"USERNAME","PASSWORD"};
            Cursor cursor_queue_all =db.query(TABLE_NAME, columns, null, null, null, null, null);
            return cursor_queue_all;
        }

        public Cursor feching_Data(){

            String[] columns = {ID,USER_NAME,USER_PASSWORD};
            db = dbHelper.getWritableDatabase();
            Cursor cursor = db.query(TABLE_NAME, columns,null,null,null,null,null);
            return cursor;

        }
        public String getSinlgeEntry(String userName)
        {
            Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
            if(cursor.getCount()<1) // UserName Not Exist
            {
                cursor.close();
                return "NOT EXIST";
            }
            cursor.moveToFirst();
            String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
            //cursor.close();
            return password;                
        }
        public String checkSinlgeEntry(String userName)
        {
            Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
            if(cursor.getCount()>=1) // UserName  Exist
            {
                cursor.close();
                return "NOT EXIST";
            }
           // cursor.close();
            return "";              
        }
        public void  updateEntry(String user_name,String pasword)
        {
            // Define the updated row content.
            ContentValues updatedValues = new ContentValues();
            // Assign values for each row.  
            updatedValues.put("USERNAME", user_name);
            updatedValues.put("PASSWORD",pasword);


            String where="USERNAME = ?";
            db.update("MilanLoginregistration",updatedValues, where, new String[]{user_name});             
        }   
        /*public void Display(View v){
            Cursor c = db.rawQuery("select * from MilanloginRegistration", null);
            admin_settings_child.text_fetched_database_results.setText("");
            c.moveToFirst();
            do{
                String username = c.getString(c.getColumnIndex("USERNAME"));
                String password = c.getString(1);
                admin_settings_child.text_fetched_database_results.append("USERNAME::-->"+username+"PASSWORD::-->"+password+"\n");

            }while(c.moveToNext());
        }*/
    }

2 个答案:

答案 0 :(得分:0)

请发布适配器的代码。在上面的代码中,您将从其他适配器中删除数据,并通知其他适配器更改的数据集。即在以下几行中,我看不到cursoradapter实际上正在更新的位置。

logindatabase_adapter.deleteEntry(item_id);
cursoradapter.notifyDataSetChanged();
cursoradapter.notifyDataSetInvalidated();

你也可以试试这个。

listview.getAdapter().notifyDataSetChanged();

为了正确实现数据交换功能,您需要另外创建自定义适配器,每次更改数据时只需设置列表适配器.i.e

listeview.setAdapter(modifiedAdapter);
listview.getAdapter.notifyDataSetChanged();

编辑1:

当您使用简单的游标适配器时,您需要在删除条目后添加以下行:

logindatabase_adapter.deleteEntry(item_id);
cursor = logindatabase_adapter.feching_Data();
//database_results.removeViewAt(position);
cursoradapter = new SimpleCursorAdapter(DatabaseListView.this,   R.layout.listcell, cursor, from, to);
database_results.setAdapter(cursoradapter);
database_results.getAdapter().notifyDataSetChanged();

答案 1 :(得分:-1)

在适配器上使用notifyDataSetChanged()方法,如下所示:

final ArrayAdapter adapter = ((ArrayAdapter) getListAdapter());
runOnUiThread(new Runnable() {
    public void run() {
        adapter.notifyDataSetChanged();
    }
});