Android: Getting into right condition using fileinputstream - android

I'm facing a different problem, see below is the code for my app that can read stored file and have to check condition according to that.
My inputs are "ON" and "OFF"
String val="";
final ToggleButton start = (ToggleButton) findViewById(R.id.startup);
FileInputStream fileos;
try {
fileos = openFileInput("startup");
byte[] input = new byte[fileos.available()];
while(fileos.read(input) != -1){
val += new String(input);
}
if(val.toString() == "ON"){
start.setChecked(true);
}else if(val.toString() == "OFF"){
start.setChecked(false);
}else{
start.setChecked(true);
}
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above code fetching the output correctly either "ON" or "OFF", But it Always going into else conditionelse
else{ start.setChecked(true); }
I'm stucked here, Please help me some one

android is based in java , in java you can't use "==" to compare two strings , you should replace
val.toString() == "ON"
to
"ON".equals(val.toString())

There are actually two big problems with this code. One is that you must use the equals() method to compare String objects, always -- the == operator is appropriate only in very limited cases.
The second one is more subtle, and won't break all the time. When you read data into input, although you're using a loop, the code will only work if all the data is read at once. This is because you're creating a String out of the entire array, even if the entire array doesn't contain valid data. The correct loop would look like this:
int count;
while((count = fileos.read(input)) != -1){
val += new String(input, 0, count);
}

you have to compare the string using .equals()
if(val.equals("ON")){
start.setChecked(true);
}else if(val.equals("OFF")){
start.setChecked(false);
}else{
start.setChecked(true);
}

Use String.equals() to compare Strings. Do no use ==
val.toString().equals("ON")

Related

Can editText.getText().toString().trim().length() ever generate NullPointerException?

I have many EditText in my app and I have used below code to check whether EditText is empty or not.
if (etEditText.getText().toString().trim().length() > 0)
EditText is initialized properly but I have not added null check since I read that getText().toString() never returns null. Can above code ever generated NullPointerException assuming that EditText is initialized properly? I want to be safe in every situation.
Proper way to null check as follows.
if (etEditText != null) {
String str = etEditText.getText().toString();
if (!TextUtils.isEmpty(str) && (str = str.trim()).length() > 0) {
// str will be trimmed text
// Do your work here
}
}
This is not a recommended way to check for a null string. Try this instead:
String text = etEditText.getText().toString();
if(!text.isEmpty()) {
....
}
And the remaining part where you are asking about NullPointerException,
EditText.getString() rarely generates that but it sometimes does, so it's better to enclose the code with a try and catch block like so:
try {
String text = etEditText.getText().toString();
if(!text.isEmpty()) {
...
}
} catch(NullPointerException e) {
e.printStackTrace();
}
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}

Android file create

I just started to learn developping android and I have a (probably) basic questions, but I didn't find anything clear.
I'm trying to store data in a JSON file, well, I've understood the logic to store it, my way is:
public boolean writeFileJson(JSONObject jobj) {
try {
FileOutputStream fOut = openFileOutput(file, Context.MODE_PRIVATE);
fOut.write(jobj.toString().getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
} catch (Exception e1) {
e1.printStackTrace();
}
return true;
}
But my problem is to read, and concretely for the first time, because the way I do it is:
public String readFileJson() {
int c;
String temp = "";
try {
FileInputStream fin = openFileInput(file);
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
}
return temp;
}
So wen I read it for the first time and I want to acces to a parameter of my JSON is obvious that any JSON Object already exist in the file.
So I try to save a first JSON Object with my parameters in onCreate() method and save it in the file, but wen I run the app, and I stop it, it returns again to execute onCreate() and deletes all data stored during the run time.
So my question is: There is any way to init only for one time the parameters of the JSON file to could access for the first time unlike it's empty???
I hope that I'd explained well!!
Thanxxxx!!!!
You can create your own flag boolean and check when you start.
Well I don't understand well why you can use a flag if the flag is set to init value in onCreate(), but I've tried a basic method: check each time if the json file is null. But it's like so basic no? Is there any ther way, or trying to understand how to use flags without reset their values?
msgjson = readFileJson();
if(msgjson == "") {
json.put("ARRAY", jsonArray);
}else{
json = new JSONObject(msgjson);
}
Thanx!!

Eclipse - Functions issue [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to get text from server and then check it a to know what actions to take with the text adopted. The problem is that when I try to check if the received text for example is "Exited" the query always return the value "false" when the received text is really "Exited".
Here is the code :
class Get_Message_From_Server implements Runnable
{
public void run()
{
InputStream iStream = null;
try
{
iStream = Duplex_Socket_Acceptor.getInputStream();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create byte array of size image
byte[] Reading_Buffer = null;
try
{
Reading_Buffer = new byte [Duplex_Socket_Acceptor.getReceiveBufferSize()];
//New_Buffer = new byte [100];
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] Byte_Char_1 = new byte[1];
int Byte_String_Lenght = 0;
//read size
try
{
iStream.read(Reading_Buffer);
String Reading_Buffer_Stream_Lenghtor = new String(Reading_Buffer);
//System.out.println("full : " + Reading_Buffer_Stream_Lenghtor);
Byte_String_Lenght = Reading_Buffer_Stream_Lenghtor.indexOf(new String(Byte_Char_1));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert to String
Meassage = new String(Reading_Buffer);
Meassage = Meassage.substring(0, Byte_String_Lenght);//The text that received
Message_Getted = 1;
}
}
The query :
if(Message_1 != "Exited")//the message query
{
System.out.println("Continued 253");
continue;
}
Its always return the value - false
its important to know that the message is in Utf - 8 encoding
so how i can to fix the issue ?
If you compare strings by using oparators, Java will not look at the contents of the string but at the reference in memory. To compare String content in Java, you should use the following:
String Message_1; // Hopefully has a value sent by the server
if(Message_1.equals("Exited")) {
// Do stuff when exited
} else {
// Do stuff when not exited
}
String is a variable - and variables should start with lower Case letter - Please read Java Code conventions. Also to check if your message contains string you thing it should just do System.out.println(Message_1); and if the message contains what you expect you compare string doing
if(Message_1.equals("Exited")) {
System.out.println("Yes they are equal");
} else {
System.out.println("No they are not");
}
If this will print "No they are not" that simply means that your variable Message_1 is not what you think it is.. As simple as that. There is no such a thing as .equals method does not work. Its your variable that doesn't ;)

Get int from text file and set it to variable

I'm trying to get the int value of a text file that have text like:
123456789 12345678 1234567 123456 12345 1234 123 12 1
as you can see every number is different and they are in a same line separated by a "space". I need to get the values separated. to get something like this:
INT1 = 123456789, INT2 = 12345678, INT3 = 1234567;
and so on. I don't create the text so I don't know how much numbers and groups they are, but they are always separated by a "space". I know how to read it. This is how I'm reading it:
try {
TEST1 = new BufferedReader(new FileReader("/sdcard/test.txt")).readLine();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TEST.setText(""+scaling_available_frequencies);
and I got this output
194208 776175 958253 767883 700246 243663 966618 345199 945363 459833
NOTE: This is just a test.txt that I created to see if it works. The current code will ask the user for entering path and file name.
Now how can I set them to a variable per group?
Thanks
This is one way to parse the String to an integer array:
public int[] toIntArray( String stringFromFile ){
String[] allStrings = stringFromFile.split( "\\s" );
int[] intArray = new int[allStrings.length];
for( int i = 0; i < allStrings.length; ++i ){
try{
intArray[i] = Integer.parseInt( allStrings[i] );
}catch( NumberFormatException e ){
// Do whatever you think is appropriated
intArray[i] = -1;
}
}
return intArray;
}
Hope this helps.
I believe readLine() get you String.
You will need to use the Split() method of String and pass in the regularExpression (whitespace).
then you will need to use Integer.parseInt( ) method and pass in every string to parse them into Integer.
you also need a loop to do the parse until nothing left

Dynamically populating an expandableListView

So All I'm trying to do is create a dynamic expandableListView Currently It works if I just do the groupViews. The problem comes in when I have to populate the children of those groupViews.. I don't know if I'm doing something wrong, or if theres another better way to do it. If anyone knows please let me know. I'm open to anything.
Currently I'm pulling my data off a server and the error I'm getting is java null pointer exception. So I'm thinking it might have something to do with how big I specified my array sizes?
private static String[][] children = new String[7][4];
private static String[] groups = new String[7];
Here is the rest of the code when I try to populate the View.
public void getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
childrenCount = 0;
// check to see if readline equals Location
//Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
temp = my_buffer.readLine();
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[groupCount][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
groupCount++;
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
}
to me it looks like an error in the loop - as you are reading another line without checking is it null
your while loop should look something like this methinks:
// prime read
while (temp != null ){
int childrenCount = 0;
// check to see if readline equals Location
// start a new location
//Log.w("HERasdfsafdsafdsafE", temp);
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
//>>remove following line as that one isn't checked and
//>>you are loosing on a line that is potentialy a child
//temp = my_buffer.readLine();
//>>check do you have first item to add subitems
else if (tempGroupCount>0){
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[tempGroupCount-1][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
//>>next counter is probably not need but can't see if you're using it somewhere else
//groupCount++;
}
I would first replace strings array to some 2d collection for example arraylist2d ( you can google it ) so you could easally add and remove data from list. If you created adapter that extends BaseExpandableListAdapter everything should be handled without any problems.
About NULLPointer, could you paste stacktrace or more info on which line it occurs ?

Categories

Resources