Start Activity with parameters from FirebaseRecyclerAdapter - android

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);

Related

unable to run app on android emulator, App keeps stopping

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);

app crashes in landscape mode?

I have a problem with my application. It crashes each time whenever I
launch my app on an Emulator and I switch to landscape mode. But it work
fine in portrait mode. Please what can i do to solve this. Thanks in
advance!
I put "android:configChanges="orientation|screenSize|keyboardHidden" in the
activity declaration in my manifest but still crash.
This is the error:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a1697759.projetintra/com.example.a1697759.projetintra.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
This is my java code:
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import static com.example.a1697759.projetintra.R.id.etTotalPrix;
public class MainActivity extends AppCompatActivity {
Button btnInscription;
EditText etQuantite;
Spinner spinner;
Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInscription = (Button) findViewById(R.id.btnInscription);
etQuantite = (EditText) findViewById(R.id.etQuantite);
EditText etTotalPrix;
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
// Use a TextWatcher to disable/enable button
etQuantite.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int
arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {}
#Override
public void afterTextChanged(Editable string) {
if(string.length() > 0) {
btnInscription.setEnabled(true);
} else {
btnInscription.setEnabled(false);
}
}
});
btnInscription.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//Demarrer le nouvelle activite
Intent intent = new Intent(MainActivity.this,
ResumeActivity.class);
//Spinner 1
Bundle b = new Bundle();
b.putString("name", spinner.getSelectedItem().toString());
intent.putExtras(b);
//Spinner 2
Bundle b2 = new Bundle();
b2.putString("name2", spinner2.getSelectedItem().toString());
intent.putExtras(b2);
//EditText Quantite
Bundle q = new Bundle();
q.putString("name3", etQuantite.getText().toString());
intent.putExtras(q);
//Reset spinner and editText
spinner.setSelection(0);
spinner2.setSelection(0);
etQuantite.setText("");
Toast.makeText(MainActivity.this, "Vous avez fait votre
commande",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a1697759.projetintra, PID: 21317
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a1697759.projetintra/com.example.a1697759.projetintra.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:2947)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4974)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
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.a1697759.projetintra.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4974) 
at android.app.ActivityThread.-wrap21(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6688) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358) 
You have to create a landscape layout for that.
Just go to the design tab in your xml file
click on the Layout Variants button.
Select the Create Landscape Variation
a landscape layout will be created. Then you are free to change the layout according to your requirements.

can't store latitude or longitude in string from location object

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());

AsyncTaskLoader not initialized after screen rotation

I am using recyclerview which is getting its data from adapter which gets data trough AsyncTaskLoader. Everything runs fine until I rotate the screen from portrait to landscape. At that point I get nullpointer exception when using .forceLoad(); on my asyncTaskLoader
I have absolutelly no idea why is the fileLoader null when the same onCreate method is called regardless of orientation and it works on portrait and doesnt on landscape.
Here is the code:
package sk.tomus.filescoper;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
mport java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<File>> {
private android.support.v4.content.AsyncTaskLoader<List<File>> fileLoader;
private DirectoryManager directoryManager;
private RecyclerView recyclerView;
private FileRecyclerAdapter recyclerAdapter;
private RecyclerView.LayoutManager layoutManager;
private boolean isLandscape;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
directoryManager = new DirectoryManager(prefs.getString("PREFERENCE_EDIT_DEF_FOLDER", "/"));
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
isLandscape = getResources().getBoolean(R.bool.isLandscape);
if (isLandscape) {
layoutManager = new GridLayoutManager(this, 4);
} else {
layoutManager = new LinearLayoutManager(this);
}
recyclerView.setLayoutManager(layoutManager);
recyclerAdapter = new FileRecyclerAdapter(new ArrayList<File>());
getSupportLoaderManager().initLoader(0, null, this);
//below is line 51 where the code crashes
fileLoader.forceLoad();
recyclerView.setAdapter(recyclerAdapter);
}
#Override
protected void onResume() {
super.onResume();
recyclerAdapter.setOnItemClickListener(new FileRecyclerAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i("LOG", " Clicked on Item " + position);
}
});
}
private void onFileClicked(File file) {
if (file.isDirectory()) {
Log.i("opening directory", file.getAbsolutePath());
if (!file.canRead()) {
Toast.makeText(getApplicationContext(), "inaccessible", Toast.LENGTH_SHORT).show();
return;
}
directoryManager.setPreviousDir(directoryManager.getCurrentDir());
directoryManager.setCurrentDir(file);
if (fileLoader.isStarted()) {
fileLoader.onContentChanged();
}
} else {
openFile(Uri.fromFile(file));
}
}
private void openFile(Uri fileUri) {
String mimeType = directoryManager.getMimeType(fileUri);
if (mimeType != null) {
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(fileUri, mimeType);
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "file type recognized, but no apps to open it", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "unknown file type", Toast.LENGTH_LONG).show();
}
}
#Override
public Loader<List<File>> onCreateLoader(int i, Bundle bundle) {
fileLoader = new android.support.v4.content.AsyncTaskLoader<List<File>>(this) {
#Override
public List<File> loadInBackground() {
Log.i("loader loading:", directoryManager.getCurrentDir().toString());
return directoryManager.getAllFiles(directoryManager.getCurrentDir());
}
};
return fileLoader;
}
#Override
public void onLoadFinished(Loader<List<File>> loader, List<File> data) {
recyclerAdapter.setFiles(data);
}
#Override
public void onLoaderReset(Loader<List<File>> loader) {
}
}
here is the stacktrace:
08-29 00:50:21.176 16411-16411/sk.tomus.filescoper E/AndroidRuntime: FATAL EXCEPTION: main
Process: sk.tomus.filescoper, PID: 16411
java.lang.RuntimeException: Unable to start activity ComponentInfo{sk.tomus.filescoper/sk.tomus.filescoper.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.content.AsyncTaskLoader.forceLoad()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
at android.app.ActivityThread.access$900(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.content.AsyncTaskLoader.forceLoad()' on a null object reference
at sk.tomus.filescoper.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053) 
at android.app.ActivityThread.access$900(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:211) 
at android.app.ActivityThread.main(ActivityThread.java:5389) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815) 
thanks in advance for any help
You shouldn't be calling forceLoad() in your onCreate() method at all - it won't be created until onCreateLoader() is called (which is after onCreate() finishes).
As per the Making Loading Data Lifecycle Aware blog post, you should instead be calling forceLoad() in your AsyncTaskLoader's onStartLoading method. This ensures that your Loader is created and ready to start loading before you call forceLoad().
fileLoader = new android.support.v4.content.AsyncTaskLoader<List<File>>(this) {
#Override
public void onStartLoading() {
forceLoad();
}
#Override
public List<File> loadInBackground() {
Log.i("loader loading:", directoryManager.getCurrentDir().toString());
return directoryManager.getAllFiles(directoryManager.getCurrentDir());
}
};

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener [duplicate]

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

Categories

Resources