简体   繁体   中英

Trying to call a method from 1st class activity and keep the same argument in a 2nd class activity (android studio)

Currently finishing up an app I have been working on but I'm kinda stuck on this last thing.

The app has 2 activities, one with buttons that are categories and the other shows the information according to the button pressed. For example if you click the button Fast food, it goes to the 2nd screen and displays info on that.

I'm trying to get a refresh button on the 2nd activity that will call a method in the 1st activity to refresh new information depending on the button pressed. The problem is that I don't know how to make it so the method keeps the same argument when called. What I mean is, if fast food was clicked, the refresh button would get new info that still relates to the fast food category.

Here's the relevant code in the Main activity:

public void yelpSearch(View view) {
    switch (view.getId()) {
        case R.id.button: buttoncategory = "Restaurant";
        break;
        case R.id.button2: buttoncategory = "Chinese restaurant";
        break;
        case R.id.button3: buttoncategory = "Fast Food";
        break;

and this on the 2nd Activity

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.refresh:
        Refresh();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public void Refresh() {
MainActivity mActivity = new MainActivity();
mActivity.yelpSearch();
}

I'm not sure what to put inside mActivity.yelpSearch(); I tried using (View view) but it'll say cannot resolve symbol view. And if I make a local variable for view, it'll say not initialized and I don't know what to set it as

Any help would be awesome, been googling on this for a while now and searched through tons of questions on here as well. I'm still new at this so bear with me

I think you want to pass data between activities?

First Activity(Send DATA):

String data="YourXXXdata" 
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("DATANAME", data);
startActivity(intent)

second Activity(Receive DATA):

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

The data now is in String value

*you have to put in data the value you need depend you preview select button.

Make your yelpSearch method static
and call it like this from 2nd activity MainActivity.yelpSearch();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM