Setting TextView text after onActivityResult - java

I have an app with a login page.
First, I have my MainActivity where everything starts:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// here i launch LoginActivity
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE){
if(resultCode != Activity.RESULT_OK) {
finish();
}
// if login succesful, i attach to variable instance of
// logged user class.
// that part works correct, in object vars exist
loggedUser = loggedUser.getInstance();
// i want to attach strings after succesful login
emailText.setText(loggedUser.getEmail());
usernameText.setText(loggedUser.getUsername());
}
}
When run the app with the code above, after succesful LoginActivity app crashes with this exception:
2019-01-26 20:46:48.015 13071-13071/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 13071
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3586)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:89)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
at android.app.Activity.performResume(Activity.java:7022)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:156) 
at android.app.ActivityThread.main(ActivityThread.java:6523) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832) 
When I deleted the setText() methods from `onActivityResult(), I don't get that exception. The error appears when I click the Login button and the app crashes.
While debugging, compiler not even go in lines with setText()
My question is, how to set texts in textviews in the scenario that I coded above?
UPDATE
Even if i popualte strings in loggedUser in constructor as empty, move loggedUser = loggedUser.getInstance() and move setText() to onCreat, i still get that NPE.
EDIT:
I added onResume method:
#Override
protected void onResume()
{
if(isLogged) {
emailText.setText(loggedUser.getEmail());
usernameText.setText(loggedUser.getUsername());
}
super.onResume();
}
And edited onActivityResult():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE){
if(resultCode != Activity.RESULT_OK) {
finish();
}
isLogged = true; //var for if statement in onResume()
loggedUser = loggedUser.getInstance();
}
}
And i still get the same error on onResume() method when i setting up TextViews.
2019-01-26 21:21:57.752 18262-18262/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 18262
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3586)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:90)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
at android.app.Activity.performResume(Activity.java:7022)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:156) 
at android.app.ActivityThread.main(ActivityThread.java:6523)

A null view is usually a result of your layout not containing a view with the id you specified in findViewById(). Therefore findViewById() returns null and the variables are remaining null when onResume() is called. Double check your view ids in main_activity.xml.
It's also possible that the full content view is not available in onCreate() if you are using a more complicated layout. If you find that your views are null in onCreate(), try moving findViewById() to a later point in the lifecycle.

Try reordering the code like this
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);

Try initializing the variables before accessing them.
public class MainActivity extends AppCompatActivity {
TextView emailText;
TextView usernameText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// here i launch LoginActivity
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
}
Could fit in a comment
You need to access the NavigationView from the activity
Update
NavigationView navigationView = findViewById(R.id.nav_id)
View header = navigationView.getHeaderView(0)
TextView usernameText = header.findViewById(R.id.username_text_view_id);

Related

How to move reusable functionalities to a generic class and invoke another activity from there?

I am new to Android development and I am facing an issue in invoking an activity from a generic class where I have a reusable function.
I have MainActivity where I need to check if the application has Network connectivity and then check if the user is already signed in.
If the user is signed in I need to open the Rate activity otherwise I will open the Login activity.
I thought I can keep the logic that checks the Network connectivity and shows the popup reusable and move it to a Global class as below
public class Global extends AppCompatActivity {
public static boolean hasConnectivity = false;
public static boolean userSignedIn = false;
String TAG = "Debug Log - Helper";
Context context;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
context = this;
}
private void networkConnectionErrorDialog(final Context context, final Class targetClass){
Log.d(TAG, "Show Alert Dialog");
new AlertDialog.Builder(context)
.setTitle(R.string.connection_error_title)
.setMessage(R.string.connection_error_message)
.setIcon(R.drawable.warning)
.setPositiveButton(
R.string.try_again,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Trying Again");
isNetworkAvailable(context, targetClass);
}
}).show();
}
protected void isNetworkAvailable(Context context, Class targetClass) {
if(NetworkUtil.isConnected(context)){
Log.d(TAG, "Has connectivity");
if(targetClass != null){
Log.d(TAG, targetClass.toString());
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
}
hasConnectivity = true;
return;
}else{
Log.d(TAG, "Has no connectivity");
hasConnectivity = false;
networkConnectionErrorDialog(context, targetClass);
}
}
}
I pass in the targetClass as Login.class or Rate.class (based on user signed in state) from the MainActivity where isNetworkAvailable() is invoked.
I am getting the following error. Could someone help me fix the issue and help me understand if my approach needs improvement?
java.lang.RuntimeException: Unable to resume activity {com.solitontech.dayatsoliton/com.solitontech.dayatsoliton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3581)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4488)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4445)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4806)
at android.app.Activity.startActivity(Activity.java:4774)
at com.solitontech.dayatsoliton.Global.isNetworkAvailable(Global.java:50)
at com.solitontech.dayatsoliton.MainActivity.onResume(MainActivity.java:68)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1355)
at android.app.Activity.performResume(Activity.java:7117)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3556)
It looks like your application is experiencing a null pointer exception in your activity's onResume method. If you had called startActivityForResult, make sure that the data in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{..}
is non null before processing it.
As for your question about starting an activity from your helper class Global, you can define a function like this.
private static void goToActivity(Context context, Class<?> activityClass){
Intent intent = new Intent(context, activityClass);
context.startActivity(intent);
}
You can call this method as below.
goToActivity(context,TargetActivity.class);
Good luck.
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
above code is wrong. You should pass your current activity and target activity here.
Intent intent = new Intent(CurrentActivity.this, TargetingActivity.class);
startActivity(intent);
As a example :
If you want to start ActivtyB form ActivtyA
Intent intent = new Intent(ActivityA.this, ActivityD.class);
startActivity(intent);
1st try to correct this error. then you can find some others.

Null Error attempting to create an intent in AsyncTask

Apologizes if this is a stupid question but I'm attempting to create a Intent to the next activity in AsynTask after it has pulled a user from my AWS Database. Note that this class is HomeActivity and the next one is GroupActivity. Below I have the button that will run the AsynTask:
Button groupPageBtm = findViewById(R.id.groupPage);
groupPageBtm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoadGroupUser loadGroupUser = new LoadGroupUser(HomeActivity.this);
loadGroupUser.execute(makeUserIDString.uniqueIDCreater(userProfile));
}
});
Here is my AsynTask subclass:
class LoadGroupUser extends AsyncTask<String, Void, GroupDO>{
private DynamoDBMapper dynamoDBMapper;
Activity activity;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
#Override
protected GroupDO doInBackground(String... groupPresidentGroups) {
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
this.dynamoDBMapper = DynamoDBMapper.builder()
.dynamoDBClient(dynamoDBClient)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.build();
GroupDO groupPresDO = dynamoDBMapper.load(GroupDO.class, groupPresidentGroups[0]);
Log.i("loadedPresident: ", groupPresDO.getGroupId().toString());
return null;
}
#Override
protected void onPostExecute(GroupDO groupDO) {
super.onPostExecute(groupDO);
groupLoadIntent.putExtra("groupPresident", groupDO.getGroupPresident().toString());
activity.startActivity(groupLoadIntent);
Log.i("groupPresident", groupDO.getGroupPresident().toString());
}
}
Error Message:
-12 17:02:59.424 10503-10503/com.ronone.securesender E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ronone.securesender, PID: 10503
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:5780)
at com.ronone.securesender.LoadGroupUser.<init>(HomeActivity.java:188)
at com.ronone.securesender.HomeActivity$1.onClick(HomeActivity.java:77)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
The problem is here:
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
}
Intent groupLoadIntent = new Intent(activity, GroupActivity.class);
The field initializer runs before the constructor, so activity is still null. Do this instead:
Intent groupLoadIntent;
public LoadGroupUser(Activity mActivity){
this.activity = mActivity;
groupLoadIntent = new Intent(activity, GroupActivity.class);
}
But note that you're potentially leaking your activity by having a strong reference to it in an AsyncTask. That's a whole other topic. Search this site for "AsyncTask activity leak."

Context for intent in onpostexecute is not null but getting null exception

I've been stumped with this problem for two days now. I've checked this forum and other forums but can't get a question or answer close enough to my problem.
Basically I'm trying to execute an intent to open an activity from a non-activities onpostexecute, I'm sending the context (MainActivty.this) and string from a onMarkerClick function that is in a method in the MainActivity. This is going to a constructor in the non-activity which has the parameters for context and the string.
The issue is that I'm getting a null exception, but after debugging, the context is not null, it has the value of MainActivity, but when the intent is executed it returns a null exception. I've also tried many variations eg. Activity, getApplicationContext, this.context, (classname).context, (classname).this and tried a global context to no avail. The odd thing is I put the intent into an if statement if(context != null) and it passes through and it executes the intent which in turn gives me null exception which doesn't make sense. I know I'm new to android if anyone has any other suggestions on opening the activity that would be great thanks very much.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quantusapps.joggertest, PID: 12253
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:131)
at android.content.ComponentName.(ComponentName.java:77)
at android.content.Intent.(Intent.java:4029)
at com.example.quantusapps.joggertest.BusCoachTramInfo.onPostExecute(BusCoachTramInfo.java:131)
at com.example.quantusapps.joggertest.BusCoachTramInfo.onPostExecute(BusCoachTramInfo.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)<
This is the Mainactivity Method with onMarkerClick
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String bctID = bctExtraMarkerInfo.get(marker.getId());
BusCoachTramInfo busCoachTramInfo = new BusCoachTramInfo(bctID, MainActivity.this);
busCoachTramInfo.execute(bctID);
return false;
}
});
This is the non-activity constructor.
Context context;
BusCoachTramInfo(String busstopID, Context context) {
this.context = context;
naptanIdUrl = "https://api.tfl.gov.uk/StopPoint/" + busstopID + "/Arrivals?app_key=" + tfl_API_KEY + "&app_id=9c0b3009";
}
This is where the null exception is happening.
#Override
protected void onPostExecute(TreeMap<Integer, String[]> Map) {
super.onPostExecute(Map);
Intent i = new Intent(context, BusArrivalTime.class);
context.startActivity(i);
One way to get things done is implementing the AsyncTask as part of a method which takes an instance of MainActivity as a parameter. The AsyncTask on the other hand would work with a WeakReference:
void doExecuteBusCoachTramInfo(final String busstopID, MainActivity activity){
final WeakReference<MainActivity> wrActivity = new WeakReference<MainActivity>(MainActivity.this);
new AsyncTask<Void, Void, TreeMap<Integer, String[]>>(){
#Override
protected TreeMap<Integer, String[]> doInBackground(Void... params)
{
// your code from BusCoachTramInfo here
}
#Override
protected void onPostExecute(TreeMap<Integer, String[]> integerTreeMap)
{
// get back to the original Activity if possible:
MainActivity activity = wrActivity.get();
if (activity != null){
Intent i = new Intent(activity, BusArrivalTime.class);
activity.startActivity(i);
}
}
}.execute();
}
This method may be part of MainActivity, but it can just as well belong to some other class.

android.app.ActivityThread.getApplicationThread()' on a null object reference

The microhonePopUp method will work in MainActivity, but I'd like for it to work from another class (MediaButtonIntentReceiver). The problem is with startActivityForResult(intent, REQUEST_CODE); - but I don't know how to resolve it.
in the MainActivity class
public void microphonePopUp(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice your answer");
startActivityForResult(intent, REQUEST_CODE);
}
in the MediaButtonIntentReceiver class
public class MediaButtonIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode()) {
MainActivity test = new MainActivity();
test.microphonePopUp();
}
}
}
}
12-09 11:20:14.803 19556-19556/com.timtennyson.priceaddition
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.timtennyson.priceaddition, PID: 19556
java.lang.RuntimeException: Unable to start receiver
com.timtennyson.priceaddition.MediaButtonIntentReceiver:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3641)
at android.app.ActivityThread.access$2000(ActivityThread.java:221)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.Activity.startActivityForResult(Activity.java:4283)
at android.app.Activity.startActivityForResult(Activity.java:4230)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at
com.timtennyson.priceaddition.MainActivity.microphonePopUp(MainActivity.java:103)
at
com.timtennyson.priceaddition.MediaButtonIntentReceiver.onReceive(MediaButtonIntentReceiver.java:27)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3634)
at android.app.ActivityThread.access$2000(ActivityThread.java:221) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method)
NEVER create an instance of an activity, service, or provider yourself.
If your objective is to listen for ACTION_MEDIA_BUTTON broadcasts while MainActivity is visible:
Move MediaButtonIntentReceiver to be a nested class inside of MainActivity
Get rid of test from onReceive(), and just call microphonePopUp() (which I assume is a method on MainActivity)
Register your MediaButtonIntentReceiver using registerReceiver() in onStart() of MainActivity, and use unregisterReceiver() in onStop()
If your objective is to listen ACTION_MEDIA_BUTTON broadcasts at other points in time — by registering your receiver in the manifest — while you can do that, you cannot use microphonePopUp() from that receiver.

View.OnClickListener causing crash of tutorial app

First, I'm new to android SDK but I have a decent amount of experience in java. I'm attempting a tutorial on the SDK to get into it. I completed writing everything required but when I go to run it, the app crashes and I get this fatal error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
Ok, sure. Clearly, there is an issue with View.OnClickListener. Spelling, check. Capitalization, check. Parenthesis, check. Brackets, check. Semicolons, check. Next I checked the documentation for View.OnClickListener. I see its only method is onClick(View v). Ok well everything is fine there. The IDE isn't giving me any other errors. So at this point, I figure I need outside help. For referance, this is the button id:
android:id="#+id/button"
This is MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.content.Intent;
import android.view.View;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
goToSecondActivity();
}
});
}
private void goToSecondActivity() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
And here is the logcat
08-20 16:00:01.171 2565-2565/com.example.joe.helloworld E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.joe.helloworld, PID: 2565
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.joe.helloworld/com.example.joe.helloworld.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.joe.helloworld.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
You've forgotten to call setContentView() with the layout id that contains the Button.
Since there is no content layout, calls to findViewById() return null.
setContentView(R.layout.activity_main);
Right after super.onCreate(...)
You forgot to set the layout for the user to view :
setContentView(R.layout.activity_main);
Also Instead of using :
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
goToSecondActivity();
}
});
}
Just use this :
button.setOnClickListener(new Button.OnClickListener()
{
#Override
public void onClick(View v){
goToSecondActivity();
}
});
}
That means inside setOnClickListener use new Button.OnClickListener instead of View.OnClickListener

Categories