0

I know that there are a lot of answers to this question already, but I'm still having trouble dealing with this concept.

An answer found here shows:

If you didn't want to use a global variable you could always create a method in your activity to return your string.

    public String getMyString(){
         return item; } 

Then in your current activity you could call:

    String myValue = LoginScreen.getMyString();

When I try this method, I am returned an error saying "Non-Static method can not be referenced from a static context". However if I make the method static it says that my variable needs to be static, but I need to update the variable. I'll include my code below.


First Activity -

btnSEARCH.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        if (editTextSearch.getText().toString() != null) {
            SearchQueryTerm = editTextSearch.getText().toString();
            editTextSearch.setText("");
        }
    }
});

public String getMyString(){
    return SearchQueryTerm;
}

Second Activity-

String SearchQueryTerm = MainActivity.getMyString();

I truly appreciate any help you can give me in this. Thanks so much!! <3


This is my updated code - however it still crashes :(

Activity 1

public void sendMessageIntent(View view) {
    Intent search_intent = new Intent(this, SearchActivity.class);
    api_intent.putExtra("my_variable", SearchQueryTerm);
    startActivity(search_intent);
}

xml file

 <Button
        android:id="@+id/button_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="View"
        android:onClick="sendMessageIntent"
        />

Activity 2 -

public String SearchQueryTerm

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enter_variable);

        if (extras != null) {
            SearchQueryTerm = extras.getString("my_variable");
        }
}
Community
  • 1
  • 1
tobekingforaday
  • 3
  • 1
  • 2
  • 7
  • Have you tried with getter and setter methods ? So that you create say: setString(SearchQueryTerm); and then in your second activity you call String newString = new MainActivity.getString(); If you are not familiar with getter / setter methods let me know and I can try explain better. – David Kasabji Sep 23 '15 at 20:07
  • I am wondering what exactly you are trying to achieve. Do you want to start a new Activity and pass your search query? Then you should use an Intent as suggested [here](http://stackoverflow.com/a/32748568/2427585). If you want to use a static field, both the field and the method have to be static. All instances of your Activity will share the same static variable. – wkarl Sep 23 '15 at 20:13
  • Hey guys thanks so much for your comments. I will look into getter and setter methods either way thanks so much!! To answer your question, I am trying to start a new activity to return a query result of an online database because for some reason a web view in the same activity will not work correctly for me. The value is entered (hence it can not be static), sent to the second activity and then the database is queried using that value – tobekingforaday Sep 23 '15 at 22:36

2 Answers2

4

Use putExtra method of an object Intent.

In your first activity create for example :

String value = "value";
Intent i = new Intent(getApplicationContext(), MyActivity.class);
i.putExtra("my_variable",value);
startActivity(i);

In your second activity you can retrieve your variable :

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("my_variable");
}

It's the best method to pass a variable between activities.


To show you how it works, i have done this code :

XML of first activity :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/editTextSearch"
            android:layout_width="200dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/buttonSearch"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:text="Button"/>
    </LinearLayout>

</RelativeLayout>

First Activity :

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnSEARCH = (Button) findViewById(R.id.buttonSearch);

        btnSEARCH.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                EditText editTextSearch = (EditText) findViewById(R.id.editTextSearch);
                if (editTextSearch.getText().toString() != null) {
                    String value = "value";
                    Intent i = new Intent(getApplicationContext(), Main2Activity.class);
                    i.putExtra("SearchQueryTerm",editTextSearch.getText().toString());
                    startActivity(i);
                    editTextSearch.setText("");
                }
            }
        });
    }

}

In this first activity we pass the value of the editText in the putExtra method with the key = "SearchQueryTerm".

To retrieve the value of editText do this in your second Activity :

public class Main2Activity extends AppCompatActivity {

    String SearchQueryTerm = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            SearchQueryTerm = extras.getString("SearchQueryTerm");
        }

        System.out.println(SearchQueryTerm);
    }

}

Now you have the value of your editText in the variable SearchQueryTerm ( Second Activity ).

It works for me, so there is no reason it dont work for you.

Hope it helps.

Yassine.b
  • 617
  • 5
  • 11
  • Thanks so much for your help!! I've tried to add this to my code but now it just crashes my new Activity. Could you please check and see if I've done it right? I've added my code to the original question because formatting in the comments doesn't display code well – tobekingforaday Sep 23 '15 at 22:29
  • No problem, edit your answer and show me what you ve done. – Yassine.b Sep 23 '15 at 22:32
1

a good solution is to add a "model" singleton class, where you store data that have to be shared between your activities

example :

public class Model {
private static Model __instance == null;

private Model() {
}

public static Model instance() {
    if (__instance == null) {
        __instance = new Model();
    }
    return __instance;
}

private Object mydataToShare = null;

public void setMyDataToShare(Object mydataToShare) {
    this.mydataToShare = mydataToShare; 
}

public Object getMyDataToShare() {
    return mydataToShare;
}

}

to store data :

Model.instance().setMyDataToShare(<value to store>);

to retrieve data :

Object valueToRetrieve = Model.instance().getMyDataToShare();

it allow you to transfer complex data and separate completely logic part from UI

Jerome B.
  • 244
  • 2
  • 8