将数据保存到外部存储,读取并显示为ListView

时间:2018-10-15 16:04:01

标签: java android listview external

我正在尝试编写一个适用于Android的简单游戏应用程序,并且在游戏结束时无法显示玩家的姓名和得分。我需要在外部存储设备上存储用户的姓名和分数,并且在游戏结束时阅读并显示它。我创建了一个具有两个字段的User类:

 public class User implements Serializable {

    private String name;
    private int score;

    public User(String name, int score){
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getUser(){
        StringBuilder builder = new StringBuilder(name);
        builder.append("\f");
        builder.append(Integer.toString(score).length() == 0 ?  "\t" : 
        score);
        return builder.toString();
    }
   }

到目前为止,我设法保存并显示了一行-当前玩家的姓名和得分。但是由于游戏崩溃,我试图显示曾经玩过该游戏的所有玩家的列表似乎出了点问题,对于实现这一目标的任何帮助或建议,我将不胜感激。 / p>

public class EndGame extends AppCompatActivity {
TextView player_name;
String target_file = "players";
String player_info;
String line = null;
private static final int REQUEST_CODE_PERMISSION = 1;
ArrayList<User> list_players = new ArrayList<User>();
ArrayAdapter<User> adapter;
ListView players;
Intent end_G = getIntent();
User player = (User) end_G.getSerializableExtra("object");


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_end_game);

    player_info = player.getUser();
    player_name = findViewById(R.id.userName);
    players = findViewById(R.id.lst_players);

    int writeExternalStoragePermission = ContextCompat.checkSelfPermission(EndGame.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (writeExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(EndGame.this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);

    save_user(target_file, player_info);
    show_player();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.end_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.new_game:
            Intent new_game = new Intent(EndGame.this, Login.class);
            EndGame.this.startActivity(new_game);
            EndGame.this.finish();
            return true;
        case R.id.exit:
            System.exit(0);
            return super.onOptionsItemSelected(item);
    }
    return true;
}


public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull
        int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CODE_PERMISSION) {
        int grantResultsLength = grantResults.length;
        if (grantResultsLength > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(), "You granted write external storage permission"
                    , Toast.LENGTH_LONG).show();
        } else
            Toast.makeText(getApplicationContext(), "You denied write external storage permission"
                    , Toast.LENGTH_LONG).show();
    }
}

private static boolean isExternalStorageWritable() {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        Log.i("State", "Writable");
        return true;
    } else return false;
}

private static boolean isExternalStorageReadable() {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())) {
        Log.i("State", "Readable");
        return true;
    } else return false;
}

public void save_user(String file, String Name) {
    if (isExternalStorageWritable()) {
        File textFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                file);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(textFile);
            fileOutputStream.write(Name.getBytes());
            fileOutputStream.close();
            //Toast.makeText(this, "File saved", Toast.LENGTH_SHORT).show();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }//else Toast.makeText(this, "External storage is not mounted", Toast.LENGTH_SHORT).show();

}


public void show_player() {
    if (isExternalStorageReadable()) {
        try {
            File textFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                    target_file);
            FileInputStream fileInputStream = new FileInputStream(textFile);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            boolean firstLine = true;
            if (fileInputStream != null) {
                while ((line = bufferedReader.readLine()) != null) {
                    if (firstLine) {
                        firstLine = false;
                        continue;
                    }
                    list_players.add(player);
                    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list_players);
                    players.setAdapter(adapter);
                }

                fileInputStream.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } else Toast.makeText(this, "Cannot read from external storage", Toast.LENGTH_SHORT).show();
}

}

0 个答案:

没有答案