Android Async task Run time Exception Error. - java

I am doing a decryption task in android platform. At first, I create a method called RunDecrypt. It's work fine when I press the button in my UI. The method shown below:
public void runDecrypt() throws IOException{
EditText editText = (EditText) findViewById(R.id.fileName);
EditText editText2 = (EditText) findViewById(R.id.keyName);
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
DecKey = brKey.readLine();
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
try{
byte[] cipherByte = DES.parseBytes(Cipher);
String decKey = DES.convertStringToHex(DecKey);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
}catch(Exception e){
messageBox("Decrypt", "Please Upload File Properly");
}
}
Since it's work fine, I try to implement this method with Async Task for running my work in background. The class that implemented shown below:
private class runDecrypt extends AsyncTask <URL , Integer, Long> {
private final ProgressDialog dialog = new ProgressDialog(Homepage.this);
AlertDialog.Builder builder = new AlertDialog.Builder(Homepage.this);
#SuppressWarnings("resource")
#Override
protected Long doInBackground(URL... params) {
EditText editText = (EditText) findViewById(R.id.fileName);
EditText editText2 = (EditText) findViewById(R.id.keyName);
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
try {
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("File could not be found.");
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
try {
DecKey = brKey.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("Key file could not be found.");
}
String decKey = DES.convertStringToHex(DecKey);
byte[] cipherByte = DES.parseBytes(Cipher);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
return null;
}
protected void onPreExecute() {
this.dialog.setMessage("Decrypting...");
this.dialog.show();
}
protected void onPostExecute(Long result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
builder.setMessage("Decryption Completed");
builder.show();
}
protected void onProgressUpdate(int progress) {
setProgress(progress * 100);
}
}
My onClick method:
public void onClick (View v){
Intent browse = new Intent(this, Browse.class);
switch (v.getId()){
case R.id.browseFile:
browse.putExtra("browse","file");
startActivityForResult(browse, 1);
break;
case R.id.browseKey:
browse.putExtra("browse", "key");
startActivityForResult(browse, 1);
break;
case R.id.decrypt:
new runDecrypt().execute();
break;
default:
break;
}
}
My logcat shown below:
Can Anyone please help? Thank you and appreciated!

There are various issues with your code, but the cause of the particular exception is explained right there in Logcat:
Only the original thread that created a view hierarchy can touch its views.
The line in question is com.example.descracker.Homepage:245 where you invoke setText() on a TextView from an AsyncTask. You will have to move this logic into the UI thread, for instance through AsyncTask's facility functions onPreExecute(), onPostExecute() or onProgressUpdate(), or by posting a delayed action to the view itself using post(Runnable).
Also, please follow Java coding conventions and start your variables names with a lowercase letter.

As Shashank kadhe mentioned try this in your onPostExecute method and please change it according to your own need.
protected void onPostExecute(String file_url) {
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
DecKey = brKey.readLine();
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
try{
byte[] cipherByte = DES.parseBytes(Cipher);
String decKey = DES.convertStringToHex(DecKey);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
}catch(Exception e){
messageBox("Decrypt", "Please Upload File Properly");
}
}
Since it's work fine, I try to implement this method with Async Task for running my work in background. The class that implemented shown below:
private class runDecrypt extends AsyncTask <URL , Integer, Long> {
private final ProgressDialog dialog = new ProgressDialog(Homepage.this);
AlertDialog.Builder builder = new AlertDialog.Builder(Homepage.this);
#SuppressWarnings("resource")
#Override
protected Long doInBackground(URL... params) {
EditText editText = (EditText) findViewById(R.id.fileName);
EditText editText2 = (EditText) findViewById(R.id.keyName);
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
try {
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("File could not be found.");
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
try {
DecKey = brKey.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("Key file could not be found.");
}
String decKey = DES.convertStringToHex(DecKey);
byte[] cipherByte = DES.parseBytes(Cipher);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
}
}

Related

Data management from file in Android

I am not able to save data from file into an object.If I recover the data from the file and save them in a string, the application works, but as soon as I try to save them inside an object (a Note object in my case), I fail .
It is a simple app(similar to notepads) with only a mainActivity to manage operations, an object class that include two variable, one for "title" and another one for "text" and an xml file with two input fields, two buttons(load and save) and a textView to view the data.
This is the the mainActivity code:
public class MainActivity extends AppCompatActivity {
EditText title,text;
Button save,load;
TextView result;
ArrayList<Note> notes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = findViewById(R.id.id_title);
text = findViewById((R.id.id_post));
save = findViewById(R.id.buttonSave);
load = findViewById(R.id.buttonLoad);
result = findViewById(R.id.id_result);
Context context = getApplicationContext();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String titolo = title.getText().toString();
String post = text.getText().toString();
//Note nota = new Note(titolo,post);
Note nota = new Note(titolo,post);
//nota.setTitle(titolo);
//nota.setNote(post);
saveData(nota,context);
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//ArrayList<Note> data;
//String x;
//x= readData(context);
//x = data.getTitle() + " " +data.getNote();
//result.setText(x);
//setTextToTextview();
readData(context);
}
});
}
/**
* This function saves data on file
* #param nota
* #param context
*/
public void saveData(Note nota,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("text.txt", Context.MODE_APPEND));
outputStreamWriter.write(nota.getTitle().toString() + "," + nota.getNote().toString() + "\n");
outputStreamWriter.flush();
outputStreamWriter.close();
Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.getMessage();
}
}
private void setTextToTextview() {
String text = "";
for(int i = 0; i < notes.size(); i++)
{
text = text + notes.get(i).getTitle() + "" + notes.get(i).getNote() + "\n";
}
result.setText(text);
}
/**
* Read data from file
*/
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(receiveString, ",");
Note nota = new Note(token.nextToken(), token.nextToken());
notes.add(nota);
}
inputStream.close();
bufferedReader.close();
setTextToTextview();
//stringa = stringBuilder.toString();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
/*******************************************************
*this work
*******************************************************/
/*
public String readData(Context context)
{
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.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("\n").append(receiveString);
}
inputStream.close();
bufferedReader.close();
ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return ret;
}
*/
/*****************************************
* this work
*******************************************/
/*
public String readData(Context context)
{
// Note nota = new Note();
String stringa ="";
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.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("\n").append(receiveString);
ret = stringBuilder.toString();
// StringTokenizer token = new StringTokenizer(ret,",");
String split[]= ret.split(",");
for(int i = 0; i< split.length;i++)
{
stringa = stringa +"," + split[i];
}
/*
nota.setTitle(split[0]);
nota.setNote(split[1]);
notes.add(nota);
*/
/*
}
inputStream.close();
bufferedReader.close();
//setTextToTextview();
//ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return stringa;
}
*/
}
I also tried like this:
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.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("\n").append(receiveString);
stringa = stringBuilder.toString();
part = stringa.split(",",2);
Note nota = new Note(part[0],part[1]);
notes.add(nota);
setTextToTextview();
}
inputStream.close();
bufferedReader.close();
//stringa = stringBuilder.toString();
}
} catch (final IOException e) {
e.printStackTrace();
}
//return stringa;
}
thanks to anyone who can help me.

AndroidStudio - save user info in CSV file and read it

I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:
public void save(View view)
{
String fileName = "user.csv";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
File file = new File(directory, fileName);
String data = "FirstName,LastName,PhoneNumber";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
The data seems to be saved and I'm redirected to MainActivity. Here is the method:
protected void onCreate(Bundle savedInstanceState) {
File file = new File(getFilesDir(),"user.csv");
if(!file.exists()) {
Intent intent = new Intent(this, activity_login.class);
startActivity(intent);
}
else {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_phone = findViewById(R.id.tv_phone);
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("user.csv"));
while ((sCurrentLine = br.readLine()) != null) {
tv_name.setText(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
No value is stored in TextView tv_name and the box is empty. Where am I making mistake?
Thank you very much for your help!
For reading data saved use this method uses, UTF_8 ENCODING
public static String readAsString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
String line;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
reader = new BufferedReader(new InputStreamReader(is,UTF_8));
}
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
return sb.toString();
}
Use this method as follows, parsing file "user.csv".
public static String readFileAsString(File file) throws IOException {
return readAsString(new FileInputStream(file));
}
Fetch string and set textView
Use as this to read file:
FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
Below is the code for creating .csv file and inserting data into it.
For more look into my answer :https://stackoverflow.com/a/48643905/8448886
CODE HERE:
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});

How to remove specific line from the file

I am trying to delete a specific line from a file, but when I run this, it returns me all the files, deleted. More specific i have a favorite button at a video fragment and i want when user press it ,to write the title of video in file (already done) and when unpress it to delete it....
my.java class is:
private void writeToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/config.txt");
FileOutputStream fos = new FileOutputStream(file,true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (!file.exists()) {outputStreamWriter.write(g);}
outputStreamWriter.append("\n"+g +"\n");
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private void deleteToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
outputStreamWriter.write(text.toString());
}
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.favorite:
if(showingFirst==true) {
Context context = getActivity();
CharSequence text = "Added to Favorites";
int duration = Toast.LENGTH_SHORT;
item.setIcon(R.drawable.heart_off);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
writeToFile(title,context);
showingFirst=false;
} else {
Context context = getActivity();
CharSequence text = "Deleted from Favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
deleteToFile(title,context);
item.setIcon(R.drawable.heart_wh);
showingFirst=true;
}
break;
case R.id.home:
Intent k=new Intent(getActivity(),MainActivity.class);
Log.i(TAG, "onNavigationItemSelected: ");
startActivity(k);
break;
}
return false;
}
So, problem lies at below line of codes where you are trying to open file for Read and Write simultaneously
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
Instead, I would suggest you to read your file completely and then at the end you should write to the file (overwrite).
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
//start writing from here
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(text.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
}
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
This line:
FileOutputStream fos = new FileOutputStream(file);
resets contents of the file (ie replaces it with empty file). I recommend you add logging and/or debug your code so you will have a better understanding of what is going on.

viewing a txt file from a textview

i want to show a txt file by a text view and i use of this code
TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);
InputStream iFile = getResources().openRawResource(R.raw.quizhelp);
String strFile = inputStreamToString(iFile);
helpText.setText(strFile);
in api 8 i have tested and this code works fine but in my new project that i have setted min sdk to 15 , can NOT recognize inputStreamToString method ! what method i should use instead this ?
tnx
You can use BufferedReader:
TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);
InputStream iFile = getResources().openRawResource(R.raw.quizhelp);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(iFile));
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
String line;
try {
while ((line = bufferReader.readLine()) != null) {
sb.append(line);
sb.append(newline);
}
} catch (IOException e) {
e.printStackTrace();
}
helpText.setText(sb.toString());
You can do it this way
TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);
try {
Resources res = getResources();
InputStream ins = res.openRawResource(R.raw.quizhelp);
byte[] b = new byte[ins.available()];
ins.read(b);
helpText.setText(new String(b));
} catch (Exception e) {
e.printStackTrace();
}

How to sort strings from txt file and post them to textview item

I am reading from txt file some strings.TextView shows me:"score=10" "score=1""score=5""score=11"
I want to sort this like:TextView shows:"score=1" "score=5""score=10""score=11"
I dont know how to sort this strings.this are not ints.
Can u Help me with an example ? Or can u see my code?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wyniki);
final TextView scores = (TextView) findViewById(R.id.textView4);
final Button button5 = (Button) findViewById(R.id.button5);
String saved_scores = readText();
if (saved_scores.length()>0){
scores.setText(saved_scores);}
sort();
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final File f = new File(Environment.getExternalStorageDirectory()+"/cos/Wynik.txt");
if (f.exists()){
f.delete();
Toast.makeText(getApplicationContext(),"Deleted",Toast.LENGTH_SHORT).show();
scores.setText(null);
}
}
});
}
public String readText(){
//this is your text
StringBuilder text = new StringBuilder();
try{
final File f = new File(Environment.getExternalStorageDirectory()+"/cos/Wynik.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = "";
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
text.append(readString + "\n");
}
buf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return text.toString();
}
Remove the "score=" part of each line in the text file, and for each line check if the remaining content is a valid number - if so, store that as an integer in a collection. Once you're done with reading the text file, you can just sort the collection and use the data in whatever fashion you want in your TextView.
You can do the following
Scanner Reader=new Scanner(fileName);
In a for loop read all the integers from using Reader.nextInt() function.

Categories

Resources