Android - Ignoring Catch Clause? - android

Can "catch" clause be ignored? I have this code and what I wanna do is to scan all words containing a specific string and store them in String res.
But the code I have now does not iterate through the loop because it stops when the "catch" clause interrupts. Is there a way to ignore catch clause and just let the "try" continue the loop until it reaches the end of file?
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}

If you really want it to continue on the inner loop even after an error you could put another try block in there.
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try {
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
catch (Exception e) {
// Error in string processing code (as opposed to IO) - Don't care... Continue
}
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
Another idea is to use more specific Exceptions - not just the general catch all Exception

I thing you must be getting exception inside while, So try this.
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
} catch(Exception e){
// Do Something
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
If you get exception it would be handled inside the loop but your loop will continue.

There is nothing in your catch clause. Try to add something like below for while loop(keep it in try block) as well to find out which exception u got:
catch(Exception e)
{
Log.e("Exception here: "+ e.getMessage());
}

Related

Android Protected variable storage even after factory reset

I'm working on Aosp. I want to keep a variable in the system but When I use a shared preference, the variable is deleted when I perform a Factory reset. I need to change and save the variable I want to keep. Think like a Mac address
You can put all the variables you want to save into a json and save it in internal storage
and you can retrive it whenever you want
example code for read and write
private void saveConfig(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
} }
private String readConfig() {
String data = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
data = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("Error", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("Error", "Can not read file: " + e.toString());
}
return data;
}
and your json can be
{
"variable1": "Value",
"variable2": false
}

Boolean.parseBoolean not working

I am trying to save this boolean array. When I read the array the string array (parts) says that
parts[0]=true;
,but when I use Boolean.parseBoolean array[0] is still false. Can someone help me and tell me what I am doing wrong. Please and Thank You.
public void writeArraytofile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(Arrays.toString(array));
outputStreamWriter.close();
} catch (IOException e) {
Log.v("MyActivity", e.toString());
}
}
public boolean[] read(){
String result = "";
boolean[] array = new boolean[2];
try {
InputStream inputStream = openFileInput("array.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
inputStream.close();
result = stringBuilder.toString();
String[] parts = result.split(" ");
for (int i = 0; i < array.length; i++){
array[i]=Boolean.parseBoolean(parts[i]);
}
}
} catch (FileNotFoundException e) {
Log.v("MyActivity", "File not found" + e.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
//here you catch and watch the problem
Log.e("MyActivity", "cant parse string: " + result);
}
return array;
}
Arrays.toString() will print brackets and commas, so when you read the string back in and call .split(" "), the first piece will be "[true,". Since that is not just "true", Boolean.parseBoolean() will return false.

How can I process FileNotFoundException ?

recently
I try A.txt file read content.
but if my device have not a.txt , occur FileNotFoundException
so I want if my device have not a.txt, How can i stay to proceed?
String path = "/sdcard/Download";
String textName = "a.txt";
String serverVersion = null;
BufferedReader br = null;
try {
br = BufferedReaderFactory.create(path, textName);
StringBuilder contentGetter = new StringBuilder();
while ((serverVersion = br.readLine()) != null) {
serverVersion = serverVersion.trim().toLowerCase();
contentGetter.append('\n' + serverVersion);
Log.d(TAG, " myServerVersion = " + serverVersion);
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
You can simple create a variable before try/catch like
boolean isFileFound = false;
So, at the final of the try you set isFileFound = true
like:
String path = "/sdcard/Download";
String textName = "a.txt";
boolean isFileFound = false;
String serverVersion = null;
BufferedReader br = null;
try {
br = BufferedReaderFactory.create(path, textName);
StringBuilder contentGetter = new StringBuilder();
while ((serverVersion = br.readLine()) != null) {
serverVersion = serverVersion.trim().toLowerCase();
contentGetter.append('\n' + serverVersion);
Log.d(TAG, " myServerVersion = " + serverVersion);
break;
}
isFileFound = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (!isFileFound){ // This is equals to if(isFileFound != null)
//Do some message here, like:
Toast toast = Toast.makeText(context, "File not found", Toast.LENGTH_SHORT).show();
}
It looks like you are already handling the exception. If there is no file your code will continue as planned. After your try/catch blocks, you should check if(serverVersion == null) and if it returns true, you know that the serverVersion was not read from the file.

Android Studio - Why does a string array cause my program to stop?

I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));

How to concatenate long String in StringBuffer for Android

I am facing one problem in StringBuffer concatination for appending large characters of String from JSONArray.
My data is huge and it is coming in log after iteration of 205 indexes of Array properly
but when I am appending each row String in StringBuffer or StringBuilder from JSONArray, so it is taking on 4063 characters only not appending all characters present in JSON Array but iteration doesn't break and goes till complete 204 rows.
String outputFinal = null;
try {
StringBuilder cryptedString = new StringBuilder(1000000);
JSONObject object = new JSONObject(response);
JSONArray serverCustArr = object.getJSONArray("ServerData");
Log.d("TAG", "SurverCust Arr "+serverCustArr.length());
for (int i = 0; i < serverCustArr.length(); i++) {
String loclCryptStr = serverCustArr.getString(i);
Log.d("TAG", "Loop Count : "+i);
cryptedString.append(loclCryptStr);
}
Log.d("TAG", "Output :"+cryptedString.toString());
CryptLib _crypt = new CryptLib();
String key = this.preference.getEncryptionKey();
String iv = this.preference.getEncryptionIV();
outputFinal = _crypt.decrypt(cryptedString.toString(), key,iv); //decrypt
System.out.println("decrypted text=" + outputFinal);
} catch (Exception e) {
e.printStackTrace();
}
My JSONArray contacts 119797 characters in 205 and after iteration for appending in StringBuffer, I have to decrypt it with library that takes string for decryption. But StringBuffer is not having complete data of 119797 characters.
And Exception is because string is not complete, I am enclosing files on link below for reference and also using cross platform CryptLib uses AES 256 for encryption easily find on Github
3 Files With Original and Logged text
Dont use StringBuffer , instead use StringBuilder ..here's the detailed Explaination
http://stackoverflow.com/questions/11908665/max-size-for-string-buffer
Hope this helps. :)
EDIT
this is the code that i used to read whole string ...
public void parseLongString(String sourceFile, String path) {
String sourceString = "";
try {
BufferedReader br = new BufferedReader(new FileReader(sourceFile));
// use this for getting Keys Listing as Input
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
br.close();
sourceString = sb.toString();
sourceString = sourceString.toUpperCase();
System.out.println(sourceString.length());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(path);
FileWriter fileWriter = null;
BufferedWriter bufferFileWriter = null;
try {
fileWriter = new FileWriter(file, true);
bufferFileWriter = new BufferedWriter(fileWriter);
} catch (IOException e1) {
System.out.println(" IOException");
e1.printStackTrace();
}
try {
fileWriter.append(sourceString);
bufferFileWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
}
and this is outPut file where i am just converting it to uppercase .
https://www.dropbox.com/s/yecq0wfeao672hu/RealTextCypher%20copy_replaced.txt?dl=0
hope this helps!
EDIT 2
If u are still looking for something ..you can also try STRINGWRITER
syntax would be
StringWriter writer = new StringWriter();
try {
IOUtils.copy(request.getInputStream(), writer, "UTF-8");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String theString = writer.toString();

Categories

Resources