如何从 activity a 中的数据库获取数据,当 activity b 在 Android 中使用 ActiveAndroid 关闭时

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

我是新手,遇到了一些问题,感谢您的帮助。

情况: 我有一个 MainActivity 和一个名为 MainAddMedActivity 的 Activity。我通过 EditText 从第二个 activity 获取数据并将其保存在数据库中。我的目的是通过从数据库中获取数据来在 MainActivity 的 ListView 中显示来自 EditText 的数据。如何以正确的方式做到这一点?

医学:

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

主要Activity:

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

可以使用Content Provider。它需要大量代码才能实现,但它会将您的数据库绑定到您的视图。

这是我过去实现的内容提供程序的示例。

您为数据库键构建一个 ContentValue 对象(基本上是一组模拟数据库行的值)并在其中设置新数据。然后,您使用 getContentResolver() 将 ContentValue 插入您的 Content Provider,Content Provider 又会用您的新数据更新您的数据库。

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

这是一个 Content Provider Class 的示例(此处代码过多),它实现了插入、删除、查询、编辑和构建数据库 URI 路径的逻辑.

然后您可以设置并使用 Cursor,它遍历您的数据源,从您的 Content Provider 访问数据,更具体地说,您可以将 CursorAdapter 扩展到直接将您的视图绑定到数据库查询。这是一个的样子:

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

    }

}
}