无法保存我的分数 - 安卓

时间:2014-08-01 15:01:02

标签: java android eclipse

首先,我是新手。 我正在创建一个应用程序,你有15秒的时间尽可能多地得分,然后我希望它能保存你的最终得分,但我无法做到,这里是代码:

package com.cannongaming.supertouch;

import java.io.FileOutputStream;
import java.util.concurrent.TimeUnit;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.os.CountDownTimer;

public class StartActivity<TextView> 
                extends ActionBarActivity 
                implements OnClickListener {
    Button buttonTap, buttonLet;
    TextView textScore, textTime;
    int score=0;
    byte[] scoreBytes;
    String filename = "myscore";
    int timer = 15000; // 1000 = 1 second 

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

        //1
        buttonTap = (Button)findViewById(R.id.buttonTap);
        buttonLet = (Button)findViewById(R.id.buttonLet);
        textScore = (TextView)findViewById(R.id.textScore);
        textTime = (TextView)findViewById(R.id.textTime);
        scoreBytes[0] = (byte) score;
        scoreBytes[1] = (byte) (score >> 8);
        scoreBytes[2] = (byte) (score >> 16);
        ((android.widget.TextView) textTime).setText("00:00:15");

        //2
        ((android.widget.TextView) textScore).setText(String.valueOf(score));

        //3
        buttonTap.setOnClickListener(this);

    buttonLet.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {

        final CounterClass timer = new CounterClass(15000, 1000);
        timer.start();
        score++;
        ((android.widget.TextView) textScore).setText(String.valueOf(score));
        view.setVisibility(View.GONE);
    }});
    }
    public void onClick(View src){
        switch(src.getId()){
        case R.id.buttonTap:
            score++;
            ((android.widget.TextView) textScore).setText(String.valueOf(score));
            break;
        }
    }

    public class CounterClass extends CountDownTimer {

        public CounterClass(long millisInFuture, long countDownInterval){
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        public void onTick(long millisUntilFinished){

            long millis = millisUntilFinished;
            String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            System.out.println(hms);
            ((android.widget.TextView) textTime).setText(hms);
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            FileOutputStream outputStream = getApplicationContext().openFileOutput(filename, Context.MODE_PRIVATE);
            outputStream.write(scoreBytes);
            outputStream.close();
            Intent i = new Intent(getApplicationContext(), ScoreActivity.class);
            startActivity(i);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.start, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

然后我有3个错误:

Description Resource    Path    Location    Type
Unhandled exception type FileNotFoundException  StartActivity.java  /SuperTouch/src/com/cannongaming/supertouch line 88 Java Problem


Description Resource    Path    Location    Type
Unhandled exception type IOException    StartActivity.java  /SuperTouch/src/com/cannongaming/supertouch line 89 Java Problem


Description Resource    Path    Location    Type
Unhandled exception type IOException    StartActivity.java  /SuperTouch/src/com/cannongaming/supertouch line 90 Java Problem

然后我将onFinish更改为:

public void onFinish() {
        // TODO Auto-generated method stub
        try {
        FileOutputStream outputStream = getApplicationContext().openFileOutput(filename, Context.MODE_PRIVATE);
        outputStream.write(scoreBytes);
        outputStream.close();
        } catch (Exception e) {
              e.printStackTrace();
            }
        Intent i = new Intent(getApplicationContext(), ScoreActivity.class);
        startActivity(i);
    }

并且没有任何错误,但是当我打开我的应用程序时,它说它被迫关闭。请帮帮我!

2 个答案:

答案 0 :(得分:1)

您可以使用 SharedPreferences ...

http://developer.android.com/reference/android/content/SharedPreferences.html

了解更多信息
SharedPreferences wmbPreference1,wmbPreference2;    
SharedPreferences.Editor editor;

//wmbPreference for Shared Prefs that lasts forever
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);  

//installsp for Shared Prefs that lasts only just once each time program is running
wmbPreference2 =getApplicationContext().getSharedPreferences("install_code_prefs",Activity.MODE_PRIVATE);

保存值

SharedPreferences.Editor editor = wmbPreference1.edit();
editor.putString("MYKEY", "12345");
editor.commit();

您可以检索

之类的值
String Phonenumber = wmbPreference1.getString("MYKEY", ""); 

其中 MYKEY是您可以通过其识别值的键名。

答案 1 :(得分:0)

您通过放置catch来缓解编译错误。

您现在遇到的问题肯定是NullPointerException,只要您声明byte[] scoreBytes;,但不要在下面的任何位置初始化它。像这样进行decalration,你将是一个例外:

byte[] scoreBytes = new byte[3];

修改

现在提出建议:

  • 以适当方式记录例外情况。我总是建议使用android工具来跟踪异常,而不是将它们转储到控制台。因此,我建议您替换重构解决方案的这一行:

    e.printStackTrace();
    

    对此:

    Log.e("TAG", "An exception while opoening the output file", e);
    
  • 尝试自己解决问题。查看Logcat中的堆栈跟踪。 logcat是Eclipse中最重要的android视图之一。如果您在默认情况下没有看到它,请通过转到Window - &gt;来显示它。其他 - &gt; android - &gt; logcat的。它将显示代码中发生的错误(例如当前失败的东西)