0

您好,我是 android 新手,请您帮我解决我的错误。当我要开始游戏时会发生错误,所以这是我的 logcat 数据库和活动

日志猫

08-06 04:02:31.350:E/AndroidRuntime(8261):致命异常:主要

08-06 04:02:31.350: E/AndroidRuntime(8261): java.lang.RuntimeException: 无法实例化活动 ComponentInfo{com.example.windowcard/com.example.windowcard.Grade1}: java.lang.NullPointerException 08- 06 04:02:31.350: E/AndroidRuntime(8261): 在 android.content.ContextWrapper.getPackageName(ContextWrapper.java:127) 08-06 04:02:31.350: E/AndroidRuntime(8261): 在 com.example。 windowcard.dbHelp.(dbHelp.java:39) 08-06 04:02:31.350: E/AndroidRuntime(8261): at com.example.windowcard.Grade1.(Grade1.java:41)

数据库

package com.example.windowcard;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;


   public class dbHelp extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private static String TAG = "dbHelp";
private static String DB_PATH = "";

private static String DB_NAME = "sample";

private SQLiteDatabase myDataBase; 

private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public dbHelp(Context context) {

    super(context, DB_NAME, null, 1); //

    DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    this.myContext = context;
}   

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * */
public void createDataBase() throws IOException{

    myContext.deleteDatabase(DB_NAME);
    boolean dbExist = checkDataBase();

    if(!dbExist){
        //do nothing - database already exist
        this.getReadableDatabase();
        this.close();
        try{
            copyDataBase();
            Log.e(TAG, "create Database database created"); 
        }
        catch (IOException e){
            throw new Error ("Error Copying Database");

        }

    }

}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase(){


    File dbFile = new File (DB_PATH + DB_NAME);
    Log.v("dbFile", dbFile + " " + dbFile.exists());
    return dbFile.exists();

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public boolean openDataBase() throws SQLException{

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
    // myDatabase =
    SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    return myDataBase != null;

}

@Override
public synchronized void close() {

    if(myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.

public Cursor getAllGrade1(){

    this.openDataBase();
    String sql = "Select * from gr1";
    Cursor  c = myDataBase.rawQuery(sql, null);
    c.moveToFirst();
    return c;
}
public String getScore(int score){
    this.openDataBase();
    String sql = "SELECT * FROM gr1 WHERE _id =" + score;
    Cursor c = myDataBase.rawQuery(sql, null);
    c.moveToFirst();
    return c.getString(c.getColumnIndex("score"));
}
public String getMistakes(int Errors){
    this.openDataBase();
    String sql="SELECT * FROM gr1 WHERE _id=" + Errors;
    Cursor c = myDataBase.rawQuery(sql, null);
    c.moveToFirst();
    return c.getString(c.getColumnIndex("Errors"));
}

    }

活动

            package com.example.windowcard;

            import java.util.ArrayList;
            import java.util.Collections;
            import android.app.Activity;
            import android.app.AlertDialog;
            import android.content.DialogInterface;
            import android.content.Intent;
            import android.database.Cursor;
            import android.media.MediaPlayer;
            import android.os.Bundle;
            import android.os.Handler;
            import android.view.View;
            import android.view.View.OnClickListener;
            import android.widget.Button;
            import android.widget.EditText;
            import android.widget.TextView;
            import android.widget.Toast;

            public class Grade1 extends Activity implements OnClickListener {
            TextView tvQuestion,tvQuestionId,tvPlayer1,tvScore,tvMissCount;
            EditText et;
            Button submit,next,start;
            Cursor c;
            MediaPlayer sonic;
            Handler mHandler = new Handler();
            long startTime;
            TextView timer,timems;
            long elapsedTime;
            final int REFRESH_RATE = 100;
            String hours,minutes,seconds,milliseconds;
            long secs,mins,hrs,msecs;
            boolean stopped = false;
            String s,timers;
            int score=1;
            int miss=1;
            dbHelp dbh = new dbHelp(this);
            ArrayList<Integer> rdm = new ArrayList<Integer>();
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.grade1);
                sonic = MediaPlayer.create(Grade1.this,R.raw.sonic);
                sonic.start();
                sonic.setLooping(true);
                sonic.setVolume(100, 100);
                initialize();   

                }
            public void updateTimer (float time){
                secs = (long)(time/1000);
                mins = (long)((time/1000)/60);
                hrs = (long)(((time/1000)/60)/60);


                secs = secs % 60;
                seconds=String.valueOf(secs);
                if(secs == 0){
                    seconds = "00";
                }
                if(secs <10 && secs > 0){
                    seconds = "0"+seconds;
                }



                mins = mins % 60;
                minutes=String.valueOf(mins);
                if(mins == 0){
                    minutes = "00";
                }
                if(mins <10 && mins > 0){
                    minutes = "0"+minutes;
                }


                hours=String.valueOf(hrs);
                if(hrs == 0){
                    hours = "00";
                }
                if(hrs <10 && hrs > 0){
                    hours = "0"+hours;
                }


                milliseconds = String.valueOf((long)time);
                if(milliseconds.length()==2){
                    milliseconds = "0"+milliseconds;
                }
                if(milliseconds.length()<=1){
                    milliseconds = "00";
                }
                //milliseconds = milliseconds.substring(milliseconds.length(), milliseconds.length());

                (timer = (TextView)findViewById(R.id.tvTime)).setText(hours + ":" + minutes + ":" + seconds);
                //((TextView)findViewById(R.id.tvTimeMs)).setText(":" + milliseconds);
            }
            public Runnable startTimer = new Runnable() {
                   public void run() {
                       elapsedTime = System.currentTimeMillis() - startTime;
                       updateTimer(elapsedTime);
                       mHandler.postDelayed(this,REFRESH_RATE);
                    }
                };
                public void startClick (View view){
                    if(stopped){
                        startTime = System.currentTimeMillis() - elapsedTime;
                    }
                    else{
                        startTime = System.currentTimeMillis();
                    }
                    mHandler.removeCallbacks(startTimer);
                    mHandler.postDelayed(startTimer, 0);
                }
                  public void stopClick (View view){
                        mHandler.removeCallbacks(startTimer);
                        stopped = true;
                    }

                    public void resetClick (View view){
                        stopped = false;
                        ((TextView)findViewById(R.id.tvTime)).setText("00:00:00");
                        //((TextView)findViewById(R.id.tvTimeMs)).setText(":0");
                    }
            private void refresh(){

                c = dbh.getAllGrade1();
                c.moveToPosition(rdm.get(0));
                rdm.remove(0);
                tvScore.setText(dbh.getScore(score));
                tvMissCount.setText(dbh.getMistakes(miss));
                tvPlayer1.setText(s);   
                //tvQuestion.setText(c.getString(c.getColumnIndex("Question")));
                tvQuestion.setText(c.getString(1));
                et.setText("");
            }


            private void initialize() {
                // TODO Auto-generated method stub
                submit= (Button) findViewById(R.id.b1);
                //tvQuestionId = (TextView) findViewById(R.id.tvQuestionId);
                tvPlayer1 = (TextView) findViewById(R.id.tvPlayer1);
                tvScore = (TextView) findViewById(R.id.tvScore);
                tvQuestion = (TextView) findViewById(R.id.tvQuestion);
                tvMissCount = (TextView) findViewById(R.id.tvMissCount);
                start = (Button) findViewById(R.id.bStart);
                et = (EditText) findViewById(R.id.et1);
                Intent z = getIntent();
                s = z.getExtras().getString("PlayerName");
                submit.setVisibility(View.INVISIBLE);
                et.setVisibility(View.INVISIBLE);
                tvQuestion.setVisibility(View.INVISIBLE);
                //Bundle receive = getIntent().getExtras();
                //hold =  receive.getString("PlayerName")

                for(int count=0; count<10; count++){
                    rdm.add(count);
                }
                Collections.shuffle(rdm);
                refresh();
                final MediaPlayer mp = MediaPlayer.create(this, R.raw.answerright);
                final MediaPlayer mp2= MediaPlayer.create(this, R.raw.answerwrong);

                start.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        if (start.isClickable()){
                            et.setVisibility(View.VISIBLE);
                            submit.setVisibility(View.VISIBLE);
                            tvQuestion.setVisibility(View.VISIBLE);
                            startClick(arg0);
                            start.setVisibility(View.INVISIBLE);
                        }
                    }
                });
                submit.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if(et.getText().toString().equalsIgnoreCase("")){
                            Toast.makeText(getApplicationContext(), "You need to answer first the question before proceeding to the next question", Toast.LENGTH_SHORT).show();
                        }else{
                            if (c.getString(c.getColumnIndex("Answer")).equalsIgnoreCase(et.getText().toString())){
                                mp.start();
                                if(score==10){
                                    stopClick(v);
                                     timers = timer.getText().toString();

                                //  dbh.insertRecord1(s, score,timers,miss);
                                    resetClick(v);
                                    AlertDialog diaBox = makneAndShowDialogBox();
                                    diaBox.show();
                                    diaBox.setCanceledOnTouchOutside(false);

                                    //Toast.makeText(getApplicationContext(), "Congratulations!", Toast.LENGTH_LONG).show();
                                    sonic.release();
                                    //Intent a = new Intent(Grade1.this,Menu.class);
                                    //startActivity(a);
                                    //finish();
                                }
                                String Score = tvScore.getText().toString();
                                score++;
                                //String newScore = dbh.getScore(score);
                                refresh();
                            }
                            else{
                            mp2.start();
                            String Miss = tvMissCount.getText().toString();
                            miss++; 
                        //  String newMiss = dbh.getMistakes(miss);
                            refresh();
                            }
                        }




                }
                });
            }
                private AlertDialog makneAndShowDialogBox() {
                    // TODO Auto-generated method stub
                    AlertDialog myDialogBox = new AlertDialog.Builder(this)
                    .setTitle("Congratulations!!") 
                    .setMessage("Congratulations on finishing the game!")
                    .setPositiveButton("Main Menu", new DialogInterface.OnClickListener() { 
                        public void onClick(DialogInterface dialog, int whichButton) { 
                            Intent i = new Intent(Grade1.this,Menu.class);
                            startActivity(i);
                            finish();
                            dialog.dismiss();
                        }

                })

                .create();
                return myDialogBox;






            /** next.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        int count = 0;
                        // TODO Auto-generated method stub
                        if(count==40){
                            Intent a = new Intent(Grade1.this,Menu.class);
                            startActivity(a);
                            finish();
                        }
                        count++;
                    refreshgame();
                    }
                });

            **/


                        }

                        @Override
                        protected void onPause() {
                            // TODO Auto-generated method stub
                            super.onPause();
                            sonic.release();
                            finish();
                        }
                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub

                        }
                        }
4

1 回答 1

0

dbHelp dbh = new dbHelp(this);把这条线放进去OnCreate

于 2013-07-16T08:59:12.750 回答