Don't understand why I'm getting NullPointerException - android

I don't understand why I my app keeps on crashing. According to LogCat, it is caused by a NullPointerExeption on a line, however, I cannot find why it is occurring. What's supposed to happen is an image resource for an ImageView is changed in MainActivity by pressing a button on another activity. I have followed multiple guides, but get the recurring error. From what I can see it occurs when extra information is passed through an Intent, something is null but I cannot find it.
LogCat
05-03 22:33:03.158: E/AndroidRuntime(31629): Caused by: java.lang.NullPointerException
05-03 22:33:03.158: E/AndroidRuntime(31629): at com.crackedporcelain.crackedcalibration.MainActivity.onCreate(MainActivity.java:21)
Line 21 (offender in MainActivity)
String gridPressed = content.getString("gridPressed");
Main Activity (receiver)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle content = getIntent().getExtras();
// Set image based on which button was pressed
String gridPressed = content.getString("gridPressed");
ImageView spotlightOne = (ImageView) findViewById(R.id.variousOne);
if (gridPressed.equals("one")) {
spotlightOne.setImageResource(R.drawable.one);
} else if (gridPressed.equals("two")) {
spotlightOne.setImageResource(R.drawable.two);
} else {
spotlightOne.setImageResource(R.drawable.one);
}
ImageView buttonGrid = (ImageView) findViewById(R.id.phoneReference);
buttonGrid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(
"com.crackedporcelain.crackedcalibration.IDENTIFICATION"));
}
});
}
Other Activity (sender)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.identification);
ImageView gridButton1 = (ImageView) findViewById(R.id.buttonImage1);
ImageView gridButton2 = (ImageView) findViewById(R.id.buttonImage2);
gridButton1.setOnClickListener(this);
gridButton2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonImage1:
Intent oneA = new Intent(IdentificationActivity.this, MainActivity.class);
oneA.putExtra("gridPressed", "one");
startActivity(oneA);
break;
case R.id.buttonImage2:
Intent oneB = new Intent(IdentificationActivity.this, MainActivity.class);
oneB.putExtra("gridPressed", "two");
startActivity(oneB);
break;
}
}
Additional Info
Layouts for these classes are setup correctly, they work fine. It only force closes when I try to use Intents.
All help is appreciated! Thanks!

The received intent did not contain any extra values. Make sure the code sending the intent had added to the intent an extra String value with the name "gridPressed". You can use Intent.putExtra(String, String) for this purpose.
Intent.getExtras() will return null if there are no extra values. In addition, Bundle.getString(String key) will return null if the Bundle does not contain the key.
Finally, be sure to check that MainActivity is not invocable in any other way (like when the app icon is clicked). If that is possible, then this version of onCreate() will work better:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView spotlightOne = (ImageView) findViewById(R.id.variousOne);
// Set image based on which button was pressed, if any
String gridPressed = getIntent().getStringExtra("gridPressed");
if ("one".equals(gridPressed)) {
spotlightOne.setImageResource(R.drawable.one);
} else if ("two".equals(gridPressed)) {
spotlightOne.setImageResource(R.drawable.two);
} else {
spotlightOne.setImageResource(R.drawable.one);
}
ImageView buttonGrid = (ImageView) findViewById(R.id.phoneReference);
buttonGrid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(
"com.crackedporcelain.crackedcalibration.IDENTIFICATION"));
}
});
}

You're getting a NPE because you are not sending a bundle from the sender activity rather just a string extra. So, to access the String extra in the receiver activity, use :
getIntent().getStringExtra("gridPressed");
To send bundles, you need to first create a bundle, then add extras to that bundle and then pass the bundle with the intent :
Bundle bundle = new Bundle();
bundle.putString("KEY", "VALUE");
intent.putExtras(bundle);
If you send a bundle as mentioned in 2, your existing code in the receiving activity will work, otherwise you can change the code in the receiving activity as mentioned in 1.

Related

How Can Set On Click on item , to go another layout? [duplicate]

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?
Easy.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
Don't forget to add your new activity in the AndroidManifest.xml:
<activity android:label="#string/app_name" android:name="NextActivity"/>
Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent class; Intent | Android Developers.
Using the onClick attribute of the Button. (Beginner)
Assigning an OnClickListener() via an anonymous class. (Intermediate)
Activity wide interface method using the switch statement. (not-"Pro")
Here's the link to my example if you want to follow along:
Using the onClick attribute of the Button. (Beginner)
Buttons have an onClick attribute that is found within the .xml file:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnActivity"
android:text="to an activity" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnotherActivity"
android:text="to another activity" />
In Java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public void goToAnActivity(View view) {
Intent intent = new Intent(this, AnActivity.class);
startActivity(intent);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, AnotherActivity.class);
startActivity(intent);
}
Advantage: Easy to make on the fly, modular, and can easily set multiple onClicks to the same intent.
Disadvantage: Difficult readability when reviewing.
Assigning an OnClickListener() via an anonymous class. (Intermediate)
This is when you set a separate setOnClickListener() to each button and override each onClick() with its own intent.
In Java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnActivity.class);
view.getContext().startActivity(intent);}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
view.getContext().startActivity(intent);}
});
Advantage: Easy to make on the fly.
Disadvantage: There will be a lot of anonymous classes which will make readability difficult when reviewing.
Activity wide interface method using the switch statement. (not-"Pro")
This is when you use a switch statement for your buttons within the onClick() method to manage all the Activity's buttons.
In Java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent1 = new Intent(this, AnActivity.class);
startActivity(intent1);
break;
case R.id.button2:
Intent intent2 = new Intent(this, AnotherActivity.class);
startActivity(intent2);
break;
default:
break;
}
Advantage: Easy button management because all button intents are registered in a single onClick() method
For the second part of the question, passing data, please see How do I pass data between Activities in Android application?
Edit: not-"Pro"
Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).
Intent i = new Intent(getBaseContext(), ViewPerson.class);
i.putExtra("PersonID", personID);
startActivity(i);
Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn't null (in case if you sometimes don't pass data), then get the data.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
personID = extras.getString("PersonID");
}
Now if you need to share data between two Activities, you can also have a Global Singleton.
public class YourApplication extends Application
{
public SomeDataClass data = new SomeDataClass();
}
Then call it in any activity by:
YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here. Could be setter/getter or some other type of logic
When user clicks on the button, directly inside the XML like that:
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextButton"
android:onClick="buttonClickFunction"/>
Using the attribute android:onClick we declare the method name that has to be present on the parent activity. So I have to create this method inside our activity like that:
public void buttonClickFunction(View v)
{
Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
startActivity(intent);
}
Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);
Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
startActivity(in);
This is an explicit intent to start secondscreen activity.
Emmanuel,
I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value);
CurrentActivity.this.startActivity(myIntent);
Try this simple method.
startActivity(new Intent(MainActivity.this, SecondActivity.class));
From the sending Activity try the following code
//EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
public static final String EXTRA_MESSAGE = "packageName.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
....
//Here we declare our send button
Button sendButton = (Button) findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//declare our intent object which takes two parameters, the context and the new activity name
// the name of the receiving activity is declared in the Intent Constructor
Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);
String sendMessage = "hello world"
//put the text inside the intent and send it to another Activity
intent.putExtra(EXTRA_MESSAGE, sendMessage);
//start the activity
startActivity(intent);
}
From the receiving Activity try the following code:
protected void onCreate(Bundle savedInstanceState) {
//use the getIntent()method to receive the data from another activity
Intent intent = getIntent();
//extract the string, with the getStringExtra method
String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);
Then just add the following code to the AndroidManifest.xml file
android:name="packagename.NameOfTheReceivingActivity"
android:label="Title of the Activity"
android:parentActivityName="packagename.NameOfSendingActivity"
Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
Kotlin
First Activity
startActivity(Intent(this, SecondActivity::class.java)
.putExtra("key", "value"))
Second Activity
val value = getIntent().getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val PUT_EXTRA_USER = "user"
}
startActivity(Intent(this, SecondActivity::class.java)
.putExtra(PUT_EXTRA_USER, "value"))
Starting an activity from another activity is very common scenario among android applications.
To start an activity you need an Intent object.
How to create Intent Objects?
An intent object takes two parameter in its constructor
Context
Name of the activity to be started. (or full package name)
Example:
So for example,if you have two activities, say HomeActivity and DetailActivity and you want to start DetailActivity from HomeActivity (HomeActivity-->DetailActivity).
Here is the code snippet which shows how to start DetailActivity from
HomeActivity.
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
And you are done.
Coming back to button click part.
Button button = (Button) findViewById(R.id.someid);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
}
});
The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it's a wealth of info on the subject, and has examples too.
You can try this code:
Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);
Start another activity from this activity and u can pass parameters via Bundle Object also.
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz#gmail.com");
startActivity(intent);
Retrive data in another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
// In Kotlin , you can do as
/* In First Activity, let in activity layout there is button which has id as button.
Suppose I have to pass data as String type from one activity to another */
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
// In Second Activity, you can get data from another activity as
val name = intent.getStringExtra("KEY")
/* Suppose you have to pass a Custom Object then it should be Parcelable.
let there is class Collage type which I have to pass from one activity to another
*/
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
#Parcelize
class Collage(val name: String, val mobile: String, val email: String) : Parcelable
/* Activity First , let here data is Collage type. which I have to pass to another activity. */
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
// then from second Activity we will get as
val item = intent.extras?.getParcelable<Collage>("KEY")
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SplashActivity.this,HomeActivity.class);
startActivity(intent);
}
});
Implement the View.OnClickListener interface and override the onClick method.
ImageView btnSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search1);
ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch: {
Intent intent = new Intent(Search.this,SearchFeedActivity.class);
startActivity(intent);
break;
}
Although proper answers have been already provided but I am here for searching the answer in language Kotlin. This Question is not about language specific so I am adding the code to accomplish this task in Kotlin language.
Here is how you do this in Kotlin for andorid
testActivityBtn1.setOnClickListener{
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
The Most simple way to open activity on button click is:
Create two activities under the res folder, add a button to the first activity and give a name to onclick function.
There should be two java files for each activity.
Below is the code:
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
SecondActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
}
}
AndroidManifest.xml(Just add this block of code to the existing)
</activity>
<activity android:name=".SecondActivity">
</activity>
Take Button in xml first.
<Button
android:id="#+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_launcher"
android:text="Your Text"
/>
Make listner of button.
pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
When button is clicked:
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("data", value); //pass data
startActivity(intent);
}
});
To received the extra data from NextActivity.class :
Bundle extra = getIntent().getExtras();
if (extra != null){
String str = (String) extra.get("data"); // get a object
}
Write the code in your first activity .
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
//You can use String ,arraylist ,integer ,float and all data type.
intent.putExtra("Key","value");
startActivity(intent);
finish();
}
});
In secondActivity.class
String name = getIntent().getStringExtra("Key");
Place button widget in xml like below
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
/>
After that initialise and handle on click listener in Activity like below ..
In Activity On Create method :
Button button =(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new
Intent(CurrentActivity.this,DesiredActivity.class);
startActivity(intent);
}
});
An old question but if the goal is to switch displayed pages, I just have one activity and call setContentView() when I want to switch pages (usually in response to user clicking on a button). This allows me to simply call from one page's contents to another. No Intent insanity of extras parcels bundles and whatever trying to pass data back and forth.
I make a bunch of pages in res/layout as usual but don't make an activity for each. Just use setContentView() to switch them as needed.
So my one-and-only onCreate() has:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater layoutInflater = getLayoutInflater();
final View mainPage = layoutInflater.inflate(R.layout.activity_main, null);
setContentView (mainPage);
Button openMenuButton = findViewById(R.id.openMenuButton);
final View menuPage = layoutInflatter.inflate(R.layout.menu_page, null);
Button someMenuButton = menuPage.findViewById(R.id.someMenuButton);
openMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(menuPage);
}
});
someMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
do-something-interesting;
setContentView(mainPage);
}
}
}
If you want the Back button to go back through your internal pages before exiting the app, just wrap setContentView() to save pages in a little Stack of pages, and pop those pages in onBackPressed() handler.
your button xml:
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="jump to activity b"
/>
Mainactivity.java:
Button btn=findViewVyId(R.id.btn);
btn.setOnClickListener(btnclick);
btnclick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(Mainactivity.this,b.class);
startActivity(intent);
}
});
imageView.setOnClickListener(v -> {
// your code here
});
Kotlin 2022
The simplest way:
val a = Intent(this.context, BarcodeActivity::class.java)
a.putExtra("barcode", barcode)
startActivity(a)
and in the other side (BarcodeActivity in my case):
val intent: Intent = intent
var data = intent.getStringExtra("barcode")
Read more here

getSerializableExtra() is null randomly

There is a link in one activity, after I click on it it opens another activity. I add an enum parameter for the second activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
binding.myLink.setOnClickListener(new View.OnClickListener() {
// ...
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivityContext(), SecondActivity.class);
intent.putExtra(KEY, MyEnum.ENUM_VALUE);
startActivity(intent);
}
});
// ...
}
In onCreate of second activity I read this parameter
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// get value
FirstActivity.MyEnum value = (FirstActivity.MyEnum ) getIntent()
.getSerializableExtra(AboutActivity.KEY);
// ...
}
Everything works but in Crashlytics I see that for some users value is null. Second activity is called only from first one and from nowhere else.
Can someone suggest me the scenario with this behavior? When can it happen like this?
I opened my app, opened the second activity and put app to background. After several hours I opened my app from the list of apps and everything is ok. No more ideas when it can happen.
use this :
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivityContext(), SecondActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable(serializableKEY,yourSerializableClass);
intent.putExtras(KEY, bundle);
startActivity(intent);
}
});
and in second activity :
Bundle bundle=getIntent().getExtras();
yourSerializableClass clazz=(yourSerializableClass)bundle.getSerializable(serializableKEY);

NullPointerException while calling an Activity

My program is crashing when I click on a button to bring me to another page. My OnClickListener seems correct but I know I've missed something. Can anyone see where I have went wrong?
error:
08-20 13:40:30.622: E/AndroidRuntime(1026): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.LoginScr.Example/com.LoginScr.Example.CredentialsActivity}: java.lang.NullPointerException
from main activity used to call 2nd activity:
lsRegstr.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(LoginScrExample.this, CredentialsActivity.class);
startActivity(i);
}
credentials Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
rName = (EditText)findViewById(R.id.reg_uname);
rCode= (EditText)findViewById(R.id.reg_pswd);
bReg = (Button) findViewById(R.id.reg_button);
bReg.setOnClickListener(this);
bRtn = (Button) findViewById(R.id.rtn_button);
bRtn.setOnClickListener(this);
Bundle RegBundle = getIntent().getExtras();
bundleRegName = RegBundle.getString(rUsername);
bundleRegCode = RegBundle.getString(rPasscode);
rName.setText(bundleRegName);
rCode.setText(bundleRegCode);
}
#Override
public void onClick (View v) {
rUsername = rName.getText().toString();
rPasscode = rCode.getText().toString();
RegDetails regDetails = new RegDetails();
regDetails.setlName(bundleRegName);
regDetails.setlCode(bundleRegCode);
if(v.getId()==R.id.rtn_button){
finish();
}else if(v.getId()==R.id.reg_button){
insertCredentials(regDetails);
}
}
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
String[] whereClauseArgument = new String[1];
whereClauseArgument[0] = regDetails.getlName();
System.out.println(" Credentials Saved!" + whereClauseArgument[0]);
sqliteDB.close();
finish();
}
}
There is very limited information(as stack trace) and too many possibilities of errors. You are getting NullPointerException it means some where in your code you are trying to access a null object. One genuine possibility is at this part of the code in the 2nd activity where you are trying to get extra data from the intent. As you have not added any extra data in the 1st activity you will be receiving null and then you are trying to get string out of the bundle. Try to put a check for string to be null at this point of the code.
Bundle RegBundle = getIntent().getExtras();
if(RegBundle != null) {
bundleRegName = RegBundle.getString(rUsername);
bundleRegCode = RegBundle.getString(rPasscode);
}
With that limited info, it could be a number of things. One of the most likely causes is not declaring the new activity in your androidmanifest.xml. Have you declared the activity you're trying to launch in your androidmanifest.xml?

Passing value from one window to the another in android

I want to show the value inserted by user in first window to the next window.
I am accepting the User weight & height in first window and I want to show it on the second screen as Your weight & Height.
I search a lot and even tried a code but in emulator m getting forcefully closed error.
First Activity :
public class BMI_Main extends Activity
{
EditText BMI_weight;
public String weight;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi_main);
Button submit =(Button)findViewById(R.id.BMI_submit);
BMI_weight = (EditText)findViewById(R.id.BMI_EdTx_kg);
submit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
weight = BMI_weight.getText().toString();
// create a bundle
Bundle bundle = new Bundle();
// add data to bundle
bundle.putString("wt", weight);
// add bundle to the intent
Intent intent = new Intent(v.getContext(), BMI_Result.class);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
}
);
Second Activity :
public class BMI_Result extends Activity
{
TextView Weight = (TextView)findViewById(R.id.BMI_TxtVw_wt);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi_result);
//get the bundle
Bundle bundle = getIntent().getExtras();
// extract the data
String weight = bundle.getString("wt");
Weight.setText(weight);
}
So please help me for it..
As far as I can see you have the following member definition in BMI_Result:
TextView Weight = (TextView)findViewById(R.id.BMI_TxtVw_wt);
But you can only call findViewById after the class was initialized, since it is a member function of the View class, so change this line to:
TextView Weight;
And add this line to the onCreate method right after setContentView(...):
Weight = (TextView)findViewById(R.id.BMI_TxtVw_wt);
Edit: It said "...right after super.onCreate(...)", now it's correct ;)
You should override onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
And the token at the end of onCreate is wrong.
You should use the Context.startActivity(Intent intent) method in your first window/Activity.
Store your data which you want to pass to the second window/Activity in the Intent object, like:
Intent intent = new Intent();
intent.putExtra("weight", weight);
intent.putExtra("height", height);
this.startActivity(intent);
And retrieve them in the second screen/Activity in the onCreate method, like:
Intent intent = getIntent(); // This is the intent you previously created.
int weight = intent.getExtra("weight");
int height = intent.getExtra("height");

How to start new activity on button click

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?
Easy.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
Don't forget to add your new activity in the AndroidManifest.xml:
<activity android:label="#string/app_name" android:name="NextActivity"/>
Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent class; Intent | Android Developers.
Using the onClick attribute of the Button. (Beginner)
Assigning an OnClickListener() via an anonymous class. (Intermediate)
Activity wide interface method using the switch statement. (not-"Pro")
Here's the link to my example if you want to follow along:
Using the onClick attribute of the Button. (Beginner)
Buttons have an onClick attribute that is found within the .xml file:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnActivity"
android:text="to an activity" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnotherActivity"
android:text="to another activity" />
In Java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public void goToAnActivity(View view) {
Intent intent = new Intent(this, AnActivity.class);
startActivity(intent);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, AnotherActivity.class);
startActivity(intent);
}
Advantage: Easy to make on the fly, modular, and can easily set multiple onClicks to the same intent.
Disadvantage: Difficult readability when reviewing.
Assigning an OnClickListener() via an anonymous class. (Intermediate)
This is when you set a separate setOnClickListener() to each button and override each onClick() with its own intent.
In Java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnActivity.class);
view.getContext().startActivity(intent);}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
view.getContext().startActivity(intent);}
});
Advantage: Easy to make on the fly.
Disadvantage: There will be a lot of anonymous classes which will make readability difficult when reviewing.
Activity wide interface method using the switch statement. (not-"Pro")
This is when you use a switch statement for your buttons within the onClick() method to manage all the Activity's buttons.
In Java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent1 = new Intent(this, AnActivity.class);
startActivity(intent1);
break;
case R.id.button2:
Intent intent2 = new Intent(this, AnotherActivity.class);
startActivity(intent2);
break;
default:
break;
}
Advantage: Easy button management because all button intents are registered in a single onClick() method
For the second part of the question, passing data, please see How do I pass data between Activities in Android application?
Edit: not-"Pro"
Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).
Intent i = new Intent(getBaseContext(), ViewPerson.class);
i.putExtra("PersonID", personID);
startActivity(i);
Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn't null (in case if you sometimes don't pass data), then get the data.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
personID = extras.getString("PersonID");
}
Now if you need to share data between two Activities, you can also have a Global Singleton.
public class YourApplication extends Application
{
public SomeDataClass data = new SomeDataClass();
}
Then call it in any activity by:
YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here. Could be setter/getter or some other type of logic
When user clicks on the button, directly inside the XML like that:
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextButton"
android:onClick="buttonClickFunction"/>
Using the attribute android:onClick we declare the method name that has to be present on the parent activity. So I have to create this method inside our activity like that:
public void buttonClickFunction(View v)
{
Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
startActivity(intent);
}
Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);
Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
startActivity(in);
This is an explicit intent to start secondscreen activity.
Emmanuel,
I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value);
CurrentActivity.this.startActivity(myIntent);
Try this simple method.
startActivity(new Intent(MainActivity.this, SecondActivity.class));
From the sending Activity try the following code
//EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
public static final String EXTRA_MESSAGE = "packageName.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
....
//Here we declare our send button
Button sendButton = (Button) findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//declare our intent object which takes two parameters, the context and the new activity name
// the name of the receiving activity is declared in the Intent Constructor
Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);
String sendMessage = "hello world"
//put the text inside the intent and send it to another Activity
intent.putExtra(EXTRA_MESSAGE, sendMessage);
//start the activity
startActivity(intent);
}
From the receiving Activity try the following code:
protected void onCreate(Bundle savedInstanceState) {
//use the getIntent()method to receive the data from another activity
Intent intent = getIntent();
//extract the string, with the getStringExtra method
String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);
Then just add the following code to the AndroidManifest.xml file
android:name="packagename.NameOfTheReceivingActivity"
android:label="Title of the Activity"
android:parentActivityName="packagename.NameOfSendingActivity"
Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
Kotlin
First Activity
startActivity(Intent(this, SecondActivity::class.java)
.putExtra("key", "value"))
Second Activity
val value = getIntent().getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val PUT_EXTRA_USER = "user"
}
startActivity(Intent(this, SecondActivity::class.java)
.putExtra(PUT_EXTRA_USER, "value"))
Starting an activity from another activity is very common scenario among android applications.
To start an activity you need an Intent object.
How to create Intent Objects?
An intent object takes two parameter in its constructor
Context
Name of the activity to be started. (or full package name)
Example:
So for example,if you have two activities, say HomeActivity and DetailActivity and you want to start DetailActivity from HomeActivity (HomeActivity-->DetailActivity).
Here is the code snippet which shows how to start DetailActivity from
HomeActivity.
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
And you are done.
Coming back to button click part.
Button button = (Button) findViewById(R.id.someid);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
}
});
The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it's a wealth of info on the subject, and has examples too.
You can try this code:
Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);
Start another activity from this activity and u can pass parameters via Bundle Object also.
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz#gmail.com");
startActivity(intent);
Retrive data in another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
// In Kotlin , you can do as
/* In First Activity, let in activity layout there is button which has id as button.
Suppose I have to pass data as String type from one activity to another */
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
// In Second Activity, you can get data from another activity as
val name = intent.getStringExtra("KEY")
/* Suppose you have to pass a Custom Object then it should be Parcelable.
let there is class Collage type which I have to pass from one activity to another
*/
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
#Parcelize
class Collage(val name: String, val mobile: String, val email: String) : Parcelable
/* Activity First , let here data is Collage type. which I have to pass to another activity. */
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
// then from second Activity we will get as
val item = intent.extras?.getParcelable<Collage>("KEY")
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SplashActivity.this,HomeActivity.class);
startActivity(intent);
}
});
Implement the View.OnClickListener interface and override the onClick method.
ImageView btnSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search1);
ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch: {
Intent intent = new Intent(Search.this,SearchFeedActivity.class);
startActivity(intent);
break;
}
Although proper answers have been already provided but I am here for searching the answer in language Kotlin. This Question is not about language specific so I am adding the code to accomplish this task in Kotlin language.
Here is how you do this in Kotlin for andorid
testActivityBtn1.setOnClickListener{
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
The Most simple way to open activity on button click is:
Create two activities under the res folder, add a button to the first activity and give a name to onclick function.
There should be two java files for each activity.
Below is the code:
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
SecondActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
}
}
AndroidManifest.xml(Just add this block of code to the existing)
</activity>
<activity android:name=".SecondActivity">
</activity>
Take Button in xml first.
<Button
android:id="#+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_launcher"
android:text="Your Text"
/>
Make listner of button.
pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
When button is clicked:
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("data", value); //pass data
startActivity(intent);
}
});
To received the extra data from NextActivity.class :
Bundle extra = getIntent().getExtras();
if (extra != null){
String str = (String) extra.get("data"); // get a object
}
Write the code in your first activity .
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
//You can use String ,arraylist ,integer ,float and all data type.
intent.putExtra("Key","value");
startActivity(intent);
finish();
}
});
In secondActivity.class
String name = getIntent().getStringExtra("Key");
Place button widget in xml like below
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
/>
After that initialise and handle on click listener in Activity like below ..
In Activity On Create method :
Button button =(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new
Intent(CurrentActivity.this,DesiredActivity.class);
startActivity(intent);
}
});
An old question but if the goal is to switch displayed pages, I just have one activity and call setContentView() when I want to switch pages (usually in response to user clicking on a button). This allows me to simply call from one page's contents to another. No Intent insanity of extras parcels bundles and whatever trying to pass data back and forth.
I make a bunch of pages in res/layout as usual but don't make an activity for each. Just use setContentView() to switch them as needed.
So my one-and-only onCreate() has:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater layoutInflater = getLayoutInflater();
final View mainPage = layoutInflater.inflate(R.layout.activity_main, null);
setContentView (mainPage);
Button openMenuButton = findViewById(R.id.openMenuButton);
final View menuPage = layoutInflatter.inflate(R.layout.menu_page, null);
Button someMenuButton = menuPage.findViewById(R.id.someMenuButton);
openMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(menuPage);
}
});
someMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
do-something-interesting;
setContentView(mainPage);
}
}
}
If you want the Back button to go back through your internal pages before exiting the app, just wrap setContentView() to save pages in a little Stack of pages, and pop those pages in onBackPressed() handler.
your button xml:
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="jump to activity b"
/>
Mainactivity.java:
Button btn=findViewVyId(R.id.btn);
btn.setOnClickListener(btnclick);
btnclick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(Mainactivity.this,b.class);
startActivity(intent);
}
});
imageView.setOnClickListener(v -> {
// your code here
});
Kotlin 2022
The simplest way:
val a = Intent(this.context, BarcodeActivity::class.java)
a.putExtra("barcode", barcode)
startActivity(a)
and in the other side (BarcodeActivity in my case):
val intent: Intent = intent
var data = intent.getStringExtra("barcode")
Read more here

Categories

Resources