I'm creating a mobile application for android and I have a problem when after the download connection by Google
the application crashes. Could someone give me a reason and how to attach it?
Main activities within reach.
public class MainActivity extends AppCompatActivity {
GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 3;
SignInButton signInButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("TAG", "signInResult:failed code=" + e.getStatusCode());
// updateUI(null);
}
}
}
Target activity after logging in:
public class MenuActivity extends AppCompatActivity {
GoogleSignInClient mGoogleSignInClient;
Button logoutBtn;
TextView userName;
ImageView profileImage;
private GoogleSignInOptions gso;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
logoutBtn=(Button)findViewById(R.id.button_wyl);
profileImage=(ImageView)findViewById(R.id.profileImage);
userName = findViewById(R.id.name);
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
// ...
case R.id.button_wyl:
signOut();
break;
// ...
}
}
});
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
String personName = acct.getDisplayName();
Uri personPhoto = acct.getPhotoUrl();
userName.setText(personName);
Glide.with(this).load(String.valueOf(personPhoto)).into(profileImage);
}
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MenuActivity.this, "Signed out Successfully", Toast.LENGTH_LONG).show();
finish();
}
});
}
}
Exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.goodmath, PID: 1780
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.goodmath/com.example.goodmath.MenuActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at com.example.goodmath.MenuActivity.onCreate(MenuActivity.java:46)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
I/Process: Sending signal. PID: 1780 SIG: 9
You do not call setContentView() in onCreate() of MenuActivity, so your findViewById() lookups will fail. As a result, logoutBtn is null, so you crash with a NullPointerException when you try calling a method on it.
The actual error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object
So findViewById fails.
Do setContentView(R.layout.activity_menu) directly after super.onCreate()
And if that doesn't work, are you sure that the view you are referencing is within the activity_menu layout file?
Related
So I have a listview that shows 5 chapters of the book of James from the Bible. As the user chooses the chapter he wants to read, the verses from the chapter will show. What I'm trying to do is to get position value from JamesChapter.java to be passed to the next activity Bible.java and use that value as an index value to the array I want to access in my json file that will display the verses. What happens is the app crashes when I click the chapter. I tried using getIntent() and getIntExtra() but I don't know how to use the value from those method to apply as an array index. Appreciate the help on how I can use the value from last activity to the array in my next activity. have a great day
public class JamesChapters extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_chapters);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Chapter 1");
list.add("Chapter 2");
list.add("Chapter 3");
list.add("Chapter 4");
list.add("Chapter 5");
ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(JamesChapters.this, Bible.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
}
public class Bible extends AppCompatActivity {
TextView tvReference, tvVersion, tvVerse;
String reference, version, verse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bible);
Intent intent = getIntent();
int position = intent.getIntExtra("position",0);
displayJArray(position);
}
public void displayJArray(int value){
String rid = rid();
try{
JSONObject json = new JSONObject(rid);
JSONArray jsonarray = json.getJSONArray("James");
JSONObject newjson = jsonarray.getJSONObject(value);
reference = newjson.getString("Reference");
version = newjson.getString("Version");
verse = newjson.getString("Verse");
tvReference.setText(reference);
tvVersion.setText(version);
tvVerse.setText(verse);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String rid(){
String content="";
try{
InputStream ist = getAssets().open("james.json");
int size = ist.available();
byte [] buffer = new byte[size];
ist.read(buffer);
content = new String(buffer);
}catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
This is the format of my json file
{
"James": [
{
"Reference": "James 1:1-27",
"Version": "NIV",
"Verse": "......"
},
{
"Reference": "James 2:1-26",
"Version": "NIV"
"Verse": "....."
}
]}
Here is the error from logcat
2022-11-02 15:51:32.805 25637-25676/ph.edu.nu.soco.finalproject E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
2022-11-02 15:51:42.272 25637-25637/ph.edu.nu.soco.finalproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: ph.edu.nu.soco.finalproject, PID: 25637
java.lang.RuntimeException: Unable to start activity ComponentInfo{ph.edu.nu.soco.finalproject/ph.edu.nu.soco.finalproject.Bible}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at ph.edu.nu.soco.finalproject.Bible.displayJArray(Bible.java:37)
at ph.edu.nu.soco.finalproject.Bible.onCreate(Bible.java:25)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
2022-11-02 15:51:43.018 25695-25721/ph.edu.nu.soco.finalproject E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
Your app is crashing because you have defined tvReference but it is not initialized and then you're trying to access it in displayJArray() method which results in a NullPointerException at runtime because Android fails to locate the view in Activity. Initialize your textViews in onCreate Method like the example below.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bible);
// Initialize views like this
tvReference = findViewById(R.id.id_of_your_textView_in_xml);
tvVersion = same as above ;
tvVerse = same as above;
Intent intent = getIntent();
int position = intent.getIntExtra("position",0);
displayJArray(position);
}
I'm trying to have it to where after the my "Overview" Button is clicked the next button "Variables" is enabled. The button enables, however the setOnClickListener for my "Variables" sends me to my OverviewActivity, rather than my VariablesActivity. I've been stuck on this for a while.
The Variables Activity is just a multiple choice screen, but i was just setting it up.
I'm really new to Java and Android Studio, so this is getting confusing fast
Code:
public class HomeActivity extends AppCompatActivity {
public Button signOutBtn;
public Button overviewBtn;
public Button varBtn;
FirebaseAuth auth;
boolean overviewDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
signOutBtn = findViewById(R.id.signOutBtn);
overviewBtn = findViewById(R.id.overviewBtn);
varBtn = findViewById(R.id.varBtn);
auth = FirebaseAuth.getInstance();
overviewDone = false;
signOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
finish();
}
});
overviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent overviewBtnIntent = new Intent(HomeActivity.this, OverviewActivity.class);
startActivity(overviewBtnIntent);
}
});
if (getIntent().hasExtra("state")) {
if (getIntent().getStringExtra("state").equals("enable")) {
overviewDone = true;
varBtn.setEnabled(true);
} else {
varBtn.setEnabled(false);
}
} else {
varBtn.setEnabled(false);
}
varBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent varbiesButtonIntent = new Intent(HomeActivity.this, VariablesActivity.class);
startActivity(varbiesButtonIntent);
Log.i("Variable Button", "Going to Variable Activity");
}
});
}
}
public class OverviewActivity extends AppCompatActivity {
public Button backBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
backBtn = findViewById(R.id.ov_backButton);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(OverviewActivity.this, HomeActivity.class);
intent.putExtra("state", "enable");
startActivity(intent);
}
});
}
}
public class VariablesActivity extends AppCompatActivity {
public RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_variables);
radioGroup = (RadioGroup)findViewById(R.id.RadioGroup);
// getting value of radio button checked
final String value = ((RadioButton)findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
if(radioGroup.getCheckedRadioButtonId() == -1){
// no radio buttons checked
} else{
// one the radio buttons are checked
Log.i("Radio Button Clicked", value);
}
}
}
Stacktrace:
2021-11-22 21:45:23.550 4535-4535/com.example.codehorizonapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.codehorizonapplication, PID: 4535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.codehorizonapplication/com.example.codehorizonapplication.VariablesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at com.example.codehorizonapplication.VariablesActivity.onCreate(VariablesActivity.java:24)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
int checkedId = radioGroup.getCheckedRadioButtonId();
String value = "";
if(checkedId != -1){
value = ((RadioButton)findViewById(checkedId)).getText().toString();
}
radioGroup.getCheckedRadioButtonId() returns -1 if there is nothing checked, -1 isn't a valid Id thus findViewById returns null.
null.getText() is a java.lang.NullPointerException
This is under the assumption that there is nothing selected and the fact that calling radioGroup.getCheckedRadioButtonId() doesn't crash only when you call getText() does it crash means your radioGroup = (RadioGroup)findViewById(R.id.RadioGroup); is correct.
The reason the OverviewActivity is created instead is due to a stack problem caused by the premature end to VariablesActivity due to the exception.
When I run the app I get an error while launching the app. It shows me that I forgot to do something with FireBase and it shows me this as well: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.t.androiduberremake. Make sure to call FirebaseApp.initializeApp(Context) first.
there's my code
private final static int LOGIN_REQUEST_CODE =7171;
private List<AuthUI.IdpConfig> providers;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
init();
}
private void init() {
providers = Arrays.asList(
new AuthUI.IdpConfig.PhoneBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build());
firebaseAuth =FirebaseAuth.getInstance();
listener = myFirebaseAuth ->{
FirebaseUser user = myFirebaseAuth.getCurrentUser();
if(user != null)
delaySplashScreen();
else
showLoginLayout();
};
}
private void showLoginLayout() {
AuthMethodPickerLayout authMethodPickerLayout = new AuthMethodPickerLayout
.Builder(R.layout.layout_sign_in).setPhoneButtonId(R.id.btn_phone_sign_in)
.setGoogleButtonId(R.id.btn_google_sign_in).build() ;
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAuthMethodPickerLayout(authMethodPickerLayout)
.setIsSmartLockEnabled(false).setAvailableProviders(providers)
.build(), LOGIN_REQUEST_CODE);
}
private void delaySplashScreen() {
Completable.timer(5, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.subscribe(() -> Toast.makeText(SplashScreenActivity.this, "Splash Screen done!! ", Toast.LENGTH_SHORT).show());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == LOGIN_REQUEST_CODE){
IdpResponse response = IdpResponse.fromResultIntent(data);
if(resultCode == RESULT_OK){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
}
else {
Toast.makeText(this, "[ERROR]: "+ response.getError().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
that is what console shows me when I try to run a given app:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.t.androiduberremake/com.t.androiduberremake.SplashScreenActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.t.androiduberremake. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3760)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3939)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8147)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.t.androiduberremake. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##19.3.0:184)
at com.google.firebase.auth.FirebaseAuth.getInstance(com.google.firebase:firebase-auth##19.3.2:1)
at com.t.androiduberremake.SplashScreenActivity.init(SplashScreenActivity.java:49)
at com.t.androiduberremake.SplashScreenActivity.onCreate(SplashScreenActivity.java:39)
at android.app.Activity.performCreate(Activity.java:8066)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3733)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3939)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8147)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
2020-08-13 15:33:55.746 12265-12265/? I/Process: Sending signal. PID: 12265 SIG: 9
You haven't added the google-services plugin to your build.gradle. Its important.
According to the documentation, you also have to add:
apply plugin: 'com.google.gms.google-services'
Apologizes if this is a stupid question but I'm attempting to create a Intent to the next activity in AsynTask after it has pulled a user from my AWS Database. Note that this class is HomeActivity and the next one is GroupActivity. Below I have the button that will run the AsynTask:
Button groupPageBtm = findViewById(R.id.groupPage);
groupPageBtm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoadGroupUser loadGroupUser = new LoadGroupUser(HomeActivity.this);
loadGroupUser.execute(makeUserIDString.uniqueIDCreater(userProfile));
}
});
Here is my AsynTask subclass:
class LoadGroupUser extends AsyncTask<String, Void, GroupDO>{
private DynamoDBMapper dynamoDBMapper;
Activity activity;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
#Override
protected GroupDO doInBackground(String... groupPresidentGroups) {
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
this.dynamoDBMapper = DynamoDBMapper.builder()
.dynamoDBClient(dynamoDBClient)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.build();
GroupDO groupPresDO = dynamoDBMapper.load(GroupDO.class, groupPresidentGroups[0]);
Log.i("loadedPresident: ", groupPresDO.getGroupId().toString());
return null;
}
#Override
protected void onPostExecute(GroupDO groupDO) {
super.onPostExecute(groupDO);
groupLoadIntent.putExtra("groupPresident", groupDO.getGroupPresident().toString());
activity.startActivity(groupLoadIntent);
Log.i("groupPresident", groupDO.getGroupPresident().toString());
}
}
Error Message:
-12 17:02:59.424 10503-10503/com.ronone.securesender E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ronone.securesender, PID: 10503
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:5780)
at com.ronone.securesender.LoadGroupUser.<init>(HomeActivity.java:188)
at com.ronone.securesender.HomeActivity$1.onClick(HomeActivity.java:77)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
The problem is here:
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
The field initializer runs before the constructor, so activity is still null. Do this instead:
Intent groupLoadIntent;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
groupLoadIntent = new Intent(activity, GroupActivity.class);
}
But note that you're potentially leaking your activity by having a strong reference to it in an AsyncTask. That's a whole other topic. Search this site for "AsyncTask activity leak."
When the app starts for the first time and the user grants permission, the app crashes. If the app is restarted the user is already logged in and the app works perfectly.
To recreate the error I have to delete the app from the phone and disassociate the app from my Facebook account. ( if this helps )
Also to clarify, I understand what a null pointer exception is, just don't quite understand why it is happening on only the first run. Do I need to add some kind of statement for the first time run?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
Parse.enableLocalDatastore(this);
Parse.initialize(this);
//parse test
ParseObject testObject = new ParseObject("TestObject");
testObject.put("foo", "bar");
testObject.saveInBackground();
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main_page);
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
Bundle logout_req = getIntent().getExtras();
if (logout_req != null) {
String logout = logout_req.getString("user_logout");
if (logout == "logout") {
LoginManager.getInstance().logOut();
}
}
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
if (Profile.getCurrentProfile() != null) {
Profile profile1 = Profile.getCurrentProfile();
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile1.getId());
myIntent.putExtra("user_name", profile1.getName());
MainPage.this.startActivity(myIntent);
}
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
ParseUser.logInInBackground(profile.getId(), "0", new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user == null) {
//No such user, create a new user.
ParseUser newUser = new ParseUser();
Profile profile = Profile.getCurrentProfile();
newUser.setUsername(profile.getId());
newUser.setPassword("0");
newUser.signUpInBackground();
//Send required data to home page
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile.getId());
myIntent.putExtra("user_name", profile.getName());
MainPage.this.startActivity(myIntent);
System.out.println("NEW USER CREATED! LOGGED IN AND SENT TO HOMEPAGE");
} else {
Profile profile = Profile.getCurrentProfile();
//Send required data to home page
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile.getId());
myIntent.putExtra("user_name", profile.getName());
MainPage.this.startActivity(myIntent);
System.out.println("USER LOGGED IN! SENT TO HOMEPAGE");
}
}
});
}
#Override
public void onCancel() {
info.setText("Login attempt canceled .");
}
#Override
public void onError(FacebookException e) {
info.setText("Login attempt failed.");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The error appears to happen just after loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
The error:
Process: com.george.coffeeconversation, PID: 16920
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {com.george.coffeeconversation/com.george.coffeeconversation.MainPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3680)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1300(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
at com.george.coffeeconversation.MainPage.run(MainPage.java:108)
at com.george.coffeeconversation.MainPage$1.onSuccess(MainPage.java:90)
at com.george.coffeeconversation.MainPage$1.onSuccess(MainPage.java:87)
at com.facebook.login.LoginManager.finishLogin(LoginManager.java:510)
at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:193)
at com.facebook.login.LoginManager$1.onActivityResult(LoginManager.java:136)
at com.facebook.internal.CallbackManagerImpl.onActivityResult(CallbackManagerImpl.java:82)
at com.george.coffeeconversation.MainPage.onActivityResult(MainPage.java:144)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3676)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1300(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
Apparently the Profile object you're trying to access is null at the point in time you're referencing it.
Since you mentioned it's occurring after returning from Facebook, it's probably happening in either done(ParseUser user, ParseException e) or onSuccess(LoginResult loginResult).
Try logging whether Profile.getCurrentProfile() is null at those points and you'll be able to track it down.