I keep getting null instead of the expected string. I have passed getSharedPreferences the context of the app and the proper key. I'll upload the XML file. I'm not sure what's going on here though.
java.lang.NullPointerException: println needs a message on line
Log.d("MomentPrefTimeStamp", momentData.getString("caption", null));
Nothing in the preference file shows up, however the keys are correct and the momentData is a valid SharedPreferences object. At least according to the debugger.
This is the XML, below is the code.
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="time_stamp">1529509324</string>
<string name="img_uri">content://com.example.android.fileprovider/my_images/JPEG_20180620_114201_1480896410651074556.jpg</string>
<string name="caption">Captionas</string>
</map>
Why am I not able to get my data with the correct key and context?
-
if (prefsDir.exists() && prefsDir.isDirectory()) {
String[] list = prefsDir.list();
Log.d("PrefList", list.toString());
//Iterate through every file in the directory
for (String title : list) {
Log.d("prefTitle", title);
//Only open files with our MOMENT marker, since there will be other shared_pref files inside folder.
String[] momentID = title.split("_");
Log.d("StringMoment", momentID.toString());
Log.d("StringMoment1", momentID[0]);
if (momentID.length > 1) {
Log.d("StringMoment2", momentID[1]);
if (momentID[1].equals("JPEG.xml")) {
Log.d("momentTitle", title);
SharedPreferences momentData = this.getSharedPreferences(title, this.MODE_PRIVATE);
Log.d("MomentPref", momentData.toString());
Log.d("MomentPrefTimeStamp", momentData.getString("caption", null));
moments.add(momentData);
}
}
}
}
return moments;
If you are getting you're SharedPreferences through string tricks and file directories, be sure to trim the extension name off of the file name. I don't know why it was still giving me a SharedPreference Object instead of a null pointer exception, but that is the problem.
1234242_JPEG.xml needs to be 1234242_JPEG to get a proper SharedPreference file.
Below is the fix.
String name = title.substring(0, title.lastIndexOf('.'));
Log.d("MomentName", name);
SharedPreferences momentData = this.getSharedPreferences(name, this.MODE_PRIVATE);
Related
I am working on an app for Android and can't figure out the error or mistake which I am making. I am searching for the error for more than 4 hours.
I am getting the following Exception working with SharedPreferences:
E/AndroidRuntime: FATAL EXCEPTION: main
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:235)
at de.immozukunft.quicksteuer.QuickSteuerActivity.updateTextView(QuickSteuerActivity.java:56)
at de.immozukunft.quicksteuer.QuickSteuerActivity.onCreate(QuickSteuerActivity.java:36)
But I am not doing a cast in that line according to my understanding. Line 36 is the call of the method updateTextView().
private void updateTextView() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int legalForm = Integer.parseInt(prefs.getString("legal_form", "1"));
boolean industrialTax = prefs.getBoolean("industrial_tax", false);
boolean turnoverTax = prefs.getBoolean("turnover_tax", false);
boolean disbursal = prefs.getBoolean("disbursal", false);
String tmp = prefs.getString("capitalownership", "0"); //this is line 56
int capitalOwnership = Integer.parseInt(tmp);
int estIncome = Integer.parseInt(prefs.getString("est_income", "0"));
}
My preference in the XML-File is the following:
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="#string/capitalownership"
android:inputType="number"
android:key="capitalownership"
android:title="#string/capitalownership" />
I needed I will post the full code and full Error list.
I am relatively new to Android.
Solution
private void updateTextView() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String legalForm = prefs.getString("legal_form", "1");
boolean industrialTax = prefs.getBoolean("industrial_tax", false);
boolean turnoverTax = prefs.getBoolean("turnover_tax", false);
boolean disbursal = prefs.getBoolean("disbursal", false);
String capitalOwnership = prefs.getString("capitalownership", "0");
String estIncome = prefs.getString("est_income", "1");
settingstv.setText(getString(R.string.overview_settings,
legalForm,
Boolean.toString(industrialTax),
Boolean.toString(turnoverTax),
Boolean.toString(disbursal),
capitalOwnership,
estIncome));
try {
if (!compareCurrentWithStoredVersionCode(this, prefs, "storedVersionCode")) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("legal_form", legalForm);
editor.putBoolean("industrial_tax", industrialTax);
editor.putBoolean("turnover_tax", turnoverTax);
editor.putBoolean("disbursal", disbursal);
editor.putString("capitalownership", capitalOwnership);
editor.putString("est_income", estIncome);
editor.commit();
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "updateTextView()", e);
}
}
The first time you've saved capitalownership you probably didn't save it as a String, so when you try to retrieve it, it will retrieve an Integer but you try to cast to String when you do getString and it will get the exception.
String tmp = prefs.getString("capitalownership", "0");
try like this:
int tmp = prefs.getInt("capitalownership", 0);
Besides, you've already set your edit text to input only numbers, so you won't get a String here.
Edit:
Shared Preferences are stored as a Map<String, Object>. As you can see the value of the map is a general Object, if you saved as an Integer you'll need to retrieve as an integer. Ths is quite dynamic, so if you saved one time as an integer and the next time as a String (to the same key) you need to keep track of the type you've saved so you can retrieve it.
If you've saved once as Integer and later save again (in the same key) as a String, when you retrieve it you'll need to use getString(). If you're not sure what's in there you can use the getAll() method to retrieve the entire preferences as a Map<String, Object>, then you can use get("capitalownership") in this map and finally check with instanceof to see what type it is. But this is too cumbersome, you need only to estabilish that you'll save that key(capitalownership) with a certain type and make sure you do that always.
So this is what's happening:
1)You try to retrieve the value associated with that key and Android gives you an Object,
2) Android then tries to cast to the value associated with the method (a String in your case). As the value is actually an Integer that's where the class cast problem comes from.
https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String) :
Returns the preference value if it exists, or defValue. Throws
ClassCastException if there is a preference with this name that is not
a String.
So I'm guessing you have a "capitalownership" preference that has been stored as an Integer
You should not use
int capitalOwnership = Integer.parseInt(tmp);
because you are trying to get an integer as a string
<EditTextPreference
android:defaultValue="0"
android:dialogTitle="#string/capitalownership"
**android:inputType="number"**
android:key="capitalownership"
android:title="#string/capitalownership" />
instead use this
int capitalOwnership = pref.getInt("capitalownership", 0);
also you need to save it like this
pref.putInt("key",value);
I'm trying to find my folder or view in my database. Which named Team Documents this folder has some filter option like By Date, By Category. But this returns me a null even the folder already exists.
String dbServer = "d23dbm95/23/A/IBM", dbFileName = "dbom\\farizan\\stsklb1.nsf";
public void runNotes()
{
Session session = null;
Database db = null;
View view = null;
Document doc = null;
try
{
NotesThread.sinitThread();
session = NotesFactory.createSession();
System.out.println("User = " + session.getUserName());
db = session.getDatabase(dbServer, dbFileName);
if(db.isOpen())
{
System.out.println("Title "+db.getTitle());
view = db.getView("Team Documents \\ By Date");
if(view == null)
{
System.out.println("still null");
}
}
}
catch(NotesException e)
{
e.printStackTrace();
}
}
I tried also to fill my getView() method like Team Documents. But still returns a null. Any approach to this problem?
While it would have been more helpful if you had included a link to a screenshot of your Domino Designer client's folder list, my best guess is that you have two folders, not one folder with "filter options". Also, my guess is that "Team Documents" is not actually a folder; it's just a prefix on the folder names that makes them appear to be nested in a parent folder.
If that's the case, you would need
iew = db.getView("Team Documents\\By Category");
Or
iew = db.getView("Team Documents\\By Date");
Note: No spaces before & after the backslashes.
If my assumptions above are not correct, then my suggestion would be to assign alias names to the folders in Domino Designer and use the aliases instead of the display names in your code. Frankly, that's always a good practice, because it allows your code to continue working even if you decide to change the display names.
I'm currently facing a string encoding problem.
ListItemType liste = new ListItemType();
String toBChecked=(String)table.getValueAt(row,0);
System.out.print(toBChecked);
toBChecked = "Angelic";
for(String s : liste.sets){
if(toBChecked.contains(s)){
setBackground(Color.GREEN);
}
}
When I copy/paste the string "Angelic" from logs and put it in toBChecked it doesn't work, but when I type it in my code it does work.
Of course, when I directly check table's value (which has the "Angelic" word in its string) it doesn't work.
Table's content is parsed from a file encoded in UTF-16-LE, is it the problem?
How can I fix it?
I am doing JSON parsing in Android by the following steps:
Get an XML response from a web-service using HttpPost object.
Convert this XML to JSON string then JSON object.
Now the problem is that sometimes the XML response has null string or Null tag.
For Example:
<data>
<name>Martin Clark</name>
<city>London</city>
<country>XYZ</country> or <country /> <!-- Sometimes it will blank string like this if country is not available -->
<age>27</age>
</data>
Parsing style:
jsonObject.getString("country"); // It is working perfect when xml is this : <country>XYZ<country/>
jsonObject.getString("country"); // It is giving Exception key is not found when xml is this : <country />
i don't understand why the parser is not giving me BLANK string for blank XML object.
By deep level debugging i have found that XML to JSON converter not produce object corresponding to blank xml object.
Please help me.
Use optString instead, catching the Exception is costly and unnecessary.
public String optString (String name)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns the empty string if no such mapping
exists.
public String optString (String name, String fallback)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary. Returns fallback if no such mapping exists.
Documentation
You can use ths logical solution for your problem.
Try this once.
public static String getStringFromJSON(JSONObject json, String key){
String value = ""; // Blank string by default.
try {
String value = json.getString(key);
return value;
}
catch(JSONException exp){
exp.getMessage();
}
return value; // this wil return BLANk string if object is not prasent.
}
You can you this method for getting String from json object,
I'm trying to pull values from a preset xml file and I keep getting null when I try to check what the value was.
if (pulled.equals("preset")) {
presetName = xmlParser.getAttributeValue(null,"name");
Log.d(TAG, presetName + " = " + xmlParser.getText());
}
This is the xml im Pulling the value from
<?xml version="1.0" encoding="utf-8"?>
<sports>
<sport name="Baseball" paid="false">
<preset name="Pitching Mound">726.0</preset>
<preset name="Base Distance">1080.0</preset>
</sport>
<sport name="Basketball" paid="false">
<preset name="NBA Free Throw Line">181.08</preset>
<preset name="NBA 3pt Line">265.8</preset>
</sport>
<sport name="Cricket" paid="true">
<preset name="Cricket Pitch">2012.0</preset>
<preset name="Testing">0.8</preset>
</sport>
</sports>
Am I doing something wrong?
On XmlPullParser api, the getText() method has the following description:
Returns the text content of the current event as String. The value
returned depends on current event type, for example for
TEXT event it is element content (this is typical case when next()
is used). See description of nextToken() for detailed description of
possible returned values for different types of events.
NOTE: in case of ENTITY_REF, this method returns the entity
replacement text (or null if not available). This is the only case
where getText() and getTextCharacters() return different values.
So based on this description, first you have to check if the current xml node is TEXT in order that getText() doesn't return null.
if (pulled.equals("preset")) {
presetName = xmlParser.getAttributeValue(null,"name");
if (xmlParser.getEventType() == XmlPullParser.TEXT) {
Log.d(TAG, presetName + " = " + xmlParser.getText());
}
}
Hope this helps,