Error parsing Colors from String - android

EDIT:A Pastebin consisting of the relevant parts of my project:
Here is the updated code
Also ColouredItem is a wrapper for:
public class ColouredItem
{//Only a wrapper class,no behaviour has been defined here
String name,colour;
}
I get a NumberFormatException when trying to parse a colour from a String using the following code:
row.setBackgroundColor(Color.parseColor(item.colour));
I use the following to create a list of items from a resource:
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.colour="#"+cmenu[1];
Log.d(TAG, item.colour);
menuList.add(item);
}
This is the exception that I get...I have found that view.setBackgroundColor only takes an integer value:
#ffffff
#ffffBB
#fff45f
#ffff00
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x4001d800)
FATAL EXCEPTION: main
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.makeAndAddView(ListView.java:1727)
at android.widget.ListView.fillDown(ListView.java:652)
at android.widget.ListView.fillFromTop(ListView.java:709)
at android.widget.ListView.layoutChildren(ListView.java:1580)
at android.widget.AbsListView.onLayout(AbsListView.java:1147)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Adding the # as some of the answers suggest did not solve the issue:
java.lang.NumberFormatException: Invalid long: "#ffffff"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
No difference with this implementation either:
String cmenu=list[i];
item.name=cmenu.substring(0, cmenu.indexOf("#"));
item.colour=cmenu.substring(cmenu.indexOf("#"));

Use this code
row.setBackgroundColor(Color.parseColor("#424242"));
it helped me too,dont remove "#".
i used this code
private List<String> item;
item = new ArrayList<String>();
item.add("#424242");
row.setBackgroundColor(Color.parseColor(item.get(0)));
and its working gud for me,may be your split thing is not working good
or for your code
Button btn;
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[] { "Page1 #ffffff", "Page2 #ffffBB" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
try {
btn = (Button) findViewById(R.id.button1);
for (int i = 0; i < list.length; i++) {
item = new ColouredMenuItem();
String[] cmenu = list[i].split("#");
item.name = cmenu[0];
item.color = "#" + cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
btn.setBackgroundColor(Color.parseColor(menuList.get(1).color));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is working good at my side
this is new code
Make your colored item as a bean class with getter and setter like this
public class ColouredMenuItem {// Only a wrapper class,no behaviour has been defined
// here
String name, colour;
List<ColouredMenuItem> list=new ArrayList<ColouredMenuItem>();
public List<ColouredMenuItem> getList() {
return list;
}
public void setList(List<ColouredMenuItem> menuList) {
this.list = menuList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
Then in your adapter use this code
try {
Log.d(TAG, menuList.get(position).colour);
textView.setText(menuList.get(position).getName());
{
row.setBackgroundColor(Color.parseColor(menuList.get(position).getColour()));
}
} catch (Exception ex) {
Log.e(TAG, "Still does not work");
}
Just give it a try,it works here at my side
Also your array is like this only na
<string-array name="menu_array">
<item>Page1 #ff7788</item>
<item>Page1 #ff6688</item>
<item>Page1 #424242</item>
</string-array>

Try Color.parseColor("#ffffff"); instead of Color.parseColor("ffffff");

look at the Stack trace it will tell you:
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
Line by Line:
you are trying to format Hexadecimal (base 16) value "0xffffff" to a decimal (base 10) value
you're trying to parse hexadecimal string "ffffff" to type Long
same as above.
error is thrown when calling `Color.parseColor()`
error is thrown from your MadAdapter.java Class on line 60.
so, you need to find a way to parse it from Hexadecimal instead of decimal value. Hexadecimal values are usually preceeded by 0x[value] OR #[value]

Assuming: while parsing the color from string object "item" is not taken from array of list, rather its taking instance variable of ColoureMenuItem.
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[]{"#ffffff","#00ffff"};
// parsing your string here, no change in this
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.color="#"+cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
// confirming whether value are parsing or not.
for(int i=0;i<menuList.size();i++)
{
int color = Color.parseColor(menuList.get(i).color);
Log.d("color",""+menuList.get(i).color);
}
and your ColouredMenuItem class.
public class ColouredMenuItem {
public String color;
public String name;
}

Related

Import Firebase data into android class [duplicate]

This question already has answers here:
Why do I get "Failed to bounce to type" when I turn JSON from Firebase into Java objects?
(3 answers)
Closed 6 years ago.
I'm trying to Query Firebase data and store it into the Dinosaur class from the example link below. I have an issue when importing directly from Firebase into the Dinosaur Facts class. It's able to create the Query and enters the "onChildAdded" method. It then goes to the Dinosaur constructor class but crashes right after that.
DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class); //CRASHES HERE
https://www.firebase.com/docs/android/guide/retrieving-data.html
Here is DinosaurFacts class
package jobsme.com.firebasequery;
import android.util.Log;
public class DinosaurFacts {
long height;
double length;
long weight;
public DinosaurFacts() {
Log.i("MyActivity", "FIIIIIIIIIIIIIIIIIINDMEEEE2");
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
public long getHeight() {
Log.i("MyActivity", "FIIIIIIIIIIIIIIIIIINDMEEEE3");
return height;
}
public double getLength() {
return length;
}
public long getWeight() {
return weight;
}
}
Here is the onCreate method in the MainAcitivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height");
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
Log.i("MyActivity", "onChildAdded");
DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class);
Log.i("MyActivity", snapshot.getKey() + " was " + facts.getHeight() + " meters tall");
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
// ....
});
Log.i("MyActivity", "FIIIIIIIIIIIIIIIIIINDMEEEE");
}
The query is successful but the importing crashes. Hopefully that means I setup everything correctly?
Here's the log output:
12-11 16:48:37.793 5581-5581/jobsme.com.firebasequery E/AndroidRuntime: FATAL EXCEPTION: main
Process: jobsme.com.firebasequery, PID: 5581
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:196)
at jobsme.com.firebasequery.MainActivity$2.onChildAdded(MainActivity.java:45)
at com.firebase.client.core.ChildEventRegistration$1.run(ChildEventRegistration.java:50)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:37)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "vanished" (class jobsme.com.firebasequery.DinosaurFacts), not marked as ignorable (3 known properties: , "weight", "length", "height"])
at [Source: java.io.StringReader#52851428; line: 1, column: 33] (through reference chain: jobsme.com.firebasequery.DinosaurFacts["vanished"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:192)
at jobsme.com.firebasequery.MainActivity$2.onChildAdded(MainActivity.java:45) 
at com.firebase.client.core.ChildEventRegistration$1.run(ChildEventRegistration.java:50) 
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:37) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
This is the JSON for one of the dinosaurs in that database:
"bruhathkayosaurus": {
"appeared": -70000000,
"height": 25,
"length": 44,
"order": "saurischia",
"vanished": -70000000,
"weight": 135000
},
The DinosaurFacts class you're using only has fields+getters for these properties: height, length, weight. So when the Firebase tries to deserialize the JSON into a DinosaurFacts object, it complains about the unmapped properties.
The simplest way to get rid of the error is by telling Jackson (which Firebase uses internally to map between JSON and Java) to ignore any unmapped properties it encounters in the JSON:
#JsonIgnoreProperties(ignoreUnknown = true)
public static class DinosaurFacts {
But be careful with this. If you now write a DinosaurFacts object back into the database, it will only have height, length and weight properties. It will not have: appeared, order or vanished. In fact: even if the properties did exist in the database before, writing this object back will delete them.
So the proper solution is to map all the properties from the JSON structure into the Java class:
public static class DinosaurFacts {
long appeared, vanished;
double height, length, weight;
String order;
public long getAppeared() {
return appeared;
}
public long getVanished() {
return vanished;
}
public double getHeight() {
return height;
}
public double getLength() {
return length;
}
public double getWeight() {
return weight;
}
public String getOrder() {
return order;
}
}

How to Sum values from EditText on ListView?

I have lists of color variations of a product in the ListView . Each list color variation has an EditText. I want to try to make the validation process orders when my button clicked.
This My Code:
btnOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int count = listView.getAdapter().getCount();
String[] listData = new String[count];
int[] listData2 = new int[count];
int sum = 0;
try {
for (int i = 0; i < count; i++) {
View quantity=listView.getChildAt(i);
if (quantity.findViewById(R.id.quantityOrder) != null){
EditText quantityOrder = (EditText) quantity.findViewById(R.id.quantityOrder);
listData[i] = quantityOrder.getText().toString();
listData2[i] = Integer.parseInt(quantityOrder.getText().toString()); // set edittext to int
sum += listData2[i];
jsonObject.put("params_"+i,listData[i]); // put to params for volley request
}
}
if (sum < 1) {Toast.makeText(getApplicationContext(),
"Sorry, you need to fill Order Quantity", Toast.LENGTH_SHORT) // validation input if edittext empty
.show();} else {
Log.d(TAG, jsonObject.toString()); }
} catch (JSONException e) {
e.printStackTrace();
}
}
});
My app get force close. here the error code
09-25 23:01:05.679 32623-32623/id.nijushop.ikutan E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:359)
at java.lang.Integer.parseInt(Integer.java:332)
at id.nijushop.ikutan.ProductDetail$1.onClick(ProductDetail.java:150)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Please, some one fix my code...I think i need to do something about this
quantity.findViewById(R.id.quantityOrder)// need to set to Interger
The problem is in this line:
listData2[i] = Integer.parseInt(quantityOrder.getText().toString()); // set edittext to int
The Integer.parseInt(String string) method will return an int or throw a NumberFormatException if passed string is not a valid integer string. An empty string - "" doesn't make up a valid integer, so if your EditText is empty, the problem arises.
You need to shield the execution of parseInt with a try - catch block catching a NumberFormatException and act accordingly - abort the method or else, but you obviously cannot continue with your arithmetic if you haven't provided a valid number.
Also, the thing that would help you is, within your EditText element in xml file, include an inputType property, for example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number|numberSigned" />
This inputType property will cause the system to use an automatic inputFilter and provideonly numeric soft keyboard, so the user cannot enter an invalid number (in this case, only a signed integer). However this will still not account for empty input, so you'll need to either catch NumberFormatException or check whether string from your EditText is not empty. (!string.isEmpty())

Unable to store value into string android

I would like to put the value to the String array, but it is unsuccessful.
I don't know what is the exact problem.
public String[] history = null;
public String record;
public int counter = 0;`
public void createString (String record){
history[counter] = record;
counter++;
}
Here is the defining variable.
What is the mistake i have done, and how to fix it ?
03-19 17:15:35.870: W/dalvikvm(4937): threadid=1: thread exiting with uncaught exception (group=0x40c20450)
03-19 17:15:35.890: E/AndroidRuntime(4937): FATAL EXCEPTION: main
03-19 17:15:35.890: E/AndroidRuntime(4937): java.lang.NullPointerException
03-19 17:15:35.890: E/AndroidRuntime(4937): at com.airportapplication.app.Buses.createString(Buses.java:147)
03-19 17:15:35.890: E/AndroidRuntime(4937): at com.airportapplication.app.Buses$1.onClick(Buses.java:101)
You need to initialize your array
like this:
String[] history = new String[lengthOfArray];
if you don't know the array length use this:
List<String> history = new ArrayList<String>();
history.add(record);

ActiveAndroid model bundle extras exception

folks! I wrote a Book class which has Chapter objects (a one to many relationship). It implements the method public List chapters(), as stated in the docs. This is the Book.java
#Table(name = "Books")
public class Book extends Model implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "Name", unique = true, onUniqueConflict = Column.ConflictAction.IGNORE)
public String name;
#Column(name = "Sort")
public int sort;
public Book() {
super();
}
public Book(String name, int sort) {
super();
this.name = name;
this.sort = sort;
}
public List<Chapter> chapters() {
return getMany(Chapter.class, "Book");
}
#Override
public String toString() {
return name;
}
}
On the main activity I can get the Chapter objects successfully. However, I have to pass a book object to another activity, which has a fragment, and though I get the object's stated attributes (String name and int sort) it throws an exception when I call to chapters():
Bundle bundle = getIntent().getExtras();
Book book = (Book) bundle.getSerializable("BOOK");
// This line is executed successfully
Log.d("TAGGED", "Recovered book: " + book.name + " has " + book.sort + " as its sort");
// This is the line that throws an exception
ArrayList<Chapter> chapters = book.chapters();
the thrown exception is the following:
05-06 15:21:59.701: E/AndroidRuntime(9647): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hanovit.libraria/com.hanovit.libraria.chapter.ChapterActivity}: java.lang.NullPointerException
05-06 15:21:59.701: E/AndroidRuntime(9647): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-06 15:21:59.701: E/AndroidRuntime(9647): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-06 15:21:59.701: E/AndroidRuntime(9647): Caused by: java.lang.NullPointerException
05-06 15:21:59.701: E/AndroidRuntime(9647): at com.activeandroid.query.From.getArguments(From.java:207)
05-06 15:21:59.701: E/AndroidRuntime(9647): at com.activeandroid.query.From.execute(From.java:183)
05-06 15:21:59.701: E/AndroidRuntime(9647): at com.activeandroid.Model.getMany(Model.java:266)
Any ideas what is wrong? Thanks!!!
Submitted an issue in Github and now is fixed (https://github.com/melvin7/ActiveAndroid)
On the other hand, putting into the extras bundle only the ID of the column also works. Then I can get the full object with Model.load(Book.class, id)

NullpointerException when Launching activity

i have an arraylist that do this :
ArrayList<Integer> id = new ArrayList<Integer>();
for (int i = 0; i <= 20; i++) {
id.add(getResources().getIdentifier("q"+i, "raw", getPackageName()));}
this method before a little change is working good but now have force close!
and i get this logcat:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{yaAli.package313.hossein110/yaAli.package313.hossein110.know}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)at android.app.ActivityThread.access$600(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at yaAli.package313.hossein110.know.onCreate(know.java:33)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
... 12 more
Here is my OnCreate():
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.basetxt);
SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ln=settings.getString("LASTREADln", null);
if(ln.equals("-1")){ln="0";}
if(ln!=null){
final ScrollView s1=(ScrollView) findViewById(R.id.sV1);
s1.post(new Runnable() {#Override
public void run() {s1.scrollTo(0, Integer.valueOf(ln));} });}
final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.arza);
String pos = getIntent().getStringExtra("key");
String arr = getIntent().getStringExtra("list");
TextView tvfa = (TextView)findViewById(R.id.TEXT313);
String fontPath = "fonts/font1.ttf";
String fontPath1 = "fonts/font2.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
Typeface tf1 = Typeface.createFromAsset(getAssets(), fontPath1);
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
tvfa.getRootView().setKeepScreenOn(sharedpreferences.getBoolean("scrnon", false));
String sizefa= sharedpreferences.getString("fontsizefa",null);
String colorfa= sharedpreferences.getString("fontcolorfa",null);
boolean style= sharedpreferences.getBoolean("appfont", false);
boolean music= sharedpreferences.getBoolean("musictype", false);
boolean curr= sharedpreferences.getBoolean("currputfont", false);
String t = read(file(pos,arr,null)); {
if (curr){tvfa.setText(PersianReshape.reshape(t));}else{tvfa.setText(t);} // Txt
tvfa.setTextSize(1, Float.valueOf(sizefa).floatValue()); // Size
tvfa.setTextColor(Color.parseColor(colorfa)); // Color
if (style) { tvfa.setTypeface(tf1); } else {tvfa.setTypeface(tf);} // Type
if (music) { mp1.start(); } else { mp1.stop(); } }} // Play
//----------------------------------------------------------------------------
best practice for java development is to have the literal string do the .equals call. so instead of:
var.equals("string")
you do:
"string".equals(var)
This guarantees you will NEVER have a null pointer exception when doing string comparison.
Also, it looks like you are storing numeric values as strings. Any particular reason you aren't storing them as ints?
Its likely here
ln=settings.getString("LASTREADln", null);
this should be
ln=settings.getString("LASTREADln", "");
since null is set to be your default value if that key does not exist or contain anything, so if it doesn't contain anything you should set it to "", and for your string comparisons you should look for !ln.contentsEquals("") instead of checking it for null
the same goes for all of the strings you get from a preferences file. set the default value to "" instead of null

Categories

Resources