我已经到了以下的墙上。我试图将一个变量从我的主要活动传递给生成我的数据库的java类,因为我想在我的一个查询中使用这个变量来获取结果,然后将其传递给主要活动。这是我的代码:
//MainActivity
public class MainActivity extends AppCompatActivity {
private static RadioGroup selectedAvgStds;
...... //rest of the code///
public void onClickListenerButton(){
selectedAvgStds = (RadioGroup)findViewById(R.id.controlAverageOfLiving);
showResults.setOnClickListener(
int avgStdLiving = selectedAvgStds.getCheckedRadioButtonId();
selectedAvgStdsRb = (RadioButton) findViewById(avgStdLiving);
//variable that I want to pass
String avgStdLivingText = (String) selectedAvgStdsRb.getText();
switch (option) {
case "one":
Intent intent = new Intent(MainActivity.this,DatabaseHelper.class);
Intent.putExtra("values",avgStdLivingText);
startActivity(intent);
break;
}
);
}
我的数据库代码
//DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper{
public Cursor showResults(){
SQLiteDatabase db = this.getWritableDatabase();
//the intent does NOT work
Bundle bundle = getIntent().getExtras();
Cursor results = db.rawQuery("select * from "+TEMP_TABLE+"where value = " + selectedAvgStds , null);
return results;
}
}
尽管我已经在活动和类中导入了所有Intent库,但意图仍无效。我怎样才能实现目标?为什么意图在这里不起作用?
任何建议和想法都将受到极大的赞赏。
答案 0 :(得分:1)
根据您的评论,为什么不简单地将DatabaseHelper
作为实例变量并将showResults
方法参数化为:
public class MyActivity extends Activity {
private DatabaseHelper myDatabaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialise your helper here
myDatabaseHelper = ...
}
public void onClickListenerButton(){
// All your other stuff here...
// variable that I want to pass
String avgStdLivingText = selectedAvgStdsRb.getText().toString();
myDatabaseHelper.showResults(avgStdLivingText);
}
}
然后在助手类中你可以做到:
public Cursor showResults(String selectedAvgStds){
SQLiteDatabase db = this.getWritableDatabase();
Cursor results = db.rawQuery("select * from "+TEMP_TABLE+"where value = " + selectedAvgStds , null);
return results;
}
}
答案 1 :(得分:0)
您无法使用intent获取数据的原因是SQLiteOpenHelper
类可能没有getIntent()
的方法定义。我希望您使用共享首选项来存储数据并在SQLiteOpenHelper
类中检索它。