ClassNotFoundException with Parse and Facebook - java

I am hoping you can help me with a problem I am facing. I am trying to integrate Facebook login to my app using Parse, and I get a ClassNotFoundException error, when I call the method
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, permissions, new LogInCallback()
The error stack trace:
05-15 10:36:00.749 3936-3936/kstr14.tipper E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: kstr14.tipper, PID: 3936
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/parse/ParseTaskUtils;
at com.parse.ParseFacebookUtils.logInWithReadPermissionsInBackground(ParseFacebookUtils.java:173)
at kstr14.tipper.Activities.LoginActivity.facebookLoginPressed(LoginActivity.java:170)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.parse.ParseTaskUtils" on path: DexPathList[[zip file "/data/app/kstr14.tipper-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at com.parse.ParseFacebookUtils.logInWithReadPermissionsInBackground(ParseFacebookUtils.java:173)
at kstr14.tipper.Activities.LoginActivity.facebookLoginPressed(LoginActivity.java:170)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Suppressed: java.lang.ClassNotFoundException: com.parse.ParseTaskUtils
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 16 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
I have the following jar files in my lib folder:
Parse-1.9.1.jar
javax.mail.jar
bolts-android-1.2.0.jar
ParseFacebookUtilsV4-1.9.2.jar
I have tried various things with the dependencies part of the build.gradle file, as I suspect this error is due to some library not being included correctly, but none of what I have tried have worked. I've tried different ways of specifying compiling the jar files as well as specifying the jars in different orders.
Currently my build.gradle file looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "kstr14.tipper"
minSdkVersion 21
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
debuggable true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
repositories {
mavenCentral()
}
dependencies {
compile fileTree(include: ['*.jar'] ,dir: 'libs')
compile files('libs/bolts-android-1.2.0.jar')
compile 'com.parse.bolts:bolts-android:1.2.0'
compile files('libs/Parse-1.9.1.jar')
compile files('libs/ParseFacebookUtilsV4-1.9.2.jar')
compile files('libs/javax.mail.jar')
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
}
Anyone have any suggestions?
Oh and by the way, when my app crashes due to the error, I press OK, and then the Facebook login screen shows up anyway.. So I suppose the facebook jar is being imported fine, and the problem is within the Parse jars. However, I have been using the Pars jar before I tried to integrate Facebook, and it worked just fine. I imported the bolts jar at the same time I imported the Facebook jar, as I read somewhere that it was necessary, so it might be a problem with the bolts jar?
EDIT: Added code for LoginActivity:
package kstr14.tipper.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import com.facebook.FacebookSdk;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import java.util.ArrayList;
import java.util.List;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import kstr14.tipper.Data.Category;
import kstr14.tipper.Data.Group;
import kstr14.tipper.Data.Tip;
import kstr14.tipper.R;
public class LoginActivity extends ActionBarActivity {
// UI elements for default login fragment
private EditText usernameDefaultLogin;
private EditText passwordDefaultLogin;
// UI elements for sign up fragment
private EditText usernameSignup;
private EditText emailSignup;
private EditText passwordSignup;
private EditText reenterPasswordSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
// initalize facebook
FacebookSdk.sdkInitialize(getApplicationContext());
// Initialize Parse
ParseObject.registerSubclass(Tip.class);
ParseObject.registerSubclass(Category.class);
ParseObject.registerSubclass(Group.class);
ParseObject.registerSubclass(ParseUser.class);
// check cache for current user - if found go directly to MainActivity
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
// otherwise set fragment to the default login screen
DefaultLoginFragment defaultLoginFragment = new DefaultLoginFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, defaultLoginFragment).commit();
}
// Required for making Facebook login work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
/**
* Method called when sign up button pressed on the default login fragment
* Switches the default login fragment with a sign up fragment
* #param view
*/
public void defaultSignUpPressed(View view) {
SignUpFragment signUpFragment = new SignUpFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Replace the default login fragment with the sign up fragment,
// and add the transaction to the back stack so the user can navigate back
fragmentTransaction.replace(R.id.fragment_container, signUpFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* Method called when login button pressed on the default login fragment
* Attempts to log in the user, if successful goes to MainActivity
* #param view
*/
public void defaultLoginPressed(View view) {
// initialize UI elements for default login fragment
usernameDefaultLogin = (EditText) findViewById(R.id.usernameDefaultLoginFragment);
passwordDefaultLogin = (EditText) findViewById(R.id.passwordDefaultLoginFragment);
// fetch input and attempt login
String username = usernameDefaultLogin.getText().toString();
String password = passwordDefaultLogin.getText().toString();
ParseUser.logInInBackground(username, password, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Method called when sign up button pressed in sign up fragment
* Attempts to register the user, if successful goes to MainActivity
* #param view
*/
public void signupPressed(View view) {
// UI elements for sign up fragment
usernameSignup = (EditText) findViewById(R.id.usernameSignupFragment);
emailSignup = (EditText) findViewById(R.id.emailSignupFragment);
passwordSignup = (EditText) findViewById(R.id.passwordSignupFragment);
reenterPasswordSignup = (EditText) findViewById(R.id.reenterPasswordSignupFragment);
String username = usernameSignup.getText().toString();
String email = emailSignup.getText().toString();
String password1 = passwordSignup.getText().toString();
String password2 = reenterPasswordSignup.getText().toString();
// validate passwords and email
if(!validatePassword(password1, password2)) {
Toast.makeText(getApplicationContext(), "Passwords do not match, try again.", Toast.LENGTH_SHORT).show();
} else if (!validateEmail(email)) {
Toast.makeText(getApplicationContext(), "Please enter a valid email.", Toast.LENGTH_SHORT).show();
} else {
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password1);
user.setEmail(email);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Sign up failed. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void facebookLoginPressed(View view) {
List<String> permissions = new ArrayList<String>();
permissions.add("public_profile");
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
/**
* Validates that two passwords are equal
* #param password1
* #param password2
* #return
*/
public boolean validatePassword(String password1, String password2) {
if(password1.equals(password2)) return true;
else return false;
}
/**
* Validates the structure of an email address
* #param email
* #return
*/
public boolean validateEmail(String email) {
boolean result = true;
try {
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
} catch (AddressException e) {
e.printStackTrace();
result = false;
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

I actually just ran into this same problem. Hopefully I can save a lot of headache for anyone searching for this issue. The answer is not to use an older SDK. Actually all you needed to do was be sure that you were using the same version of Parse and ParseFacebookUtils. Look at your gradle file above
compile 'com.parse.bolts:bolts-android:1.2.0'
compile files('libs/Parse-1.9.1.jar')
compile files('libs/ParseFacebookUtilsV4-1.9.2.jar')
You were using Parse-1.9.1 and ParseFacebookUtilsV4-1.9.2. I actually made the same mistake. I pulled the Parse-1.9.1 from another project and downloaded the SDK again to pull the FacebookUtils library out.

After trying a bunch of different things, including upgrading AndroidStudio and gradle, I solved this by using an older version of the Parse libraries. I was using the newest version 1.9.2, and now I am using 1.9.0, and it works! So there must be some bug in the new version..

Related

My targetSDKVersion is 28 and I couldnt implement "Take Picture" function on this sdk version

I was told that this may because that if targetSdkVersion is >= Android 6.0(API level 23), developer need to add some code for request related permissions from the user at the runtime.
"If you still want to implement the "Open Camera/Take Picture" function, you should request the permisson of CAMERA for take pictures and storage related permisson for saving pictures at the runtime. And maybe FileProvider can be used to store pictures."
How can I implement this suggestion in my project?
This is my SelectImageActivity where the code for TAKEPICTURE involves
package com.microsoft.projectoxford.face.samples.ui;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import com.microsoft.projectoxford.face.samples.R;
import java.io.File;
import java.io.IOException;
// The activity for the user to select a image and to detect faces in the image.
public class SelectImageActivity extends AppCompatActivity {
// Flag to indicate the request of the next task to be performed
private static final int REQUEST_TAKE_PHOTO = 0;
private static final int REQUEST_SELECT_IMAGE_IN_ALBUM = 1;
// The URI of photo taken with camera
private Uri mUriPhotoTaken;
// When the activity is created, set all the member variables to initial state.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_image);
}
// Save the activity state when it's going to stop.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("ImageUri", mUriPhotoTaken);
}
// Recover the saved state when the activity is recreated.
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mUriPhotoTaken = savedInstanceState.getParcelable("ImageUri");
}
// Deal with the result of selection of the photos and faces.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode)
{
case REQUEST_TAKE_PHOTO:
case REQUEST_SELECT_IMAGE_IN_ALBUM:
if (resultCode == RESULT_OK) {
Uri imageUri;
if (data == null || data.getData() == null) {
imageUri = mUriPhotoTaken;
} else {
imageUri = data.getData();
}
Intent intent = new Intent();
intent.setData(imageUri);
setResult(RESULT_OK, intent);
finish();
}
break;
default:
break;
}
}
// When the button of "Take a Photo with Camera" is pressed.
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null) {
// Save the photo taken to a temporary file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File file = File.createTempFile("IMG_", ".jpg", storageDir);
mUriPhotoTaken = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
setInfo(e.getMessage());
}
}
}
// When the button of "Select a Photo in Album" is pressed.
public void selectImageInAlbum(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_IMAGE_IN_ALBUM);
}
}
// Set the information panel on screen.
private void setInfo(String info) {
TextView textView = (TextView) findViewById(R.id.info);
textView.setText(info);
}
}
This is my build gradle (:app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.microsoft.projectoxford.faceapisample"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
// Include local lib mostly for debug purpose.
// implementation project(':lib')
// Use the following line to include client library for Face API from Maven Central Repository
implementation 'com.microsoft.projectoxford:face:1.4.4'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
compile project(':voicetwo')
implementation project(':voicetwo')
}
My error log :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.microsoft.projectoxford.faceapisample, PID: 16272
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:7167)
at android.view.View.performClickInternal(View.java:7140)
at android.view.View.access$3500(View.java:813)
at android.view.View$PerformClick.run(View.java:27597)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7519)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:7167) 
at android.view.View.performClickInternal(View.java:7140) 
at android.view.View.access$3500(View.java:813) 
at android.view.View$PerformClick.run(View.java:27597) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:224) 
at android.app.ActivityThread.main(ActivityThread.java:7519) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995) 
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.microsoft.projectoxford.faceapisample/files/Pictures/IMG_2029674407291738623.jpg exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:2089)
at android.net.Uri.checkFileUriExposed(Uri.java:2388)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:977)
at android.content.Intent.prepareToLeaveProcess(Intent.java:10780)
at android.content.Intent.prepareToLeaveProcess(Intent.java:10765)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1710)
at android.app.Activity.startActivityForResult(Activity.java:5258)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:5216)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at com.microsoft.projectoxford.face.samples.ui.SelectImageActivity.takePhoto(SelectImageActivity.java:103)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:7167) 
at android.view.View.performClickInternal(View.java:7140) 
at android.view.View.access$3500(View.java:813) 
at android.view.View$PerformClick.run(View.java:27597) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:224) 
at android.app.ActivityThread.main(ActivityThread.java:7519) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995) 
E/MQSEventManagerDelegate: failed to get MQSService.
D/OOMEventManagerFK: checkEventAndDumpForJE: 0
E/MQSEventManagerDelegate: failed to get MQSService.
The line in the error log at com.microsoft.projectoxford.face.samples.ui.SelectImageActivity.takePhoto(SelectImageActivity.java:103) is
startActivityForResult(intent, REQUEST_TAKE_PHOTO);

New To Android Development: App Runs On My MacBook Pro But Fails With Kotlin Typecast Exception on iMac

This is the weirdest thing.. A few weeks ago I ran into this issue and found the solution to be to update the Gradle Runtime, which I did on both computers. I decided I wanted to sit at my desk with my iMac and work last night, but could not get the app to run do to a Kotlin Typecast Exception. I switched to the remote branch I have pulled on my MacBook, but got this error:
09-23 12:28:29.112 4141-4141/com.example.pmarl.peedeehealthadvisor E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pmarl.peedeehealthadvisor, PID: 4141
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pmarl.peedeehealthadvisor/com.example.pmarl.peedeehealthadvisor.MainActivity}: kotlin.TypeCastException: null cannot be cast to non-null type android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: kotlin.TypeCastException: null cannot be cast to non-null type android.widget.Button
at com.example.pmarl.peedeehealthadvisor.MainActivity.onCreate(MainActivity.kt:31)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
I panic'd and tested the MacBook again, but it worked fine.
`
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private Button MyHealthData;
private Button MyHealthResources;
private boolean firstStart;
#Override
protected void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
/*First time open code*/
SharedPreferences app_preferences = getApplicationContext()
.getSharedPreferences("MyPref",0);
SharedPreferences.Editor editor = app_preferences.edit();
firstStart = app_preferences.getBoolean("first_time_start",true);
/*If statement to see if the app has been open before or not*/
if(firstStart)
{
/*If the app hasn't been opened before, it runs the following code
* and sets firstStart to false*/
editor.putBoolean("first_time_start",false);
editor.commit();
//do your one time code here
launchFirstTimeLogIn();
//Toast.makeText(this,"This is first app run!", Toast.LENGTH_LONG).show();
}
else
{
//app open directly
Toast.makeText(this, "Welcome!!!", Toast.LENGTH_LONG).show();
}
this.MyHealthData = (Button) findViewById(R.id.MyHealthData);
this.MyHealthData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchMyHealthData();
}
});
this.MyHealthResources = (Button) findViewById(R.id.HealthResources);
this.MyHealthResources.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchSearchServiceActivity();
}
});
}
private void launchMyHealthData()
{
Intent intent = new Intent (this, MyHealthDataActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
private void launchSearchServiceActivity()
{
Intent intent = new Intent (this, SearchServiceActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
private void launchFirstTimeLogIn()
{
Intent intent = new Intent(this, FirstTimeLogin.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
`
Both are the same Gradle versions, and the same version of Android Studio. I"m not sure what this would be caused by? My logic says that if it is the Button causing the issue, like the posts I found say, it wouldn't work on my MacBook.
Thank you for the help everyone!
null cannot be cast to non-null type android.widget.Button
I'm assuming that you declared a Button like this: (for example)
mineBtn = findViewById(R.id.yourbtnid) as Button
Add "?" after the as:
mineBtn = findViewById(R.id.yourbtnid) as? Button
Then error should be gone.
Edit: Remove this. before declaring widgets. And declare a widget like this:
MyHealthData = (Button) findViewById(R.id.MyHealthData);
Note that it's better to change R.id.MyHealthData from xml layout to be make sure it won't cause other issues in future.

Issue when compiling android application

Good evening. I am taking a course in android and having issues compiling the app.
I am currently following this tutorial. I have earlier set up a requestQueue for GET requests.
This is my MainActivity.java file:
package com.ticketapp.emailaddresss.ticketapp;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.share.model.ShareHashtag;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
String server_url = "https://www.idg.se/";
RequestQueue requestQueue;
private ShareDialog shareDialog;
private String name, surname, imageUrl;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.bm);
textView = (TextView) findViewById(R.id.txt);
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
nameView.setText("" + name + " " + surname);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response);
//requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Something went wrong");
error.printStackTrace();
//requestQueue.stop();
}
});
//requestQueue.add(stringRequest);
SingletonRequestQueue.getmInstance(getApplicationContext()).addRequestQueue(stringRequest);
}
});
}
private void share() {
shareDialog = new ShareDialog(this);
List<String> taggedUserIds = new ArrayList<String>();
taggedUserIds.add("{USER_ID}");
taggedUserIds.add("{USER_ID}");
taggedUserIds.add("{USER_ID}");
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse("http://www.sitepoint.com"))
.setContentTitle("This is a content title")
.setContentDescription("This is a description")
.setShareHashtag(new ShareHashtag.Builder().setHashtag("#sitepoint").build())
.setPeopleIds(taggedUserIds)
.setPlaceId("{PLACE_ID}")
.build();
shareDialog.show(content);
}
private void getPosts() {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/posts", null, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e(TAG, response.toString());
}
}).executeAsync();
}
private void logout() {
LoginManager.getInstance().logOut();
Intent login = new Intent(MainActivity.this, LoginActivity.class);
startActivity(login);
finish();
}
//#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.share:
share();
break;
case R.id.getPosts:
getPosts();
break;
case R.id.logout:
logout();
break;
}
}
}
LoginActivity.java
package com.ticketapp.emailaddress.ticketapp;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private LoginButton loginButton;
private String firstName,lastName, email,birthday,gender;
private URL profilePicture;
private String userId;
private String TAG = "LoginActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// FacebookSdk.sdkInitialize(this);
//FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setHeight(100);
loginButton.setTextColor(Color.WHITE);
loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
loginButton.setCompoundDrawablePadding(0);
loginButton.setReadPermissions("email", "user_birthday","user_posts");
loginButton.registerCallback(callbackManager, callback);
}
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG,object.toString());
Log.e(TAG,response.toString());
try {
userId = object.getString("id");
profilePicture = new URL("https://graph.facebook.com/" + userId + "/picture?width=500&height=500");
if(object.has("first_name"))
firstName = object.getString("first_name");
if(object.has("last_name"))
lastName = object.getString("last_name");
if (object.has("email"))
email = object.getString("email");
if (object.has("birthday"))
birthday = object.getString("birthday");
if (object.has("gender"))
gender = object.getString("gender");
Intent main = new Intent(LoginActivity.this,MainActivity.class);
main.putExtra("name",firstName);
main.putExtra("surname",lastName);
main.putExtra("imageUrl",profilePicture.toString());
startActivity(main);
finish();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
//Here we put the requested fields to be returned from the JSONObject
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, birthday, gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
e.printStackTrace();
}
};
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
}
SingletonRequestQueue.java
package com.ticketapp.emailaddress.ticketapp;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import java.lang.ref.ReferenceQueue;
/**
* Created by Adde on 2017-09-11.
*/
public class SingletonRequestQueue {
private
static SingletonRequestQueue mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
private SingletonRequestQueue(Context context){
mCtx = context;
requestQueue = getRequestQueue();
}
public RequestQueue getRequestQueue(){
if(requestQueue == null){
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
public static synchronized SingletonRequestQueue getmInstance(Context context) {
if(mInstance == null){
mInstance = new SingletonRequestQueue(context);
}
return mInstance;
}
public<T> void addRequestQueue(Request<T> request){
requestQueue.add(request);
}
}
build.gradle (module)
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.ticketapp.myName.ticketapp"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
//FB SDK
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
// compile 'com.android.support:design:26.0.1'
// compile 'com.android.support:appcompat-v7:26.0.1'
// compile 'com.android.support:multidex:1.0.1'
// Firebase
// Volley
// compile 'com.android.volley:volley:1.0.0'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-auth:11.2.2'
compile 'com.mcxiaoke.volley:library:1.0.19'
//compile "com.google.android.gms:play-services-location:11.2.2"
testCompile 'junit:junit:4.12'
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
build.gradle (app)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
//FB SDK
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// Add this line
classpath 'com.google.gms:google-services:3.1.0'
}
}
allprojects {
repositories {
jcenter()
//FB SDK
maven {
url "https://maven.google.com" // Google's Maven repository
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
logcat message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 9650
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.
at com.facebook.internal.Validate.sdkInitialized(Validate.java:145)
at com.facebook.AccessTokenTracker.<init>(AccessTokenTracker.java:55)
at com.facebook.login.widget.LoginButton$2.<init>(LoginButton.java:581)
at com.facebook.login.widget.LoginButton.configureButton(LoginButton.java:581)
at com.facebook.FacebookButtonBase.<init>(FacebookButtonBase.java:64)
at com.facebook.login.widget.LoginButton.<init>(LoginButton.java:210)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 
at android.view.LayoutInflater.createView(LayoutInflater.java:647) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49) 
at android.app.Activity.performCreate(Activity.java:6975) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="Secretokrn" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:screenOrientation="portrait" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProviderSecretToken"
android:exported="true" />
<activity android:name=".LoginActivity"></activity>
</application>
strings.xml
<resources>
<string name="app_name">TicketApp</string>
<string name="facebook_app_id">SecretToken</string>
<string name="fb_login_protocol_scheme">fbSecretToken</string>
<string name="app_id">$app_id_here</string>
<string name="ShareContent">Share Content</string>
<string name="Posts">Posts</string>
<string name="Logout">Logout</string>
<string name="Hello">Hello</string>
</resources>
I hope I have included enough for a replicating this or solving it without testing.
Updated catlog.
09-12 15:13:21.988 5675-5675/com.ticketapp.myname.ticketapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 5675
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Ok guys! New update! Apparently there was an issue in the code so I put a try and catch and the application worked. Unfortunately when u log in nothing displays at the moment. This is what I changed in the MainActivity.java
try {
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
nameView.setText("" + name + " " + surname);
} catch (Exception e){
Log.e("Error on setContent", e.getMessage());
}
In your MainActivity, you have this:
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
But the first time you load it, inBundle will be null. You should check if it is null before running getString on it:
Bundle inBundle = getIntent().getExtras();
if(inBundle!=null){
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
}

ClassCastException : Fragment cannot be cast to Fragment

I have that app when, in MainActivity(which here is LoginActivity) first is replaced with a fragment(LoginFragment), for the sake of good code.
If a user want to signup, is redirected to a new SignUpFragment directly from mainActivity supportFragment manager:
//setting the first fragment in onCreate
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
//Opening new registration fragment in LoginFragment.java
signUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((LoginActivity)getActivity()).loadSignUpFragment();
}
});
//In LoginActvity.java
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
all good, is working at first opening. Trying to register a new user, is working
But, after applying some minor code changes(like showing a snackbar if login fails), i got that error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.minimalart.studentlife/com.minimalart.studentlife.activities.LoginActivity}: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519)
at android.app.ActivityThread.-wrap19(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at com.minimalart.studentlife.activities.LoginActivity$override.onCreate(LoginActivity.java:38)
at com.minimalart.studentlife.activities.LoginActivity$override.access$dispatch(LoginActivity.java)
at com.minimalart.studentlife.activities.LoginActivity.onCreate(LoginActivity.java:0)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) 
at android.app.ActivityThread.-wrap19(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
why i got that?
i'm switching and opening fragments only from my main activity
Thanks.
all LoginActivity.java:
package com.minimalart.studentlife.activities;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.minimalart.studentlife.R;
import com.minimalart.studentlife.fragments.LoginFragment;
import com.minimalart.studentlife.fragments.SignUpFragment;
public class LoginActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
}
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
public void signUpNewUser(String email, String pass, String firstName, String secName, String age){
firebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
}
else{
Snackbar.make(findViewById(R.id.signUpLinearLayout), task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
// ...
}
});
}
public void logInUser(String email, String pass){
}
}
I solved this, i found that the problem is at declaring main fragment
replaced
LoginFragment fragment = (LoginFragment)fragmentManager.findFragmentById(R.id.activity_main_content);
with
Fragment fragment = fragmentManager.findFragmentById(R.id.activity_main_content);
thanks #Selvin for your hint :)

Error while opening Android app

i am new to android development and i am writing an app for my college project .The app transmits a string of data stored in shared preferences .The data is stored by one time setup screen which is never shown again.The issue is after first time,when app is started again it shows that "app has unfortunately stopped working "and when i click ok the app starts.Can anybody tell me why this is happening?
Code:
package com.example.homeautomation.zigbeehomeauto;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainScreen extends ActionBarActivity {
NdefMessage msg;
NfcAdapter nfcadapter;
public static final String PREFS_NAME = "MyPrefsFile";
public String pass2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
String Pass = check.getString("Str", "Nothing");
pass2 = Pass;
nfcadapter = NfcAdapter.getDefaultAdapter(this);
if (nfcadapter == null) {
Toast.makeText(this, "NFC is not available User", Toast.LENGTH_LONG)
.show();
finish();
}
}
public void ExApp(View v) {
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void Nsend(View v)
{
byte[] stringBytes = pass2.getBytes();
nfcadapter.setNdefPushMessage(msg = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", stringBytes)
}),this);
}
}
Logcat Ouput:
04-07 12:04:38.478 10836-10836/com.example.homeautomation.zigbeehomeauto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.homeautomation.zigbeehomeauto, PID: 10836
android.util.SuperNotCalledException: Activity {com.example.homeautomation.zigbeehomeauto/com.example.homeautomation.zigbeehomeauto.SetupScreen} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2603)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5752)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Check in your SetupScreen.java do you have super.onCreate(savedInstanceState);
after onCreate() Method is starts .
post your SetupScreen.java code also ..
Your onCreate() method of class SetupScreen do not call the super.onCreate(). Add the statement and the error should go away.

Categories

Resources