Search code examples
javaandroiddatabasesqliteactiveandroid

How to get data from the db in activity a, when activity b is closed in Android with ActiveAndroid


im new to this and have some problems, thanks for your help.

Situation: I have a MainActivity and a second Activity called MainAddMedActivity. I get data from the second activity through an EditText and save it in the database. My intention is to display the data from the EditText in a ListView in the MainActivity by taking it from the database. How to do it the right way ?

Med:

@Table(name = "Med")
public class Med extends Model {
// Zähler für eindeutige IDs
private static long counter = 0;

@Column(name = "_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public long id;

@Column(name = "Description", index = true)
public String description;

public Med() {
    super();
}

public Med(String message) {
    super();
    id = counter++;
    description = message;
}
}

MedDAO:

public class MedDAO {

public static List<Med> getAll(String text) {
    return new Select()
            .from(Med.class)
            .where("Description like ?", new String[]{'%' + text + '%'})
            .orderBy("Description")
            .limit(40)
            .execute();
}

public static List<Med> getAll() {
    return new Select()
            .all()
            .from(Med.class)
            .execute();
}

public static List<Med> getOneItem(String text) {
    return new Select()
            .from(Med.class)
            .where("Description = ?", text)
            .execute();
}

public static void insertMed(String msg){
    new Med(msg).save();
}

public static void remove(String text) {
    new Delete().from(Med.class).where("Description = ?", text).execute();
}
}

MainActivity:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
private ArrayAdapter<String> listAdapter;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(view.getContext(), MainAddMedActivity.class);
            startActivity(intent);
        }
    });

    ListView mainListView = (ListView) findViewById(R.id.listView);

    mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String item = listAdapter.getItem(position);
            //Aus DB entfernen
            MedDAO.remove(item);
            //Aus Liste im Gui entfernen
            listAdapter.remove(item);
            Toast.makeText(getBaseContext(), item + "gelöscht", Toast.LENGTH_SHORT).show();
        }
    });
    //TODO: ArrayAdapter bugt
    //Adapter für die Liste erzeugen
    listAdapter = new ArrayAdapter<String>(this, R.layout.single_row, R.id.listMedNrPart);
    mainListView.setAdapter(listAdapter);


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

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

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

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


@Override
public void onResume() {
    super.onResume();
//        MedDAO.getLatestItem();
    /*int max = listAdapter.getCount();
    int i = 0;
    while (i < max){
        Log.d("MainActivity", listAdapter.getItem(i));
        i++;
    }*/
//        listAdapter.add(MedDAO.getLatestItem().toString());
}
}

MainAddMedActivity:

public class MainAddMedActivity extends AppCompatActivity {


private EditText txtSearchMedicament;
private EditText txtNumberMedicament;
private TextView txtAlarmPrompt;
private TimePickerDialog timePickerDialog;
private Switch switchReminder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_add_med);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);


    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText description = (EditText) findViewById(R.id.txtSearchMedicament);
            String text = description.getText().toString();
            **//SAVE IN DATABASE**
            MedDAO.insertMed(text);
            //TODO: Close Activity
        }
    });

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    this.txtSearchMedicament = (EditText) findViewById(R.id.txtSearchMedicament);
    this.txtNumberMedicament = (EditText) findViewById(R.id.txtNumberMedicament);
    this.txtAlarmPrompt = (TextView) findViewById(R.id.txtAlarmPrompt);
    this.switchReminder = (Switch) findViewById(R.id.switchReminder);


    switchReminder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                cancelSwitch();
            }
        }
    });

Solution

  • A Content Provider could be used. It takes a good amount of code to implement but it binds your database to your view.

    Here is an example of a Content Provider I have implemented in the past.

    You construct a ContentValue object (basically a set of values to mimic a database row) for your database keys and set your new data there. You then use getContentResolver() to insert the ContentValue into your Content Provider, which in turn updates your database with your new data.

    ContentValues values = new ContentValues();
    
    values.put(DatabaseHelper.KEY_VENUE_NAME, store.getName());
    values.put(DatabaseHelper.KEY_VENUE_CITY, store.getCity());
    values.put(DatabaseHelper.KEY_VENUE_STATE, store.getState());
    
    //insert row
    context.getContentResolver().insert(Uri.parse(ContentProvider.base_CONTENT_URI + index), values);
    

    Here's an example of the Content Provider Class (too much code for here) which implements the logic for inserting, deleting, querying, editing, and constructing URI paths to your database.

    You can then set up and use a Cursor, which iterates through your data source, to access the data from your Content Provider, more specifically you can extend CursorAdapter to directly bind your views to database queries. Here is what one looks like:

    public class StoreCursorAdapter extends SimpleCursorAdapter {
    private static final String TAG = "VenueCursorAdapter";
    
    DatabaseHelper databaseHelper;
    private Context context;
    private int layout;
    
    private int selection; //MapsActivity.getStoreSelection();
    
    public StoreCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
    
        databaseHelper = DatabaseHelper.getInstance(context);
        this.context = context;
        this.layout = layout;
    }
    
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
    
        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(layout, parent, false);
    
        return v;
    }
    
    @Override
    public void bindView(View v, Context context, Cursor c) {
    
        selection = ((MapsActivity) context).getStoreSelection();
    
        int position = c.getPosition();
    
        int nameColumn = c.getColumnIndex(DatabaseHelper.KEY_VENUE_NAME);
    
        String name = c.getString(nameColumn);
    
        TextView nameText = (TextView) v.findViewById(R.id.nameTextView);
        TextView ratingText = (TextView) v.findViewById(R.id.ratingTextView);
    
        if(nameText != null && ratingText != null) {
            nameText.setText(name);
    
        }
    
    }
    }