如何在其他Activity中更新数据库后更新Activity中的ListView?

时间:2016-08-11 06:16:04

标签: android listview adapter

    public class SettingsActivity extends AppCompatActivity {
    private Context context;
    private DogDatabaseHelper dbHelper;
    private ListView mListView;
    private ArrayList<String> names = new ArrayList<String>();
    private AdapterForNames namesAdapter;

    @Override
    public void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
        setContentView(R.layout.settings);
        mListView = (ListView)findViewById(R.id.listforall);
        context = this;

        namesAdapter = new AdapterForNames(this,names);
        mListView.setAdapter(namesAdapter);
        DogDatabaseHelper dbHelper = new DogDatabaseHelper(getApplicationContext());
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select name from dog",null);
        if(cursor != null && cursor.moveToFirst()){
            do{
                names.add(cursor.getString(cursor.getColumnIndex("name")));
    namesAdapter.notifyDataSetChanged();

            }while (cursor.moveToNext());
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(SettingsActivity.this,SetupActivity.class);
                intent.putExtra("name",names.get(position));
                startActivity(intent);
            }
        });
    }




    public class AdapterForNames extends ArrayAdapter<String> {
    private ArrayList<String> names;

    AdapterForNames(Context context, ArrayList<String> names){
        super(context,R.layout.settingsname,names);
        this.names = names;
    }

    public void refresh(ArrayList<String> names){
        this.names= names;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater setLayout = LayoutInflater.from(getContext());
        View customView = setLayout.inflate(R.layout.settingsname,parent,false);

        String setItem = names.get(position);
        TextView nameText = (TextView)customView.findViewById(R.id.settingsname);

        nameText.setText(setItem);
        return customView;

    }
}


public class SetupActivity extends AppCompatActivity {

private Context context;
static String extra = "values";
ListView mListView;
private String name;

final String[] setItems = {"name","birthday","size","sex"};

@Override
public void onCreate(Bundle savedInstance){
    super.onCreate(savedInstance);
    setContentView(R.layout.setuplist);
    mListView = (ListView)findViewById(R.id.listview);

    context = this;
    Intent intent =getIntent();
    name = intent.getStringExtra("name");
    setResult(RESULT_OK,intent);
    showView();
}

private void showView(){
    DogDatabaseHelper dbHelper= new DogDatabaseHelper(getApplicationContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    Cursor cursor = db.rawQuery("select * from dog where name = ?",new String[]{name});
    //Cursor cursor = db.query("Dog",null,null,null,null,null,null,null);
    if(cursor.moveToFirst()){
        String name = cursor.getString(cursor.getColumnIndex("name"));
        String birthday = cursor.getString(cursor.getColumnIndex("birthday"));
        String size = cursor.getString(cursor.getColumnIndex("size"));
        String sex = cursor.getString(cursor.getColumnIndex("sex"));

        final String[] setValues = {name,birthday,size,sex};
        ListAdapter listAdapter = new CustomAdapter(this,setItems,setValues);
        mListView.setAdapter(listAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String setupItemValue = setValues[position];
                String setupItem = setItems[position];
                Intent intent;
                if(setupItem.equals("name")){
                    intent = new Intent(SetupActivity.this,ChangeName.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,1);
                } else if(setupItem.equals("birthday")){
                    intent = new Intent(SetupActivity.this,ChangeBirthday.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,2);
                }else if(setupItem.equals("size")){
                    intent = new Intent(SetupActivity.this,ChangeType.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,3);
                }else{
                    intent = new Intent(SetupActivity.this,ChangeSex.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,4);
                }

            }
        });

    }

    cursor.close();
}


private void updateView(){
    DogDatabaseHelper dbHelper= new DogDatabaseHelper(getApplicationContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    Cursor cursor = db.query("Dog",null,null,null,null,null,null,null);
    if(cursor.moveToFirst()){
        String name = cursor.getString(cursor.getColumnIndex("name"));
        String birthday = cursor.getString(cursor.getColumnIndex("birthday"));
        String size = cursor.getString(cursor.getColumnIndex("size"));
        String sex = cursor.getString(cursor.getColumnIndex("sex"));

        final String[] setValues = {name,birthday,size,sex};
        ListAdapter listAdapter = new CustomAdapter(this,setItems,setValues);
        mListView.setAdapter(listAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String setupItemValue = setValues[position];
                String setupItem = setItems[position];
                Intent intent;
                if(setupItem.equals("name")){
                    intent = new Intent(SetupActivity.this,ChangeName.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,1);
                } else if(setupItem.equals("birthday")){
                    intent = new Intent(SetupActivity.this,ChangeBirthday.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,2);
                }else if(setupItem.equals("size")){
                    intent = new Intent(SetupActivity.this,ChangeType.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,3);
                }else{
                    intent = new Intent(SetupActivity.this,ChangeSex.class);
                    intent.putExtra(extra,setupItemValue);
                    startActivityForResult(intent,4);
                }

            }
        });
    }

    cursor.close();
}

@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){

    DogDatabaseHelper dbHelper= new DogDatabaseHelper(getApplicationContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    Cursor cursor = db.query("Dog",null,null,null,null,null,null,null);
    switch (requestCode){
        case 1:
            if (resultCode == RESULT_OK){
                ContentValues cv = new ContentValues();
                cv.put("name",data.getStringExtra("return_name"));
                db.update("dog",cv,"id=?",new String[]{"1"});

            }
            break;
        case 2:
            if(resultCode == RESULT_OK){
                ContentValues cv = new ContentValues();
                cv.put("birthday",data.getStringExtra("return_birthday"));
                db.update("dog",cv,"id=?",new String[]{"1"});

            }
            break;
        case 3:
            if(resultCode == RESULT_OK){
                ContentValues cv = new ContentValues();
                cv.put("size",data.getStringExtra("return_type"));
                db.update("dog",cv,"id=?",new String[]{"1"});
            }
            break;
        case 4:
            if(resultCode == RESULT_OK){
                ContentValues cv = new ContentValues();
                cv.put("sex",data.getStringExtra("return_sex"));
                db.update("dog",cv,"id=?",new String[]{"1"});

            }
            break;

    }
    db.close();
    updateView();
}

}

   public class DogDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_DOG = "create table dog ("
        + "id integer primary key autoincrement,"
        + "name text,"
        + "birthday text,"
        + "size text,"
        + "sex text,"
        + "count integer)";

private Context context;

public DogDatabaseHelper(Context context){
    super(context,"Dog.db",null,1);
    this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db){
    db.execSQL(CREATE_DOG);

}

@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
    db.execSQL("drop table if exists Dog");
    onCreate(db);
}


public ArrayList<String> getAllNames(){
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<String> names = new ArrayList<String>();

    Cursor cursor = db.query("Dog",null,null,null,null,null,null);
    if(cursor.moveToFirst()){
        do{
            String name = cursor.getString(cursor.getColumnIndex("name"));
            names.add(name);
        }while (cursor.moveToNext());
    }
    cursor.close();
    return names;
}

}

我可以从数据库中获取数据,我可以在点击ListView中的名称后更新数据,但当我返回此Activity时,我不知道如何更新数据ListView,因为notifyDataSetChanged()无效。

不知道出了什么问题,任何人都可以提供帮助吗?

2 个答案:

答案 0 :(得分:2)

使用startActivityForResult()代替startActivity()来启动SetupActivity

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
    Intent intent = new Intent(SettingsActivity.this, SetupActivity.class);
    intent.putExtra("name", names.get(position));
    startActivityForResult(intent, REQUEST_SETUP);
    // REQUEST_SETUP is just a private int constant in SettingsActivity
}

覆盖onActivityResult()中的SettingsActivity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == RESULT_OK) {
        switch (requestCode) {
            case REQUEST_SETUP:
                dataChanged();
                break;

            // other request codes (if any)
        }
    }
}

dataChanged()方法:

private void dataChanged() {
    // fetch the new data from the DB into your ArrayList
    names.clear();
    names.addAll(dbHelper.getAllNames());

    // update the ListView with the new data
    namesAdapter.notifyDataSetChanged();
}

getAllNames()中的DogDatabaseHelper方法:

public ArrayList<String> getAllNames() {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<String> names = new ArrayList<>();

    Cursor cursor = db.query(TABLE_DOG, new String[]{COLUMN_NAME},
        null, null, null, null, null, null);

    if (cursor.moveToFirst()) {
        do {
            String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
            names.add(name);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return names;
}

最后,当你完成SetupActivity中的内容并插入/更新数据库中的数据时,将结果设置为RESULT_OK并通过调用SettingsActivity返回finish() }:

setResult(RESULT_OK);
finish();

注意:为了获得更好的性能,您可以将SetupActivity中插入/更新的记录的ID传递给SettingsActivity Intent因此,不是通过调用getAllNames()来查询所有行,而是可以获取修改后的记录。

答案 1 :(得分:1)

我认为最简单快捷的方法是放置所有这些代码:

DogDatabaseHelper dbHelper = new DogDatabaseHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select name from dog",null);

// Edit: to reload all data you must first clear the list
names.clear();

if (cursor != null && cursor.moveToFirst()) {
    do {
        names.add(cursor.getString(cursor.getColumnIndex("name")));
    } while (cursor.moveToNext());

    // Note: move this out of the bucle to avoid calling it in every iteration
    namesAdapter.notifyDataSetChanged();
}
在您的MainActivity的onResume()方法中,因此每次您回来时都会刷新数据。

编辑:,因为每次活动调用onResume时重新加载数据,我建议你也使用MainActivity的标志来知道是否有变化。类似的东西:

@Override
protected void onResume() {
    super.onResume();
    if (thereWereChanges) {
        realoadDataSet();
    }
}