How to solve the Android Studio Activity global variable Unfortunatelly error?

Asked 2 years ago, Updated 2 years ago, 65 views

Hello, I am currently making a web page viewer using Android Studio.

Depending on the value of the action mode int global variable in WebActivity I want to display a web page, but I keep getting errors

Please tell me the solution. Thank you.

MainActivity myApp = (MainActivity)getApplicationContext();

actmode = myApp.getActmode();

Error occurred in the above code

package com.themerite.app.AppMain;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private int actmode;

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

    public void onWebClicked(View v) {
        Intent WebView = new Intent(this, WebActivity.class);
        startActivity(WebView);
    }

    public void setActmode(int actmode){
        this.actmode = actmode;
    }

    public int getActmode(){
        return actmode;
    }
}


Make the main activity look like a stomach A global variable error called by WebActivity occurs as shown below.

public class WebActivity extends AppCompatActivity {

    WebView mWebView; 
    String goURL;
    int actmode;

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

        /* Apply global variables from MainActivity to WebActivity */
        /* Error occurred! */
        MainActivity myApp = (MainActivity)getApplicationContext();
        actmode = myApp.getActmode();

        if(actmode==2) {
            goURL = "https://naver.com";
        }
        webviewStart();
    }

    public void webviewStart() {
        /*
       Run View
        */
    }


android android-studio unfortunately java

2022-09-22 13:43

1 Answers

Try using the variable ActMode in the application class instead of Activity.

You need to register with Manifest to use the application.

public class MyApp extends Application {

  int actmode;

  @Override public void onCreate() {
    super.onCreate();
    act mode = 2;
  }

  public void setActmode(int actmode){
        this.actmode = actmode;
    }

    public int getActmode(){
        return actmode;
    }
}

When you do this and retrieve the value,

MyApp myApp = (MyApp) getApplication();
actmode = myApp.getActmode();

It's possible in this way.

I don't know the exact purpose, but it's better to deliver the value to WebActivity as an int It looks like it'

Look for int forwarding between activities as well.


2022-09-22 13:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.