我在我的应用上设置了一个活动,创建了一个新的高分然后保存它并允许它通过FileOutputStream和FileInputStream逻辑重新加载和显示。我一直在测试手机上的应用程序,当加载高分时我回来了0。我相信这是因为文件中有零个字节。
以下是我的所有代码:
public class Course extends ActionBarActivity {
String chosenCourseValue = "";
int courseNum;
String listPars = "";
String listHoles = "";
String courseImage = "";
int[] scoreNum = new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int totalScoreNum = 0;
String collected = "test string";
public void upButtonOnClick(View imageButton)
{
int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
TextView score = (TextView) findViewById(textViewId);
totalScoreNum++;
if (score.getId() == R.id.score1)
{
scoreNum[0]++;
score.setText(String.valueOf(scoreNum[0]));
}
if (score.getId() == R.id.score2)
{
scoreNum[1]++;
score.setText(String.valueOf(scoreNum[1]));
}
if (score.getId() == R.id.score3)
{
scoreNum[2]++;
score.setText(String.valueOf(scoreNum[2]));
}
if (score.getId() == R.id.score4)
{
scoreNum[3]++;
score.setText(String.valueOf(scoreNum[3]));
}
if (score.getId() == R.id.score5)
{
scoreNum[4]++;
score.setText(String.valueOf(scoreNum[4]));
}
if (score.getId() == R.id.score6)
{
scoreNum[5]++;
score.setText(String.valueOf(scoreNum[5]));
}
if (score.getId() == R.id.score7)
{
scoreNum[6]++;
score.setText(String.valueOf(scoreNum[6]));
}
if (score.getId() == R.id.score8)
{
scoreNum[7]++;
score.setText(String.valueOf(scoreNum[7]));
}
if (score.getId() == R.id.score9)
{
scoreNum[8]++;
score.setText(String.valueOf(scoreNum[8]));
}
if (score.getId() == R.id.score10)
{
scoreNum[9]++;
score.setText(String.valueOf(scoreNum[9]));
}
if (score.getId() == R.id.score11)
{
scoreNum[10]++;
score.setText(String.valueOf(scoreNum[10]));
}
if (score.getId() == R.id.score12)
{
scoreNum[11]++;
score.setText(String.valueOf(scoreNum[11]));
}
if (score.getId() == R.id.score13)
{
scoreNum[12]++;
score.setText(String.valueOf(scoreNum[12]));
}
if (score.getId() == R.id.score14)
{
scoreNum[13]++;
score.setText(String.valueOf(scoreNum[13]));
}
if (score.getId() == R.id.score15)
{
scoreNum[14]++;
score.setText(String.valueOf(scoreNum[14]));
}
if (score.getId() == R.id.score16)
{
scoreNum[15]++;
score.setText(String.valueOf(scoreNum[15]));
}
if (score.getId() == R.id.score17)
{
scoreNum[16]++;
score.setText(String.valueOf(scoreNum[16]));
}
if (score.getId() == R.id.score18)
{
scoreNum[17]++;
score.setText(String.valueOf(scoreNum[17]));
}
}
public void downButtonOnClick(View imageButton)
{
int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
TextView score = (TextView) findViewById(textViewId);
totalScoreNum--;
if (score.getId() == R.id.score1)
{
scoreNum[0]--;
score.setText(String.valueOf(scoreNum[0]));
}
if (score.getId() == R.id.score2)
{
scoreNum[1]--;
score.setText(String.valueOf(scoreNum[1]));
}
if (score.getId() == R.id.score3)
{
scoreNum[2]--;
score.setText(String.valueOf(scoreNum[2]));
}
if (score.getId() == R.id.score4)
{
scoreNum[3]--;
score.setText(String.valueOf(scoreNum[3]));
}
if (score.getId() == R.id.score5)
{
scoreNum[4]--;
score.setText(String.valueOf(scoreNum[4]));
}
if (score.getId() == R.id.score6)
{
scoreNum[5]--;
score.setText(String.valueOf(scoreNum[5]));
}
if (score.getId() == R.id.score7)
{
scoreNum[6]--;
score.setText(String.valueOf(scoreNum[6]));
}
if (score.getId() == R.id.score8)
{
scoreNum[7]--;
score.setText(String.valueOf(scoreNum[7]));
}
if (score.getId() == R.id.score9)
{
scoreNum[8]--;
score.setText(String.valueOf(scoreNum[8]));
}
if (score.getId() == R.id.score10)
{
scoreNum[9]--;
score.setText(String.valueOf(scoreNum[9]));
}
if (score.getId() == R.id.score11)
{
scoreNum[10]--;
score.setText(String.valueOf(scoreNum[10]));
}
if (score.getId() == R.id.score12)
{
scoreNum[11]--;
score.setText(String.valueOf(scoreNum[11]));
}
if (score.getId() == R.id.score13)
{
scoreNum[12]--;
score.setText(String.valueOf(scoreNum[12]));
}
if (score.getId() == R.id.score14)
{
scoreNum[13]--;
score.setText(String.valueOf(scoreNum[13]));
}
if (score.getId() == R.id.score15)
{
scoreNum[14]--;
score.setText(String.valueOf(scoreNum[14]));
}
if (score.getId() == R.id.score16)
{
scoreNum[15]--;
score.setText(String.valueOf(scoreNum[15]));
}
if (score.getId() == R.id.score17)
{
scoreNum[16]--;
score.setText(String.valueOf(scoreNum[16]));
}
if (score.getId() == R.id.score18)
{
scoreNum[17]--;
score.setText(String.valueOf(scoreNum[17]));
}
}
class AsyncAPI extends AsyncTask<Void, Void, String>
{
@Override
protected String doInBackground(Void... arg0)
{
String JSONString = null;
try
{
//hard coded url API from website
String urlString = "http://webthree.ict.op.ac.nz/murraas1/golf.html";
//converting url string to object then sending (same as pressing return)
URL URLObject = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) URLObject.openConnection();
connection.connect();
//if it doesnt return 200 no data received. (use if statement to check in future)
int responseCode = connection.getResponseCode();
//getting inputstream from the sent object and setting up bufferreader
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//reading the input
String responseString;
StringBuilder stringBuilder = new StringBuilder();
while ((responseString = bufferedReader.readLine()) != null)
{
stringBuilder = stringBuilder.append(responseString);
}
//getting string from stringbuilder and converting to a json string
JSONString = stringBuilder.toString();
}
catch (Exception e){e.printStackTrace();}
return JSONString;
}
protected void onPostExecute(String fetchedString)
{
String selectedCourse = "";
String totalPar = "";
if (chosenCourseValue.equals("Chisholm"))
{
courseNum = 0;
courseImage = "chisolm";
}
if (chosenCourseValue.equals("St Clair"))
{
courseNum = 1;
courseImage = "stclair";
}
if (chosenCourseValue.equals("Balmacewen"))
{
courseNum = 2;
courseImage = "balmacewen";
}
if (chosenCourseValue.equals("Taieri"))
{
courseNum = 3;
courseImage = "taieri";
}
if (chosenCourseValue.equals("Island Park"))
{
courseNum = 4;
courseImage = "islandpark";
}
try {
JSONObject root = new JSONObject(fetchedString);
JSONArray courseArray = root.getJSONArray("courses");
JSONObject courseInfo = courseArray.getJSONObject(courseNum);
selectedCourse = (courseInfo.getString("name"));
totalPar = (courseInfo.getString("course par"));
JSONArray parsInfo = courseInfo.getJSONArray("pars");
for(int i = 0; i < parsInfo.length(); i++)
{
JSONObject parsNum = parsInfo.getJSONObject(i);
listPars += ("Par " + parsNum.getString("par") + ",");
}
JSONArray holesInfo = courseInfo.getJSONArray("pars");
for(int i = 0; i < holesInfo.length(); i++)
{
JSONObject holeNum = holesInfo.getJSONObject(i);
listHoles += (holeNum.getString("hole") + ",");
}
}
catch (JSONException e) {
e.printStackTrace();
}
//Convert Pars and Holes text into usable array
String[] listParsArray = listPars.split(",");
String[] listHolesArray = listHoles.split(",");
//dumping Name into textview
TextView tv = (TextView) findViewById(R.id.courseName);
tv.setText(selectedCourse);
//dumping Total Par into textview
TextView tv1 = (TextView) findViewById(R.id.totalPar);
tv1.setText(totalPar);
//dumping Pars into textview
int[] parViewIDs = new int[] {R.id.hole1Par, R.id.hole2Par, R.id.hole3Par, R.id.hole4Par, R.id.hole5Par, R.id.hole6Par, R.id.hole7Par, R.id.hole8Par, R.id.hole9Par, R.id.hole10Par, R.id.hole11Par, R.id.hole12Par, R.id.hole13Par, R.id.hole14Par, R.id.hole15Par, R.id.hole16Par, R.id.hole17Par, R.id.hole18Par,};
for(int i = 0; i < 18; i++) {
TextView tv2 = (TextView) findViewById(parViewIDs[i]);
tv2.setText(listParsArray[i]);
}
//dumping Holes into textview
int[] holeViewIDs = new int[] {R.id.hole1, R.id.hole2, R.id.hole3, R.id.hole4, R.id.hole5, R.id.hole6, R.id.hole7, R.id.hole8, R.id.hole9, R.id.hole10, R.id.hole11, R.id.hole12, R.id.hole13, R.id.hole14, R.id.hole15, R.id.hole16, R.id.hole17, R.id.hole18,};
for(int i = 0; i < 18; i++)
{
TextView tv3 = (TextView) findViewById(holeViewIDs[i]);
tv3.setText(listHolesArray[i]);
}
int[] images = {R.drawable.chisholm, R.drawable.stclair, R.drawable.balmacewen, R.drawable.taieri, R.drawable.islandpark};
ImageView i = (ImageView) findViewById(R.id.courseImage);
i.setImageResource(images[courseNum]);
}
}
private void updateTextView() {
TextView tv3 = (TextView) findViewById(R.id.totalScore);
tv3.setText(String.valueOf(totalScoreNum));
}
public class SaveData implements View.OnClickListener
{
//String totalScoreString = String.valueOf(totalScoreNum);
@Override
public void onClick(View v) {
try {
FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
fou.write(totalScoreNum);
fou.close();
// Toast Confirm
Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadData()
{
FileInputStream fis = null;
try {
fis = openFileInput("scoreFile.txt");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class LoadData implements View.OnClickListener
{
@Override
public void onClick(View v) {
TextView tv7 = (TextView) findViewById(R.id.returnScore);
tv7.setText(collected);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
updateTextView();
}
});
}
} catch (InterruptedException e) {
}
}
};
loadData();
t.start();
Button SaveDataBtn = (Button)findViewById(R.id.saveScore);
SaveData handler = new SaveData();
SaveDataBtn.setOnClickListener (handler);
Button LoadDataBtn = (Button)findViewById(R.id.loadScore);
LoadData handler1 = new LoadData();
LoadDataBtn.setOnClickListener (handler1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
chosenCourseValue = extras.getString("passedChosenCourse");
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AsyncAPI APIThread = new AsyncAPI();
APIThread.execute();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
继承FileOutputStream FileInputStream,我相信问题所在:
public class SaveData implements View.OnClickListener
{
//String totalScoreString = String.valueOf(totalScoreNum);
@Override
public void onClick(View v) {
try {
FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
fou.write(totalScoreNum);
fou.close();
// Toast Confirm
Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadData()
{
FileInputStream fis = null;
try {
fis = openFileInput("scoreFile.txt");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
首次运行应用程序时,分数将返回最初填充的字符串“test string”,但一旦加载并保存实际分数,它将返回“0”。任何帮助或解释将不胜感激!
答案 0 :(得分:0)
您是否尝试过为输入和输出流提供完整路径?
例如&#34; /sdcard/Downloads/myapp/scoreFile.txt"
也不要对路径进行硬编码,使用Environment.getExternalStorageDirectory(),我认为这将返回一个等于&#34; / sdcard /&#34;
的File对象或字符串路径不要忘记为外部读写添加权限