android.content.res.Resources$NotFoundException for string onStart() - android

Problem
I've seen this question posted before, but the answers did not solve my problem, so I'm guessing it may be a different problem.
My code works well when I run it, but if I leave the activity on for a while and come back to it later - it crashes.
The activity contains a fragment, which itself contains a fragment. The crash occurs inside onViewCreated() on getContext().getString(R.string.vote_for)
Code
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView description = rootView.findViewById(R.id.votes_chart_desc);
description.setText(getArguments().getString("voteItemDesc"));
int votesForNum = getArguments().getInt("voteFor");
int voteAgainstNum = getArguments().getInt("voteAgainst");
int voteAbstainNum = getArguments().getInt("voteAbstain");
PieChart chart = rootView.findViewById(R.id.votes_chart);
ArrayList<PieEntry> entries = new ArrayList<>();
# CRASH happens here, inside the if, when evaluating getString().
if (votesForNum > 0) entries.add(new PieEntry(votesForNum, getContext().getString(R.string.vote_for)));
if (voteAgainstNum > 0) entries.add(new PieEntry(voteAgainstNum, getContext().getString(R.string.vote_against)));
if (voteAbstainNum > 0) entries.add(new PieEntry(voteAbstainNum, getContext().getString(R.string.vote_abstain)));
PieDataSet set = new PieDataSet(entries, "");
set.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(set);
chart.setData(data);
chart.invalidate();
}
Stacktrace
FATAL EXCEPTION: main
Process: [myprocess], PID: 11262
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: android.content.res.Resources$NotFoundException: String resource ID #0x7f0e003b
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2729)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2790)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1505)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:173)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f0e003b
at android.content.res.Resources.getText(Resources.java:352)
at android.content.res.Resources.getString(Resources.java:398)
at android.content.Context.getString(Context.java:476)
at [myprocess].Votes.VoteFragment.onViewCreated(VoteFragment.java:65)
...
Things I've tried / questions I've searched
This question seemed similar (resource exists, but error) - Cleaning the project did not help
This is not similar, but similar exception - getString() receives and ID as it should, and the program works until I change to a different app.
Not similar to my issue, OP had their layout removed somehow. My layout exists, and works until you switch apps.
Duplicate of 2, irrelevant.
Duplicate of 2, irrelevant.
Changing the crashing line to rootView.getResources().getString(R.string.vote_for)
Changing the crashing line to getString(R.string.vote_for)
Changing the crashing line to getParentFragment().getActivity().getString(R.string.vote_for)
Debugger info
I put a breakpoint on the problematic line, but the debugger disconnects after I switch between 9 apps, so I cannot come back to the crashing line after switching between apps. If my understanding of the activity lifecycle is correct, the crash happens only onStop(), onResume() resumes as normal.
I've tried resolving this issue on my own, but I failed. I'm out of ideas. Has anyone else encountered something similar? Thank you.

The problem stemmed from the fact that I had several string.xml files, and for some reason the locale changed after the onRestart() function. So as a result, onViewCreated() was referencing a different xml file than I was expecting. The solution was to just change locale in the onResume() function of the parent activity.
It's also good practice to keep the strings.xml files synced and not miss any values. Had I seen the strings in English, I would have been able to identify the problem much quicker.

Related

I can't see my logs in Android Studio logcat

Here's a simple app, I'm trying to create logs in the printToLogs method.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("Log0","test");
}
public void printToLogs(View view){
TextView menuTextView1 = findViewById(R.id.menu_item_1);
TextView menuTextView2 = findViewById(R.id.menu_item_2);
TextView menuTextView3 = findViewById(R.id.menu_item_3);
String item1 = (String) menuTextView1.getText();
String item2 = (String) menuTextView2.getText();
String item3 = (String) menuTextView3.getText();
Log.v("Log1",item1);
Log.v("Log2",item2);
Log.v("Log3",item3);
}
but logs with the tags Log1, Log2, Log3 are not shown at all in the logcat, what does show up is the Log0 in the onCreate method, but the other ones in printToLogs never show up when I search for them at all. I attempted re-installing the app and restarting logging. That didn't work.
The menu items are: Mango sorbet, Blueberry pie, Chocolate lava cake. And yes, I tried searching for them, and they are not in the logcat either.
If this is your actual code, you aren't even calling printToLogs in the onCreate method. You should be more diligent before posting something simple like this.
Barring a serious runtime environment issue, this problem should be fairly easy to solve.
It seems as if the printToLogs(View view) method is to be executed in response to the user clicking a button. If so, try including the following line in your activity_main.xml if you haven't already:
android:onClick="printToLogs"
This will bind the button on the UI with the printToLogs(View view) method.
If, on the other hand, printToLogs(View view) is intended to be a standalone method (i.e. one that should execute regardless of user input) it should not accept a View as an argument. For your purposes, its parameter list should be completely empty. In other words, the method signature should read:
public void printToLogs()
Also, it should be called within the onCreate(Bundle savedInstances) method. Add the following to the onCreate(Bundle savedInstances) method:
printToLogs();
This will initiate the execution of the method as soon as the app begins to run.
Make sure the logcat filter is set to "Verbose" when testing like so: (img is link since apparently I need 10 rep. to embed images into answers directly)
logcat filter
heyy add your method/function name in your button by using property section or just android:onClick in your xml file and then it will be solved

Issue with Android fragments: getView() returns null

Our app has several fragments. In one of them user fills several TextEdit fields. When he finishes he presses a button in the ActionBar to save the data. The Action just calls a private method named "saveData" that fetches all data from the fields and submit it to our server.
We have many stack traces from our users showing that getView() returns null in method saveData, but for just a small part of them. For most of them there is no problem at all. We cant reproduce the problem and we cant understand what might be causing it. The code is pretty simple:
View vw = this.getView();
EditText et;
et = (EditText)vw.findViewById(R.id.editEmail);
String email = et.getText().toString().trim();
et = (EditText)vw.findViewById(R.id.editPassword);
String password = et.getText().toString().trim();
The action is added in osResume, see below:
public void onResume() {
super.onResume();
MainActivity act = (MainActivity)this.getActivity();
act.bar.removeAllActions();
act.bar.addAction(new SaveAction());
}
Any ideas? How can we reproduce it?
Can you tell from your logs whether the problem is always for the same users / devices ?
I see from the code that you have submitted that the view is in the same fragment - is that actually the case ?
It's POSSIBLE that a fragment no longer in view can have their view destroyed in order to free up resources. e.g.
getView() returns null
If I suspected that this might be the case then I would attempt to recreate the problem on a phone / tablet / emulator with limited resources.
Good luck !

Setting an imageview src through an activity

I keep trying to set an imageview through my main activity and it keeps returning a null pointer exception in LogCat. My code is fairly self explanatory.
I'm pulling data from a JSON url and pulling data out of objects.
for (int i=0; i<forecastday_arr.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = forecastday_arr.getJSONObject(i);
JSONObject date_obj = e.getJSONObject("date");
String curDate = date_obj.getString("weekday");
String conditions = e.getString("conditions");
String icon_to_use = e.getString("icon");
map.put("weekday", curDate);
map.put("conditions", conditions);
map.put("icon", icon_to_use);
if (icon_to_use=="rain") {
ImageView imgView = (ImageView) findViewById(R.id.imageViewDayOne);
imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.rain));
}
mylist.add(map);
}
From my code I'm checking to see if the value in "icon" is equal to rain, which it is (today), and if so, return the rain icon that's stored in my drawable folder. Even without the if statement I get the same null pointer exception. I'm quite new to Android so debugging isn't the easiest thing right now.
I presume I'm setting the image correctly. I've attached a picture of my LogCat below.
Sorry to be so vague but I thought it would be really simple to set an image. I'm sorry if I've missed anything as well - if I have I will quickly correct.
Pastebin of my MainActivity.java: http://pastebin.com/uNfYDGAw and a pastebin of my activity_main.xml: http://pastebin.com/M1xy1buB
So it appears your NullPointerException is coming from this line:
imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.rain));
I suspect that either this.getResources() or more likely BitmapFactory.decodeResource is returning null.
Luckily for you, there is an easier way to set an image on an ImageView. You can use setImageResource to set the drawable resource at runtime, like this:
imgView.setImageResource(R.drawable.rain);
--EDIT--
You also need to make sure you call setContentView with the layout that contains the ImageView you are attempting to use in onCreate of you MainActivity, before trying to reference any Views using findViewById.
setContentView(R.layout.layoutContainingImageViewDayOne);
Lastly, if you are attempting to do any network requests, they should be done in a background thread (off the UI thread) or the application with get an "Application Not Responding" crash. AsyncTasks are useful for this (however there are other methods). See http://developer.android.com/training/basics/network-ops/connecting.html for more info.
--EDIT 2--
So now that you posted all of the code, I see there are some major flaws here. Your R.layout.activity_main should actually be renamed to R.layout.list_row since it contains your row elements. Right now you are trying to use the same layout (R.layout.activity_main) for your Activity and its ListAdapter, which is impossible. R.layout.activity_main needs to have a ListView in it, that you attach your ListAdapter to. You are also trying to set your ImageView in your Activity code for your list rows, which the ListAdapter will already do for you.
So I'm going to suggest you take a look at some examples and refactor your app, Vogella has some great tutorials - http://www.vogella.com/articles/AndroidListView/article.html.
First use equals method to compare the Strings. Instead of ==
if (icon_to_use != null && icon_to_use.equals("rain")) {
....
}
Cause of NullPointerException
It might be because of you did not call setContentView to the layout or did not set right layout. means imageViewDayOne is not define in that layout.

NullPointerException in my aboutButton I think

My second book for Android programming Hello, Android by Ed Burnette. I'm using eclipse. The code matches the book and it matches the code downloaded from the website of the book. But I know I'm doing something wrong here. I added a bunch of breakpoints where I figure (mostly guessing) where the problem might be happening. What I've come to is that this line of code is the culprit (SudokuActivity.java line 21) You can download the entire code here
http://kbsoftware.dlinkddns.com/Sudoku.zip
aboutButton.setOnClickListener(this);
but I just can't figure out why ? It must be the result of something I'm doing wrong somewhere else. I've deleted and recreated the avd and that made no difference so not it. I'm at a lost here.
public class SudokuActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
}
I want to thank everyone who responded, it's all fixed and working and I could not have done it without your help. I've learned more working on this problem then I would of in weeks if not months of problem free programming.
Yout aboutButton is not getting bound properly.
Do something like
Button aboutButton = (Button) findViewById(R.id.about_button);
I downloaded your code and it runs correctly on my phone. So if your code is the same it should run.
It seems that findViewById didn't find the view and then calling a method on a null object caused the nullpointerexception.
My dumb question: have you tried a project clean up? You can even try saving your classes, deleting the project and creating a new one.
Hope it helps

"Force Close" Error on declaring TextView and ToggleButton

Well basicly I have a textview and when the application is created it sets a string as the textviews text not hard, but I get a force close error when I run the app on my phone.
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
Then I have a error on a togglebutton also
ToggleButton silent=(ToggleButton)findViewById(R.id.silentbutton);
silent.setChecked(false);
And I have errors for all my other buttons/textviews can anyone help, please?!
EDIT:
I cant post pics because I am a new member, :(
Link to imgshack http://imageshack.us/photo/my-images/849/unledggp.png/
If code for the whole textview snippet.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_UNMOUNTED)) {
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
}
OnCreate Function
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkSD();
checkRing();
checkWifi();
checkBt();
}
Look for all instances of sd_textview and make sure the one that you're trying to reference is a TextView. If you want more clarity you can debug your code and see what object is actually being returned by not casting into a TextView:
View sdcard = findViewById(R.id.sd_textview); //debug this
//you can also log the View object to see the type
Log.d("Test", "" + sdcard);
Looking at your error log (assuming its the right error log) you have a ClassCastException in the checkWifi method. Edit your question and include ALL of the onCreate method and all of the checkWifi method, but I expect you are using the same id for multiple views.
Two things I can think of (although seeing more code would help).
Make sure you have called setContentView(R.layout.main) (or whatever your layout file is called). Do this BEFORE any attempt to use findViewById(...).
Secondly sdcard.setText(R.string.not_mounted); in this statement R.string.not_mounted is a resource ID (int) and not a string. You would need to use...
sdcard.setText(getString(R.string.not_mounted));

Categories

Resources