Reputation: 2780
I have reached the wall on the following. I am trying to pass a variable from my main activity to a java class that generates my database because I want to use this variable in one of my queries of that database to get a result and then pass it to the Main activity. Here's my piece of code:
//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;
}
);
}
Piece of code of my database
//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;
}
}
The intent is not working despite the fact I have imported all the Intent libraries in the activity and the class. How can I achieve my goal? Why the Intents do not work here?
Any suggestion and idea will be enormously appreciated.
Upvotes: 0
Views: 1095
Reputation: 2297
The reason you are not able to get data using intent is that SQLiteOpenHelper
class might not have the method definition for getIntent()
. I would prefer you use Shared Preferences to store the data and retrieve it inside you SQLiteOpenHelper
class.
Upvotes: 0
Reputation: 5149
As per your comment, why do you not simply make DatabaseHelper
an instance variable and parameterize your showResults
method as following:
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);
}
}
And then within the helper class you can simply do:
public Cursor showResults(String selectedAvgStds){
SQLiteDatabase db = this.getWritableDatabase();
Cursor results = db.rawQuery("select * from "+TEMP_TABLE+"where value = " + selectedAvgStds , null);
return results;
}
}
Upvotes: 1