Alejandro Ramos Alejandro Ramos - 1 year ago 75
Android Question

How to pass data from an activity to a java class

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:


public class MainActivity extends AppCompatActivity {

private static RadioGroup selectedAvgStds;
...... //rest of the code///

public void onClickListenerButton(){

selectedAvgStds = (RadioGroup)findViewById(;


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


Piece of code of my database

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.

Answer Source

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;

    protected void onCreate(Bundle 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();


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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download