This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here's code of Splash Screen (it's not my desire, but client) - the only thing I've done - just to replace sone code with loading data to this activity:
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
GetAll getAllProducts = retrofit.create(GetAll.class);
Call<ArrayList<Products>> call = getAllProducts.getAll(Constants.PARTNER_ID,
WaterFragment.getMD5Hash(Constants.PARTNER_ID + Constants.API_KEY));
call.enqueue(new Callback<ArrayList<Products>>() {
#Override
public void onResponse(Response<ArrayList<Products>> response, Retrofit retrofit) {
if (response.body() != null) {
ActiveAndroid.beginTransaction();
try {
ProductsDMC product;
for (Products p : response.body()) {
if (new Select().from(ProductsDMC.class).where("product_id = ?", p.id).executeSingle() != null) {
product = new Select().from(ProductsDMC.class).where("product_id = ?", p.id).executeSingle();
product.price = p.price;
} else {
product = new ProductsDMC(p.id, p.article, p.title, p.price, p.amount, p.category_id,
p.brand_id, p.description, p.photo[0], p.option != null ? p.option.bottle_price : "0");
}
product.save();
}
ActiveAndroid.setTransactionSuccessful();
} finally {
ActiveAndroid.endTransaction();
}
}else{
Toast.makeText(SplashActivity.this, "Try later!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure (Throwable t){
Toast.makeText(SplashActivity.this, "Check your connection!", Toast.LENGTH_SHORT).show();
Log.d("LoloPolo", t.getMessage().toString());
}
});
Intent intent = new Intent(this, ListOrdersActivity.class);
startActivity(intent);
finish();
}
}
Tonight my crashlytic send info about crash on app:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at ru.luny.aqualuxe.activity.SplashActivity$3.onFailure(SplashActivity.java:142)
at retrofit.ExecutorCallAdapterFactory$ExecutorCallback$2.run(ExecutorCallAdapterFactory.java:94)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Method.java)
It's about this:
Toast.makeText(SplashActivity.this, "Try later!", Toast.LENGTH_SHORT).show();
I really don't understand - how Toast.makeText().show can cause NPE))
Could you help me please?
EDIT
It seems strange but crashlytics shows me wrong place of error code string.
It's not about toast but debug-loggin with getting message from exception.
Problem is t.getMessage().toString()
You are getting NPE in onFailure (Throwable t) section . For testing case add ""+
#Override
public void onFailure (Throwable t){
Toast.makeText(SplashActivity.this, "Check your connection!", Toast.LENGTH_SHORT).show();
Log.d("LoloPolo",""+ t.getMessage().toString());
}
it's highly problem that the NPE is due of Log.d("LoloPolo", t.getMessage().toString());. Not always getMessage() returns a valid object. Printing t should be enough. E.g.
Log.d("LoloPolo", "Error", t);
(have a look here)
also those callback don't run on the UI Thread. I wont use them to show a `Toast.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am trying to build an app with android studio. I am following a tutorial but the thing is, the guy paused the screen to start the emulator and when he played it again a piece of code was missing. I don't know for sure what he did but I tried all of the options presented to me.
I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
code:
public void onResponse(Call<Users> call, Response<Users> response) {
if (response.isSuccessful()) {
mediaObjectList = (ArrayList<MediaObject>) response.body().getAllPosts();
recyclerview.setMediaObjects(mediaObjectList);
VideoPlayerRecyclerAdapter adapter = new VideoPlayerRecyclerAdapter(mediaObjectList, initGlide());
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerview.setKeepScreenOn(true);
recyclerview.smoothScrollToPosition(mediaObjectList.size()+1);
} else {
Toast.makeText(HomeActivity.this, "Network Error.", Toast.LENGTH_SHORT).show();
}
}
I'm getting the error on this line:
recyclerview.smoothScrollToPosition(mediaObjectList.size()+1);
Check if getAllPost() has value or not
Correct Way:
public void onResponse(Call<Users> call, Response<Users> response) {
if (response.isSuccessful()) {
mediaObjectList = (ArrayList<MediaObject>) response . body ().getAllPosts();
if (mediaObjectList != null) {
recyclerview.setMediaObjects(mediaObjectList);
VideoPlayerRecyclerAdapter adapter = new VideoPlayerRecyclerAdapter(mediaObjectList, initGlide());
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerview.setKeepScreenOn(true);
recyclerview.smoothScrollToPosition(mediaObjectList.size() + 1);
} else {
Toast.makeText(HomeActivity.this, "No Post Available.", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(HomeActivity.this, "Network Error.", Toast.LENGTH_SHORT).show();
}
}
I am trying to use Jetpack in my Android development, I am able to display data from the the sports api but some of the data is null and not displaying, I am using data binding and this is was my first instinct check if null during my interview
android:text="#{model.league != null ? model.league : #string/app}"
During my interview however I failed I suppose due to not being able to identify what other location I can check for null data when the I display data. So my question is how do I change this code to ensure no textview is null or how do how I handle null api calls, and where, I just want to be able to not make the same mistake again.
Reponse Class
public LiveData<List<Match>> getEvents(String teamId) {
final MutableLiveData<List<Match>> events = new MutableLiveData<>();
Call<AppResponse> call = RetrofitClient.getEvents(teamId);
call.enqueue(new Callback<AppResponse>() {
#Override
public void onResponse(#NonNull Call<AppResponse> call, #NonNull Response<AppResponse> response) {
if (response.isSuccessful()) {
AppResponse appResponse = response.body();
if (appResponse != null)
events.setValue(appResponse.getEvents());
} else
Log.i(TAG, "Error: " + response.errorBody());
}
#Override
public void onFailure(#NonNull Call<AppResponse> call, #NonNull Throwable t) {
Log.i(TAG, "Error " + t.getMessage());
}
});
return events;
}
I'm trying to implement getLastLocation().addOnSuccessListener as documented here: https://developer.android.com/training/location/retrieve-current#last-known but in my case within a JobService which is periodically ran by the JobScheduler.
Here is the meaningful part of my jobService:
public class PeriodicJob extends JobService {
final String TAG = "BNA.Job";
private FusedLocationProviderClient fusedLocationClient;
#Override
public void onCreate() {
super.onCreate();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
Log.i(TAG, "onCreate");
}
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started..."); // logs every 15mins
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
Log.d(TAG, "got Location: " + location);
Log.d(TAG, "Accuracy:" + location.getAccuracy()+", LON:"
+location.getLongitude() + ", LAT:" + location.getLatitude());
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
(...) // never runs
});
return true;
}
When I run this (it compiles fine), I get: Caused by: java.lang.ClassCastException: (...)PeriodicJob cannot be cast to java.util.concurrent.Executor
I looked at Android app crashes on firebase phone authentication and Can't cast this into Executor in google reCAPTCHA but I still couldnt get it working. Just calling .addOnSuccessListener(new OnSuccessListener<Location>() like the second question's answer suggests, throws no error, but the code is never executed (at least, no log is written).
How can I get the call to onSuccess working?
EDIT: In fact it was working all the time (without the first parameter), I had neglected to detect the case when a null location was returned (which I wasnt expecting). Thanks to Mike M.!
I am trying to insert data using the Retrofit library. The data has been inserted successfully and I am also receiving the response from the API, but my error is that I am not getting the intent Activity (AdminActivity.class) after the Toast. Can anyone help me on this??
private void createUserResponse() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
CreateUserRequest createUserRequest = new CreateUserRequest(editTextUserId.getText().toString().trim(),
editTextPassword.getText().toString().trim(),
editTextUserName.getText().toString().trim(),
editTextProfileImage.getText().toString().trim(), editTextSchoolId.getText().toString().trim(),editTextRole.getText().toString().trim());
Call<CreateUserResponse> createUserResponseCall = apiInterface. createUserCall(createUserRequest);
createUserResponseCall.enqueue(new Callback<CreateUserResponse>() {
#Override
public void onResponse(Call<CreateUserResponse> call, Response<CreateUserResponse> response) {
Log.d("CreateUser" , "onResponse: " + response.body().getMessage());
String status = response.body().getStatus();
if (status.equals("sucess")){
String message = response.body().getMessage();
Toast.makeText(getActivity(),"User Created Successfully" + message,Toast.LENGTH_SHORT).show();
Intent i = new Intent(getActivity(), AdminActivity.class);
startActivity(i);
} else{
String message = response.body().getMessage();
Toast.makeText(getActivity(),"" + message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<CreateUserResponse> call, Throwable t) {
}
});
}
You have a typo within your if-else condition, so your code do not execute the if statement even if you get a successful response.
Fix the following typo and try again:
if (status.equals("success")) // fixed typo on "sucess" word
I have multiple methods to be called when activity is started. I have added those methods in the oncreate method. The problem is when the activity is started some methods are called some or not called. How do i call all the methods when the activity is started.
My code is
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.post("http://localhost/website/getdbrowcount.php",params ,new AsyncHttpResponseHandler()
{
public void onSuccess(String response)
{
try
{
Log.d("home", "success");
JSONObject obj = new JSONObject(response);
Log.d("home", obj.toString());
System.out.println(obj.get("count"));
syncDB();
sync();
subsync();
syncfeature();
syncelec();
syncconnector();
synccontrols();
synckeypad();
syncmech();
syncorder();
syncpower();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onFailure(int statusCode, Throwable error,String content)
{
if(statusCode == 404)
{
update.setText("The update has been cancelled. Please update via Settings to work"
+ " with latest Sonetonix product data");
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
btn1.setEnabled(true);
btn1.setTextColor(Color.parseColor("#FFFFFF"));
}
else if(statusCode == 500)
{
update.setText("The update has been cancelled. Please update via Settings to work"
+ " with latest Sonetonix product data");
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
btn1.setEnabled(true);
btn1.setTextColor(Color.parseColor("#FFFFFF"));
}
else
{
update.setText("The update has been cancelled. Please update via Settings to work"
+ " with latest Sonetonix product data");
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
btn1.setEnabled(true);
btn1.setTextColor(Color.parseColor("#FFFFFF"));
}
Log.d("home", "failure");
}
});
}
In the code when OnSuccess the methods has to be called but only syncDB(),sync() is called and rest are not called . What change should i make in the code to resolve this issue.
Please help
It is because in the sync() method or possibly at the start of the subsync() method your program is throwing an error. Because of the try/catch block, you are allowing the program to continue.
Check the method for an error and fix that.