如何通过另一个 activity 显示我数据库中的特定行?

How to display a specific row in my database through another activity?

我想在 table 中显示特定行。我有两个活动,第一个 activity 是输入传递给第二个 Activity 的 ID,它将根据我输入的 ID 在我的 table 中显示该行。

希望你能帮助解决我的问题。我不知道我的代码有什么问题。

//主要Activity:

public class MainActivity extends Activity {
   EditText et_id;

   public void doView(View v){
      String id = et_id.getText().toString();

      if(!id.isEmpty()){
         Intent i = new Intent(this.getApplicationContext(), ActivityView.class);
         i.putExtra("id", id);
         startActivity(i);
      } else {
         Dialog d = new Dialog(this);
         d.setTitle("Message");
         TextView tv = new TextView(this);
         tv.setText("ID must be provided");
         d.setContentView(tv);
         d.show();
      }
   }
}

//ActivityView.class

public class ActivityView extends Activity {

   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.layout_view);
      TextView tv_id = (TextView) findViewById(R.id.tvId);
      TextView tv_name = (TextView) findViewById(R.id.tvName);
      TextView tv_course = (TextView) findViewById(R.id.tvCourse);
      Bundle extra = getIntent().getExtras();
      String id = extra.getString("id");
      DBase db = new DBase(this);
      db.open();
      String[] rec = db.getRecord(Integer.parseInt(id));
      db.close();

      if(rec[0]!=null){
         tv_name.setText(rec[0]);
         tv_course.setText(rec[1]);
      } else { 
         Dialog d = new Dialog(this);
         d.setTitle("Message");
         TextView tv = new TextView(this);
         tv.setText("There is no record");
         d.setContentView(tv);
         d.show();
      }
   }
}

//DBase.java

public String[] getRecord(int rid) throws SQLException{
   String selectQuery = "SELECT * FROM "+DB_TABLE+"WHERE"+K_RID+"="+rid;
   Cursor c = null;
   c = dBase.rawQuery(selectQuery, null);
   String[] data = new String[2];
   if(c.moveToFirst()){
      int indexName = c.getColumnIndex(K_NAME);
      int indexCourse = c.getColumnIndex(K_COURSE);
      data[0] = c.getString(indexName);
      data[1] = c.getString(indexCourse);
   }

   return data;
}

我怀疑您的代码无法运行的原因是您的查询有误:

String selectQuery = "SELECT * FROM "+DB_TABLE+"WHERE"+K_RID+"="+rid;

您没有任何白色 space,所以您的 table 名称、所在列和 ID 都被砸在一起了。确保每个项目之间有一个space:

String selectQuery = "SELECT * FROM " + DB_TABLE + " WHERE " + K_RID + " = " + rid;