Right now I have two activities, activity_bustracking and activity_main
When the button in the main activity is pressed it is supposed to move to the bustracking activity; however, right now it when I click the button the application crashes with the error:
05-28 16:34:32.680 26130-26130/com.example.robertloggia.test1 D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-28 16:34:32.770 26130-26130/com.example.robertloggia.test1 D/AndroidRuntime﹕ Shutting down VM
05-28 16:34:32.770 26130-26130/com.example.robertloggia.test1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.robertloggia.test1, PID: 26130
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:77)
at android.content.Intent.<init>(Intent.java:4562)
at com.example.robertloggia.test1.MainActivity$1.onClick(MainActivity.java:67)
at android.view.View.performClick(View.java:5162)
at android.view.View$PerformClick.run(View.java:20873)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
My MainActivity.class looks like:
package com.example.robertloggia.test1;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
//import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener{
//GPS Specific variables
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
boolean gps_enabled, network_enabled;
Spinner routeChoice;
Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
routeChoice = (Spinner) findViewById(R.id.route_choices);
btnSubmit = (Button) findViewById(R.id.btn_submit);
txtLat = (TextView) findViewById(R.id.textView1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//get location and make sure it is enabled
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Toast.makeText(MainActivity.this, "Please enable GPS", Toast.LENGTH_LONG).show();
}
addListenerOnButton();
}
public void addListenerOnButton() {
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this,
// "OnClickListener : " +
// "\nSpinner 1 : " + String.valueOf(routeChoice.getSelectedItem()),
// Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, BusTrackingActivity.class);
startActivity(intent);
}
});
}
/*
* METHODS FOR GETTING LOCATION
*/
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textView1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude", "enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude", "status");
}
}
My BusTrackingActivity.class looks like:
package com.example.robertloggia.test1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
/**
* Created by RobertLoggia on 5/28/15.
*/
public class BusTrackingActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bustracking);
}
}
My activity_main.xml:
<ImageView
android:layout_width="330dp"
android:layout_height="200.5dp"
android:layout_marginTop="110dp"
android:id="#+id/imageView"
android:src="#drawable/ripta_logo"
android:layout_gravity="center_horizontal"
android:contentDescription="#string/logo" />
<Spinner
android:layout_width="290dp"
android:layout_height="50dp"
android:id="#+id/route_choices"
android:entries="#array/route_array"
android:prompt="#string/route_prompt"
android:layout_gravity="center_vertical"
android:layout_below="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit_text"
android:id="#+id/btn_submit"
android:layout_gravity="center_vertical"
android:layout_alignBottom="#+id/route_choices"
android:layout_toRightOf="#id/route_choices"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please make sure GPS is enabled"
android:id="#+id/textView1"
android:layout_below="#+id/route_choices"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
activity_bustracking.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
And my android manifest looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.robertloggia.test1" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".BusTrackingActivity" >
</activity>
</application>
</manifest>
The problem is that you never assign context to this.
However, there is no reason to save off a Context in an Activity, just use MainActivity.this instead of context:
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this,
// "OnClickListener : " +
// "\nSpinner 1 : " + String.valueOf(routeChoice.getSelectedItem()),
// Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, BusTrackingActivity.class);
startActivity(intent);
}
When you are starting the new intent in this line:
Intent intent = new Intent(context, BusTrackingActivity.class);
The context object has not been initiated yet. You declared it earlier:
protected Context context;
Inside your onCreate() method, use this code:
context = this;
context in MainActivity is null.Either initialize it or use MainActivity.this in place of context.
Add the line of code from the 67th line in the MainActivity, as this is the line with the error.
However without this, I am guessing something went wrong with the button listener.
This being said, try removing all of this:
public void addListenerOnButton() {
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, BusTrackingActivity.class);
startActivity(intent);
}
});
}
Listeners are better put in the method they are used, or in this case on create. This can be done by putting this line of code:
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, BusTrackingActivity.class);
startActivity(intent);
}
});
Really though, if this doesn't work I just need to like of code at the error. If you click the first blue thing in the logcat (the rest will be grey), I can help more.
this could be because of using card view in first activity or that activity on which your app got crashed while running.
used this code to implement card view in dependencies
implementation 'androidx.cardview:cardview:1.0.0'
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
My Homepage has a problem, the app failed to start when i run it. but, when i comment out the code on .Homepage in the AndroidManifest the app can run.
Error at Logcat:
2022-05-31 13:28:30.991 5606-5606/com.example.limbangfoodhuntfortourism E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.limbangfoodhuntfortourism, PID: 5606
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.limbangfoodhuntfortourism/com.example.limbangfoodhuntfortourism.Homepage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2951)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3016)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1716)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:232)
at android.app.ActivityThread.main(ActivityThread.java:6806)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1103)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.limbangfoodhuntfortourism.Homepage.onCreate(Homepage.java:24)
at android.app.Activity.performCreate(Activity.java:6974)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2904)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3016)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1716)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:232)
at android.app.ActivityThread.main(ActivityThread.java:6806)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1103)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
this is the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.limbangfoodhuntfortourism, PID: 27159
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.limbangfoodhuntfortourism/com.example.limbangfoodhuntfortourism.Homepage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
This is my Log in code:
package com.example.limbangfoodhuntfortourism;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Login extends AppCompatActivity {
EditText mEmail, mPassword;
Button mLoginButton;
TextView mCreateLinkSignUp, mForgotPassword;
FirebaseAuth fAuth;
ProgressBar progressBar;
ImageView mLogo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEmail = findViewById(R.id.email);
mPassword = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBarLogin);
mLoginButton = findViewById(R.id.loginButton);
mCreateLinkSignUp = findViewById(R.id.signUpNow);
mForgotPassword = findViewById(R.id.forgotPassword);
fAuth = FirebaseAuth.getInstance();
mLoginButton.setOnClickListener((view) -> {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is Required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is Required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password must be >= 6 characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
// authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener((task) -> {
if(task.isSuccessful()) {
Toast.makeText(Login.this, "Logged in Successfully!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Homepage.class));
} else {
Toast.makeText(Login.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
});
mCreateLinkSignUp.setOnClickListener((view) -> {
startActivity(new Intent(getApplicationContext(), Register.class));
});
mLogo = findViewById(R.id.imageView);
mLogo.setImageResource(R.drawable.main_logo);
mForgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText resetMail = new EditText(view.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(view.getContext());
passwordResetDialog.setTitle("Reset Password?");
passwordResetDialog.setMessage("Enter Your Email To Received Reset Link.");
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// extract the mail and send reset link
String mail = resetMail.getText().toString();
fAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(Login.this, "Reset Link Sent To Your Email.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Login.this, "Error! Reset Link is Not Sent." + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}
this is my Homepage:
package com.example.limbangfoodhuntfortourism;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
public class Homepage extends AppCompatActivity {
ImageView mLogo;
TextView mLogoutLink;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
mLogoutLink = findViewById(R.id.Logout);
mLogo = findViewById(R.id.imageView);
mLogo.setImageResource(R.drawable.main_logo);
fAuth = FirebaseAuth.getInstance();
mLogoutLink.setOnClickListener((view) -> {
startActivity(new Intent(getApplicationContext(), Logout.class));
});
}
}
This is my AndroidManifest code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.limbangfoodhuntfortourism">
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.LimbangFoodHuntForTourism"
tools:targetApi="31">
<activity
android:name=".Logout"
android:exported="true" />
<activity
android:name=".RestaurantDetails"
android:exported="true" />
<activity
android:name=".Homepage"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Login"
android:exported="true" />
<activity
android:name=".Register"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:exported="true" />
</application>
</manifest>
try this in your login activity
mLogo = findViewById(R.id.imageView);
mLogo.setImageDrawable(ContextCompat.getDrawable(getActivity(),
R.drawable.main_logo));
lemme know if it works out for you
I'm trying to develop basic facebook activty and The app will get username and display it in screen but I'm facing a kind of FATAL EXCEPTION: main error I have provided my complete set of codes starting with manifest file, class file, xml file and the Logcat error,your help is highly required
The below provided code is my manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.world.trialwithmugaputhagam">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MyApplicatioon"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<activity android:name=".MainFragment" />
</application>
The below code is the class file I have used.In below code I have also assigned mTextDetails but when I hover the cursor it say the value is not assigned
import android.os.Bundle;
import android.app.Fragment;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends Fragment {
private TextView mTextDetails;
private CallbackManager mcallbackManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mcallbackManager=CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main,container,false);
}
private FacebookCallback<LoginResult> mcallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome "+ profile.getName());
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton. setReadPermissions("user_friends");
loginButton. setFragment(this);
loginButton.registerCallback(mcallbackManager, mcallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mcallbackManager.onActivityResult(requestCode, resultCode, data);
}}
The below code is my XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.world.trialwithmugaputhagam.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Welcome"
android:id="#+id/text_details"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_above="#+id/login_button"/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
android:layout_centerInParent="true"/></RelativeLayout>
Logcat error Sorry about the wrong alignment.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.world.trialwithmugaputhagam/com.example.world.trialwithmugaputhagam.MainActivity}: java.lang.ClassCastException: com.example.world.trialwithmugaputhagam.MainActivity cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.example.world.trialwithmugaputhagam.MainActivity cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Because you are extending MainActivity from Fragment. Thus, your MainActivity is not actually an Activity but a Fragment. Extend it from Activity or subclasses of Activity.
Like this:
MainActivity extends AppCompatActivity
Edit 1: (Based on comments):
You haven't initialized mTextDetails;
try to do like this in Activity's onCreate:
mTextDetails = (TextView)findViewById(R.id.text_view_id);
I'm new to android and trying to add Facebook login and catch the event after clicking the Logout button(using AccessTokenTracker) in android using facebook sdk using Android studio but i'm getting this error
here is the logcat,
// (please horizontal scroll for logcat)
01-12 00:47:15.306 12572-12572/com.example.arpit.facebooklogindemo E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity {com.example.arpit.facebooklogindemo/com.example.arpit.facebooklogindemo.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2790)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2266)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.arpit.facebooklogindemo.MainActivity.onResume(MainActivity.java:83)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
at android.app.Activity.performResume(Activity.java:5211)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2780)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2266)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Here is AndroidManifest.xml,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.arpit.facebooklogindemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
//from http://developers.facebook.com
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//from http://developers.facebook.com
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
</manifest>
Here is activity_main.xml,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.arpit.facebooklogindemo.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/textView2" />
//from http://developers.facebook.com
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_above="#+id/login_button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="90dp" />
</RelativeLayout>
Here is MainActivity.java,
package com.example.arpit.facebooklogindemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
LoginButton loginButton;
TextView textView;
AccessTokenTracker accessTokenTracker;
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
if(profile != null){
fillTextView(profile);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Log.d("find", String.valueOf(error));
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
textView.setText("Logged out");
}
}
};
accessTokenTracker.startTracking();
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, mFacebookCallback);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onResume(){
super.onResume();
Profile profile = Profile.getCurrentProfile();
textView.setText(profile.getName());
}
#Override
protected void onDestroy(){
super.onDestroy();
accessTokenTracker.stopTracking();
}
private void fillTextView(Profile profile){
textView.setText(profile.getName());
}
}
Look at this line in your logs:
Caused by: java.lang.NullPointerException
at com.example.arpit.facebooklogindemo.MainActivity.onResume(MainActivity.java:83)
It is clearly mentioned that your app is crashing due to NullPointerException in onResume() function. One possible reason is you might be getting null profile details while calling profile.getName()
Make a null checking before setting text as below:
Profile profile = Profile.getCurrentProfile();
if(null != profile)
textView.setText(profile.getName());
Sometimes, you might get null or old profile details. In such case, you need to request for updated profile details. Below is samle code:
Profile profile = Profile.getCurrentProfile();
if(null != profile) {
new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
if (currentProfile != null) {
// handle it
stopTracking();
}
}
}.startTracking();
} else {
textView.setText(profile.getName());
}
put a null check on your onResume before setting textView.
This question already has answers here:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
(46 answers)
Closed 7 years ago.
i'm getting this error when i launch my app, how can i solve this?
12112-12112/com.javacodegeeks.androidqrcodeexample E/AndroidRuntime﹕
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.javacodegeeks.androidqrcodeexample/com.javacodegeeks.androidqrcodeexample.Login}:
java.lang.NullPointerException
this is my .xml file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javacodegeeks.androidqrcodeexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.javacodegeeks.androidqrcodeexample.AndroidBarcodeQrExample"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.javacodegeeks.androidqrcodeexample.Login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and here my activity :
package com.javacodegeeks.androidqrcodeexample;
/**
* Created by Andre on 14/06/15.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity {
EditText username = (EditText)findViewById(R.id.editText);
EditText password = (EditText)findViewById(R.id.editText2);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void login(View view) {
if (username.getText().toString().equals("admin") && password.getText().toString().equals("admin")) {
Toast toast = Toast.makeText(this, "CORRECT PW", Toast.LENGTH_LONG);
toast.show();
//correcct password
Intent i = new Intent(getApplicationContext(), AndroidBarcodeQrExample.class);
i.putExtra("Disco", username.getText().toString());
startActivity(i);
} else {
Toast toast = Toast.makeText(this, "UNCORRECT PW", Toast.LENGTH_LONG);
toast.show();
//wrong password
}
}
}
Move lines:
EditText username = (EditText)findViewById(R.id.editText);
EditText password = (EditText)findViewById(R.id.editText2);
inside onCreate
EditText username;
EditText password;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText)findViewById(R.id.editText);
password = (EditText)findViewById(R.id.editText2);
}
So I'm using Android Studio for the first time. I'm got two Activities, when the Main Activity Loads it checks for a login flag set, if its not then it loads a Login Activity.
However, when I'm in the Login activity and I use a button OnClick to call a method which is in that Activity and for some reason, java is not looking in that Activity its looking in Main and throwing the following error:
java.lang.IllegalStateException: Could not find a method ExitApp(View) in the activity class com.test.apps.test.MainActivity for onClick
I'm sure I'm just missing some setting I am missing, my understanding is that java searches the current class first than its parent class, why is a button in my Second Activity even looking in my Main Activity?
AndroidManifest.xml
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login"
android:windowSoftInputMode="adjustResize|stateVisible" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
MainActivity.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String LoggedIn = preferences.getString("Logged_In", "");
if (LoggedIn.equals("")) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
else {
setContentView(R.layout.activity_main);
}
}
LoginActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.app.Activity;
public class LoginActivity extends ActionBarActivity {
private EditText username;
private EditText password;
public void ExitApp(View view){
finish();
}
activity_login.xml
<Button
android:layout_width="250dp"
android:layout_height="50dp"
android:text="Login"
android:id="#+id/btnLogin"
android:layout_below="#+id/txtPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:nestedScrollingEnabled="false"
android:onClick="ExitApp"
android:clickable="true"/>
Any help would be great...
Your method ExitApp() doesn´t exist in your Activity MainActivity:
Could not find a method ExitApp(View) in the activity class com.test.apps.test.MainActivity for onClick
If you want execute the method ExitApp() from LoginActivity load the correct layout activity_login.xml
public class LoginActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login.xml);
}
Try to stop your app with an Intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Are you actually setting the content view in your LoginActivity's onCreate method? I assume you just cut it out for brevity on here, but maybe posting the full LoginActivity and MainActivity code would help get to the bottom of it. Unless I'm missing some detail, everything you've posted looks like it should work well enough.
Otherwise, there's really no disadvantage to using findViewById() and addOnClickListener() in your Activity instead of doing it in the layout xml.
View loginButton = findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ExitApp();
}
});
So the solution is to use the following code in the .MainActivity to "start" the Login Activity properly and tell java to look in that "active" activity:
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
Question was edited to reflect the correct working code