简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM