nullpointerexception in getResource method - java

When I click back button in my app, I get a NullPointerException in getResource() method. getResource is used in the url and is called in the glideApp.
my code
private void setupPostUserImage(ImageView image, PostDetail detail) {
mUserPicture.setVisibility(View.VISIBLE);
String url = getActivity().getResources().getString(R.string.profile_image_path1) + "/" + detail.getUser_id_fk() + "/thumb/" + detail.getProfile_picture();
//Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();
GlideApp.with(image.getContext())
.load(url)
.placeholder(R.drawable.ic_avtar_male)
.into(image);
}
This is my crash report from logcat
Process: com.ATG.World, PID: 24491
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.support.v4.app.FragmentActivity.getResources()' on a null object reference
at com.ATG.World.fragments.ArticleDetailFragment2.setupPostUserImage(ArticleDetailFragment2.java:316)
at com.ATG.World.fragments.ArticleDetailFragment2.setData(ArticleDetailFragment2.java:301)
at com.ATG.World.fragments.ArticleDetailFragment2$1.onResponse(ArticleDetailFragment2.java:176)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
at android.os.Handler.handleCallback(Handler.java:898)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6716)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
12-21 19:38:17.829 24491-24491/com.ATG.World I/Process: Sending signal. PID: 24491 SIG: 9
what should I do in order to resolve this exception?

I don't have reputation to comment so I have to write answer. It looks like your fragment is not attached to activity so method getActivity() returns null. Look this answer may be it will be useful getActivity() returns null in Fragment function

Related

Firebase Firestore gives null pointer exception for a key which exists

I am making a chat app and want to implement a feature to get the online-offline and typing statuses for that in my adapter. I am trying to get the value from the database to display.
This is what I tried
FirebaseFirestore database = FirebaseFirestore.getInstance();
Log.d("conversationId",chatMessage.conversationId + "");
database.collection(Constants.KEY_COLLECTION_USERS)
.document(chatMessage.conversationId + "")
.addSnapshotListener((value, error) -> {
if (value.getString(Constants.KEY_AVAILABILITY).equals("0")){
binding.onlineIndicator.setVisibility(View.GONE);
binding.textRecentConversation.setText(chatMessage.message);
}else if (value.getString(Constants.KEY_AVAILABILITY).equals("1")){
binding.onlineIndicator.setVisibility(View.VISIBLE);
binding.textRecentConversation.setText(chatMessage.message);
}else if (value.getString(Constants.KEY_AVAILABILITY).equals("2")){
makeTypingText(binding, chatMessage.conversationName);
binding.onlineIndicator.setVisibility(View.VISIBLE);
}
});
And this is the error I got
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.chatverse.free, PID: 14452
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.chatverse.free.Adapters.RecentConversationsAdapter$ConversationViewHolder.lambda$setData$0$com-chatverse-free-Adapters-RecentConversationsAdapter$ConversationViewHolder(RecentConversationsAdapter.java:144)
at com.chatverse.free.Adapters.RecentConversationsAdapter$ConversationViewHolder$$ExternalSyntheticLambda3.onEvent(Unknown Source:6)
at com.google.firebase.firestore.DocumentReference.lambda$addSnapshotListenerInternal$2$com-google-firebase-firestore-DocumentReference(DocumentReference.java:504)
at com.google.firebase.firestore.DocumentReference$$ExternalSyntheticLambda2.onEvent(Unknown Source:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0$com-google-firebase-firestore-core-AsyncEventListener(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$ExternalSyntheticLambda0.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
This is how I verified
First, in the logs, I check the value I printed for the receiver id. It's correct.
I also verified the keys, and everything is correct. I am not sure why such an error is occurring.
I got it.
I was using a static String, giving n error, but it worked when I tried using hard-coded values. Note that this gave me an emulator error but worked fine with an actual device! To make it work on an emulator, I had to try/catch for NullPointerExeption.
Thanks to #AlexMamo

at com.future.vpn.Activities.MainActivity.onStart(MainActivity.java:186) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
2021-08-14 19:43:53.129 8682-8682/com.future.vpn E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.future.vpn, PID: 8682
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.future.vpn.Activities.MainActivity.onStart(MainActivity.java:186)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
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)
2021-08-14 19:43:53.186 8682-8682/com.future.vpn I/Process: Sending signal. PID: 8682 SIG: 9
In onstart() Method you have a string that is not initialized and you are comparing it with another string that's why you are getting this error.
first, initialize string then compare with another string
This is a NullPointerException, you are passing a null value. Place break points on the sections that contain variables/values then run it (using the Debug feature on). This will show you:
which value you are getting a null response from. Once achieved, now check:
how your code structure is (global and local scopes). This might be an issue as the scope of the variable assignment determines whether your variable has a value or it doesn't.
Start from there, and it would be best you share the code snippet to make it more elaborate.

How do I "define" two other classes in a class so that I can use their methods

Currently I have already intialized
myDb = new DatabaseHelper(this);
and have no problem using DatabaseHelper's methods in my Main class. But now I'm trying to initialize another class
expenses = new AddExpenses();
and when I try to set the context for that it goes red and when I try to use AddExpenses class' method in my Main class, my app crashes.
The logcat when the app crashes :-
--------- beginning of crash
10-26 00:44:16.144 4105-4105/project.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: project.myapplication, PID: 4105
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor project.myapplication.DatabaseHelper.getLatestAmount(java.lang.String, java.lang.String)' on a null object reference
at project.myapplication.AddExpenses.recalculateAllSpendings(AddExpenses.java:273)
at project.myapplication.SpendingTracker$5.onClick(SpendingTracker.java:188)
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)

Error with calling FileProvider from DialogFragment - null object of reference,

I am trying to fix this error but I am kind of not seeing where it comes from.
From my fragment which creates new user I am calling another fragmentDialog (on ImageButton Click) which enables me to pick a photo from camera or gallery. Gallery works fine, but camera does not. In this line:
Uri photoUri = FileProvider.getUriForFile(globalContext, getActivity().getPackageName() + ".provider", getCameraFile());
I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
All the data is displaying correctly (I check in logs).
Where cna be the issue?
Regards,
Grzegorz
EDIT:
Full stack trace:
FATAL EXCEPTION: main
Process: com.myapp.myapp, PID: 27523
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
at com.myapp.myapp.utils.PictureDialog.onTakePhoto(PictureDialog.java:80)
at com.myapp.myapp.utils.PictureDialog_ViewBinding$1.doClick(PictureDialog_ViewBinding.java:32)
at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
at android.view.View.performClick(View.java:5184)
at android.view.View$PerformClick.run(View.java:20893)
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:5940)
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:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
FileProvider cannot find the <provider> element in the manifest that has an android:authorities value equal to getActivity().getPackageName() + ".provider". Specifically, this code results in a null value for info:
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
(where context is the first parameter to getUriForFile() and authority is the second parameter to getUriForFile())
Make sure that your supplied authority string matches your <provider> element.

Android Studio Weather Application Crashing

So, I have been following a YouTube tutorial for an android Weather application. The app seems to compile, however crashes whenever opened on the emulator. I'm not the most fluent programmer, however the code is understood. I can't figure out what's causing the issue though. The app is supposed to fetch weather data for the location of the hardcoded location in "MainActivity.java". The data is fetched from Yahoo! using an API.
Link for the project files: https://drive.google.com/drive/folders/0B2dQ9-JQjysVeXlqZENBZDExN0E?usp=sharing
Below is the error I get:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mattbenson.cw_2_weather, PID: 2529
java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.optInt(java.lang.String)' on a null object reference
at com.example.mattbenson.cw_2_weather.service.WeatherService$1.onPostExecute(WeatherService.java:81)
at com.example.mattbenson.cw_2_weather.service.WeatherService$1.onPostExecute(WeatherService.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:667)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
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)
E/Surface: queueBuffer: error queuing buffer to SurfaceTexture, -19
E/EGL_emulation: tid 2570: swapBuffers(487): error 0x300d (EGL_BAD_SURFACE)
W/OpenGLRenderer: swapBuffers encountered EGL error 12301 on 0x76990bb1c580, halting rendering...
Application terminated.
(Sorry, I am new to this site!)
Any help is greatly appreciated.
As StackTrace says the error is at Class WeatherService at line 81 int count = queryResults.optInt("Count"); because it is returning NULL.
Try using method optInt with fallback value queryResults.optInt("Count", 0);

Categories