gpt4 book ai didi

java - 如何将数据从 Activity 传递到 Java 类

转载 作者:行者123 更新时间:2023-12-01 09:32:17 26 4
gpt4 key购买 nike

我已经到达下面的墙了。我尝试将变量从我的主要 Activity 传递到生成数据库的 java 类,因为我想在该数据库的一个查询中使用此变量来获取结果,然后将其传递给主要 Activity 。这是我的代码:

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

尽管我已经导入了 Activity 和类中的所有 Intent 库,但 Intent 不起作用。我怎样才能实现我的目标?为什么 Intent 在这里不起作用?

任何建议和想法都将受到极大的赞赏。

最佳答案

根据您的评论,为什么不简单地将 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;
}
}

关于java - 如何将数据从 Activity 传递到 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39311888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com