Ben
Ben

Reputation: 601

How to update ListView in Activity after updating database in other Activity?

    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;
}

}

I can get data from database and I'm able to update data after clicking the name in the ListView, but when I return to this Activity, I don't know how to update the ListView, cause notifyDataSetChanged() didn't work.

Have no idea what went wrong, Anyone can help?

Upvotes: 2

Views: 1643

Answers (2)

earthw0rmjim
earthw0rmjim

Reputation: 19417

Use startActivityForResult() instead of startActivity() to start your 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
}

Override onActivityResult() in 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)
        }
    }
}

The dataChanged() method:

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();
}

The getAllNames() method in 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;
}

And finally, when you finished your stuff in SetupActivity and inserted/updated the data in the DB, set the result to RESULT_OK and return to SettingsActivity by calling finish():

setResult(RESULT_OK);
finish();

NOTE: for better performance, you could pass the ID(s) of the inserted/updated record(s) from SetupActivity to SettingsActivity in the Intent, so instead of querying all rows by calling getAllNames(), you could just fetch the modified record(s).

Upvotes: 2

josemigallas
josemigallas

Reputation: 3909

I think the easiest and quicker way for you would be to put all this code:

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();
}

in your MainActivity's onResume() method, so every time you come back you refresh the data.

EDIT: since reloading the data each time the activity calls onResume, I would suggest you also use a flag for the MainActivity to know if there have been changes. Something like:

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

Upvotes: 1

Related Questions