-1

How to get and set the string from one activity to another in android?

I tried this code.

MainActivity.java

public class MainActivity extends AppCompatActivity {

     private static MainActivity instance;
     private String name;
     private EditText nameEditText;
     

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         instance = this;
         nameEditText = (EditText) findViewById(R.id.ipAddress); 
         name = nameEditText.getText().toString();
     }

     public static MainActivity getInstance() {
         return instance;
     }

     public String getString() {
        return name ;
     }
 }

Another Activity

  public class websiteview extends AppCompatActivity {


    protected WebView webView;
    String name = MainActivity.getInstance().getString();

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_websiteview);
        webView = findViewById(R.id.webviewab);

        webView.loadUrl(name);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setUserAgentString(getString(R.string.user_agent_string));
        webView.getSettings().setUseWideViewPort(true);
        webView.setInitialScale(100);}}
    

But, It failed.

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abcdefgh, PID: 31915
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.abcdefgh/com.example.abcdefgh.pcscreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.abcdefgh.MainActivity.getString()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3341)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7814)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.abcdefgh.MainActivity.getString()' on a null object reference
    at com.example.abcdefgh.websiteview.<init>(websiteview.java:20)
    at java.lang.Class.newInstance(Native Method)
    at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
    at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3329)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:237) 
    at android.app.ActivityThread.main(ActivityThread.java:7814) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068) 
I/Process: Sending signal. PID: 31915 SIG: 9

how to get and set the string from one activity to another in android?

How to get and set the string from one activity to another in android?

my project

Give a solution for this.

Pradeep
  • 19
  • 1
  • 6
  • 3
    Does this answer your question? [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Ryan M Jul 25 '20 at 06:29
  • Also, you may want to study up on method signatures in java. In the code above, you are calling an undefined method. You are defining the method `public String getString()`, but then you call the method `public String getString(ReturnType parameter)`. In java these are 2 different methods. – Nate T Jul 27 '20 at 12:33

3 Answers3

0

You can send it as parameter to your another activity. When you create a new intent as below:

Intent yourIntent = new Intent(this, yourAnotherActivity.class);
yourIntent.putExtra("name", name);
startActivity(yourIntent);

You can put it in with putExtra() method. And in your anotherActivity class which is you want to receive name value:

Intent yourIntent = getIntent();
String name = myIntent.getStringExtra("name");

You can get it with getStringExtra()


First Edit

You can't access directly to an activity from another activity. When you run MainActivity.getInstance() it returns null cause what is the MainActivity in this activity? You didn't define MainActivity. If you want to use a method of an activity firstly you should access to this MainActivity class. But you try to getInstance method through any reference so it returns null. Also you try to call getString() method with "null reference" (which returns with MainActivity.getInstance()) And then you try to assign a null value to a String variable so you get NullPointerException. Your main and second activity should be like in below instead of yours:

Main Activity:

   public class MainActivity extends AppCompatActivity {

    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = "test";
        Intent secondActivity = new Intent(this, SecondActivity.class);
        secondActivity.putExtra("name", name);
        startActivity(secondActivity);
    }

}

Second Activity:

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second2);
        Intent getActivity = getIntent();
        String name = getActivity.getStringExtra("name");

        Log.d("name", name);
    }
}

Now you can see the value of name variable "text" in your logs

Also don't forget declare your second activity in your AndroidManifest.xml otherwise you'll get the same error.


Second Edit

In your Project you forgot put the name value to intent. So your T function should be like this:

    private void T() {
        Intent intent=new Intent(this,web.class);
        intent.putExtra("name", name);
        startActivity(intent);
    }

And your web page should be like this:

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);

    Intent intent = getIntent();
    String name = intent.getStringExtra("name");

    webView = findViewById(R.id.local);
bsgal
  • 313
  • 2
  • 13
0

The above comment and answer is correct , though if you want to access the name without passing it with intent, here is a procedure

MainActivity.java

public class MainActivity extends AppCompatActivity {

     private static MainActivity instance;
     private String name;
     private EditText nameEditText;
     

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         instance = this;
         nameEditText = (EditText) findViewById(R.id.ipAddress); 
         name = nameEditText.getText().toString();
     }

     public static MainActivity getInstance() {
         return instance;
     }

     public String getString() {
        return name ;
     }
 }

Another Activity

 public Class AnotherClass() {
      // call this method
      String name = MainActivity.getInstance().getString();
 }

Edit

or you can set the name value when you want to save or you can directly return nameEditText.getText().toString() like

public String getString() {
    return nameEditText.getText().toString();
 }

Edit

public class Constant {
public static String name= "";
}

You can set value like


#Note: set the value before finish your activity

Constant.name = nameEditText.getText().toString();

and retrieve like

String name =  Constant.name;

EDIT 2


here is your MainActivity Oncreate, Hope it will work

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    instance = this;
    webaddress = (EditText) findViewById(R.id.ipAddress);
    

    touch1 =findViewById(R.id.touvh1);
    touch1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name = webaddress.getText().toString();
            T();
        }
    });
}
Jyotish Biswas
  • 674
  • 5
  • 11
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/218817/discussion-on-answer-by-jyotish-biswas-how-to-set-and-get-string-from-another-ac). – Samuel Liew Jul 29 '20 at 12:15
0

You are trying to get Instance of MainActivity which is never get Instanciated by you

Modify your getInstance() like this:

public static MainActivity getInstance() {
        return  INSTANCE == null ? INSTANCE = new MainActivity(): INSTANCE;
    }

OR:

Use intent to call activity and bundle for data transfer

In you MainActivity.java inside onCreate(..)

TextView tvName = findViewById(R.id.name);
        Bundle bundle = new Bundle();
        bundle.putString("Key",tvName.getText().toString());
        Intent intent = new Intent(this,MainActivity.class);
        intent.putExtras(bundle);//set bundle inside intent
        startActivity(intent);

In your secondActivity.java:

Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            String text = bundle.getString("Key");//this will have same data passed by first activity
        }
chand mohd
  • 2,363
  • 1
  • 14
  • 27