package com.example.android.interestcalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText amountEditText;
EditText rupeePerHundred;
Button calculateButton;
TextView resultTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
//error here calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountString = amountEditText.getText().toString();
String rupeePerHundredString = rupeePerHundred.getText().toString();
if (amountString.isEmpty() & rupeePerHundredString.isEmpty()) {
Toast.makeText(MainActivity.this, " input a value", Toast.LENGTH_SHORT).show();
} else {
int result = calculateInterest(amountString, rupeePerHundredString);
displayResult(result);
}
}
});
}
private void displayResult(int result) {
resultTextView.setText(result);
}
private int calculateInterest(String amountString, String rupeePerHundredString) {
int amount = Integer.parseInt(amountString);
int rupees = Integer.parseInt(rupeePerHundredString);
return amount / 100 * rupees;
}
private void findViews() {
amountEditText = findViewById(R.id.edit_text_amount);
rupeePerHundred = findViewById(R.id.edit_text_rupee_per_hundred);
resultTextView = findViewById(R.id.text_view_result);
}
}
LOGCAT:
2021-07-18 18:01:16.942 5655-5655/com.example.android.interestcalculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.interestcalenter image description hereculator, PID: 5655
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.interestcalculator/com.example.android.interestcalculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.android.interestcalculator.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) **
you should findViewById for your Button calculateButton
set this code in findViews()
calculateButton = findViewById(R.id.calculateButton);
Related
All,
Just want to be straight with everyone that I have no idea what I am doing lol. But I am having an issue implementing SharedPreferences onPause\onResume in this project, and I am wondering if someone can tell me where I am going wrong.
Error details:
`E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.androidlabs, PID: 2260
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androidlabs/com.example.androidlabs.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:744)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.androidlabs.MainActivity.<init>(MainActivity.java:19)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) `
Here is my main activity code. I can tell that the issue is coming from onResume (I think!) but no clue why!
`package com.example.androidlabs;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
//initializing variables
Button next = (Button) findViewById(R.id.next);
EditText name = (EditText) findViewById(R.id.name); //initializing variables
public static final String SHARED_PREF = "sharedprefs";
public static final String TEXT = "text";
private String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sh.edit();
editor.putString("name", name.getText().toString());
editor.apply();
openNameActivity();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String savedName = sh.getString("name",null);
if (savedName != null){
name.setText(savedName);
}
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
//save the users name in My Shared Pref
SharedPreferences.Editor editor = sh.edit();
editor.putString("name", name.getText().toString());
editor.apply();
}
public void openNameActivity(){
EditText name = (EditText) findViewById(R.id.name);
String nameText = name.getText().toString();
Intent intent = new Intent(MainActivity.this, NameActivity.class);
intent.putExtra("name", nameText);
startActivityForResult(intent, 1);
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
int result = data.getIntExtra("namePref", 0);
if(result == 0){
Toast.makeText(MainActivity.this,"Choose a new name", Toast.LENGTH_LONG).show();
}else{
finishAndRemoveTask();
}
}
if(resultCode == RESULT_CANCELED){
Toast.makeText(MainActivity.this,"Something went wrong", Toast.LENGTH_LONG).show();
}
}
}
}`
Your app is crashing when you open your app?
It looks like you are doing initialisation of your button and editText at wrong place
can you move below mentioned code to onCreate method and place it below of setContentView method
next = (Button) findViewById(R.id.next);
name = (EditText) findViewById(R.id.name);
and also you will need to declare next and name both variable
I need to start an activity with details of some data passing a parameter that I get from my Firebase DB on my Intent, but everytime I click an item on the Adapter my app crashes.
I have an activity like this:
And need to open something like this:
Here is my Adapter.setOnClickListener code:
viewHolder.eventCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent eventIntent = new Intent(getContext(), EventActivity.class);
eventIntent.putExtra("event_id", event.getName());
startActivity(eventIntent);
}
});
And here is my new activity code to get that parameter:
package br.com.ministeriosonhodedeus.sonhodedeus.activity;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import br.com.ministeriosonhodedeus.sonhodedeus.R;
import br.com.ministeriosonhodedeus.sonhodedeus.domain.Event;
import br.com.ministeriosonhodedeus.sonhodedeus.fragments.EventFragment;
public class EventActivity extends BaseActivity {
private Event e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
setUpToolbar();
e = getIntent().getParcelableExtra("event_id");
getSupportActionBar().setTitle(e.getName());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ImageView appBarImg = (ImageView) findViewById(R.id.appBarImg);
Picasso.with(getContext()).load(e.geturl_foto()).into(appBarImg);
if (savedInstanceState == null) {
EventFragment frag = new EventFragment();
frag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.EventFragment, frag).commit();
}
}
public void setTitle(String s) {
CollapsingToolbarLayout c = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
c.setTitle(s);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
ActivityCompat.finishAfterTransition(getActivity());
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my error logcat:
03-21 14:18:12.390 27190-27190/br.com.ministeriosonhodedeus.sonhodedeus E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.ministeriosonhodedeus.sonhodedeus, PID: 27190
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.ministeriosonhodedeus.sonhodedeus/br.com.ministeriosonhodedeus.sonhodedeus.activity.EventActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String br.com.ministeriosonhodedeus.sonhodedeus.domain.Event.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String br.com.ministeriosonhodedeus.sonhodedeus.domain.Event.getName()' on a null object reference
at br.com.ministeriosonhodedeus.sonhodedeus.activity.EventActivity.onCreate(EventActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Any idea of what went wrong? Thanks!
To solve this, please change this line of code:
e = getIntent().getParcelableExtra("event_id");
with
String event_id = (String) getIntent().getExtras().get("event_id");
and this:
getSupportActionBar().setTitle(e.getName());
with
getSupportActionBar().setTitle(event_id);
I'm making an application that requires location of the device. I have no issues with permissions and the location is being stored in the Location object. The latitudes and longitudes from the object are being displayed in text views too. However, when I write:
double d = mLastLocation.getLatitude();
the app crashes.
The code I have written is:
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Map;
public class NodeList extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private FusedLocationProviderClient mFusedLocationClient;
private Location mLastLocation;
private TextView lat;
private TextView lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_node_list);
mListView = (ListView)findViewById(R.id.listView);
myRef = FirebaseDatabase.getInstance().getReference().child("Users");
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, latitudes);
mListView.setAdapter(arrayAdapter);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
lat = (TextView)findViewById(R.id.recLat);
lon = (TextView)findViewById(R.id.recLon);
getLastLocation();
double d = mLastLocation.getLatitude();
}
#Override
public void onStart() {
super.onStart();
if (!checkPermissions()) {
requestPermissions();
}
}
private void startLocationPermissionRequest() {
ActivityCompat.requestPermissions(NodeList.this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION);
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale, android.R.string.ok,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
startLocationPermissionRequest();
}
});
} else {
Log.i(TAG, "Requesting permission");
startLocationPermissionRequest();
}
}
#SuppressWarnings("MissingPermission")
private void getLastLocation() {
mFusedLocationClient.getLastLocation()
.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mLastLocation = task.getResult();
lat.setText("Latitude: " + Double.toString(mLastLocation.getLatitude()));
lon.setText("Longitude: "+Double.toString(mLastLocation.getLongitude()));
} else {
Log.w(TAG, "getLastLocation:exception", task.getException());
showSnackbar(getString(R.string.no_location_detected));
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
} else {
showSnackbar(R.string.permission_denied_explanation, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
}
This is really starting to frustrate me as I can't figure out what the mistake is.
The error in the log cat is :
10-11 12:58:51.817 9285-9285/com.mohana.pdc E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mohana.pdc/com.mohana.pdc.NodeList}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.mohana.pdc.NodeList.onCreate(NodeList.java:83)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
10-11 12:58:52.048 9285-9285/com.mohana.pdc E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mohana.pdc, PID: 9285
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mohana.pdc/com.mohana.pdc.NodeList}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.mohana.pdc.NodeList.onCreate(NodeList.java:83)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Thanks in advance!
Your method getLastLocation() updates your mLastLocation variable asynchronously. You can see that it's async by the fact that you had to use an OnCompleteListener.
What this means is that when you write:
getLastLocation();
double d = mLastLocation.getLatitude();
chances are extremely high that mLastLocation is still null at this point, and so your app will crash with a NullPointerException.
You'll have to move anything that depends on mLastLocation into the callback, or provide some other way of guaranteeing that the callback has executed before you try to use mLastLocation.
you can convert Double to String like this
String latitudeStr=String.valueOf(mLastLocation.getLatitude());
what im trying to do right now is trying to grab a location object that is already in my firebase database eg: Artic base and store it in the localeobj i created but for some reason when i run the program it keeps saying localeobj is null am i doing my listener correctly?
package com.example.spy;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Random;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class GameJoin extends AppCompatActivity implements View.OnClickListener {
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseUser user;
private TextView location;
private TextView role;
private TextView desc;
private Button back;
private Intent extra;
private Bundle data;
private String spy;
private Location localeObj;
private String game_code;
private Random rand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
rand = new Random();
//Firebase stuff
user = FirebaseAuth.getInstance().getCurrentUser();
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
//Views
role = (TextView) findViewById(R.id.label_role);
location = (TextView) findViewById(R.id.label_location);
desc = (TextView) findViewById(R.id.descriptionText);
//Buttons
back = (Button) findViewById(R.id.button3);
//Attach a listener to the button
findViewById(R.id.button3).setOnClickListener(this);
//Retrieve data from previous activity
extra = getIntent();
data = extra.getBundleExtra("game_data");
game_code = data.getString("game_code");
//TODO: Pull location object from Firebase
myRef.child("lobby").child(game_code).child("location").addValueEventListener( new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
System.out.println("************************IN CANCELLED*************************************");
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("************************OUTSIDE IF*************************************");
for (DataSnapshot data : dataSnapshot.getChildren()) {
localeObj = dataSnapshot.getValue(Location.class);
System.out.println("************************IN IF*************************************");
}
}
});
myRef.child("lobby").child(game_code).child("spy").addValueEventListener( new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
spy = (String) dataSnapshot.getValue(String.class);
}
}
});
//Display a special UI if the user is a spy
if (user.getEmail().equals(spy)) {
role.setText("You are the spy. Don't get caught!");
location.setText("Mystery Location");
desc.setText("Welcome to Spy Fall. Keep your identity hidden for the length of the game, or figure out what the location is to win the game.");
} else {
role.setText(localeObj.getRole(rand.nextInt(3)));
location.setText(localeObj.getLocationName());
desc.setText("Welcome to Spy Fall. Infer who is the spy before time runs out in order to win the game.");
}
}
#Override
public void onClick(View v) {
//Stuff happens when buttons are clicked
int id = v.getId();
if (id == R.id.button3) {
//Clean up old game lobby information
myRef = database.getReference("lobby");
myRef.child(game_code).child("players").child(user.getUid()).removeValue(); //Remove all data associated with the current game
//Return to the main lobby
Intent main_lobby = new Intent(GameJoin.this, MainActivity.class);
startActivity(main_lobby);
}
}
}
Here is the tomcat message i get too
--------- beginning of crash
05-09 11:01:42.718 3083-3083/com.example.spy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.spy, PID: 3083
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.spy/com.example.spy.GameJoin}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.spy.Location.getRole(java.lang.Integer)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
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.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.spy.Location.getRole(java.lang.Integer)' on a null object reference
at com.example.spy.GameJoin.onCreate(GameJoin.java:112)
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.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
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)
https://gyazo.com/2b0c1ee92f365f06b1737c99793c96b3
ive posted how my database structure looks like too
If you want to get the locationName please use the following code:
myRef.child("lobby").child(game_code).child("location").addValueEventListener( new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
System.out.println("************************IN CANCELLED*************************************");
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("************************OUTSIDE IF*************************************");
String locationName = (String) dataSnapshot.child("locationName").getValue();
}
})
Hope it helps.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
enter image description hereWhen I open my Android application it crashes. Here is the code:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button requestButton;
private TextView coordinateText;
private LocationManager locationManager;
private LocationListener locationListener;
private Button buttonMap;
private Button buttonCurrentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//reference requestButton
requestButton = (Button) findViewById(R.id.requestButton);
//reference coordText
coordinateText = (TextView) findViewById(R.id.coordinateText);
// Creating button object for buttonMap
buttonMap = (Button) findViewById(R.id.buttonMap);
//Create a button object for buttonCurrentLocation
buttonCurrentLocation = (Button) findViewById(R.id.buttonCurrentLocation);
//Action listener for buttonMap
buttonMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent1);
}
});
// Action listener for buttonCurrentLocation
buttonCurrentLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), GPSShow.class);
startActivity(i);
}
});
//Initialize locationManager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Initialize locationListener
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
coordinateText.append("\n" + location.getLatitude() + " " + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent2 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent2);
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET
}, 10);
}
return;
} else {
configureButton();
}
}
//OUTSIDE ONCREATE METHOD
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
configureButton();
return;
}
}
private void configureButton() {
requestButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
});
}
}
Here is the logcat:
01-15 17:10:18.088 2340-2340/com.example.matt.palt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.matt.palt, PID: 2340
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matt.palt/com.example.matt.palt.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.matt.palt.MainActivity.configureButton(MainActivity.java:124)
at com.example.matt.palt.MainActivity.onCreate(MainActivity.java:103)
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)
01-15 17:10:20.435 2340-2340/com.example.matt.palt I/Process: Sending signal. PID: 2340 SIG: 9
The first time I ran the application it was running fine.
It seems that the problem is the requestButton. I have tried looking further for a solution but can't find one.
Main XML file and other XML file
R.id.buttonMap is not found, resulting in null from findViewById(R.id.buttonMap).
The id buttonMap should be in your activity_main xml file. It is not.
From logcat its clear that the button requestButton is null. Seems your java code is right and the problem is in your layout. The id requestButton is not exactly the same in your xml file. Do match your xml with java code