不等待计时器让用户点击Android测验游戏中的答案,然后快速运行

时间:2017-06-11 20:34:28

标签: android android-sqlite

我的导航抽屉带有菜单导航项目。现在我定义了一个项目,当点击它时,打开一个新的活动。在这个活动中,我设计了开始标志游戏测验的布局。当点击玩游戏按钮时,游戏开始如此之快,无需等待点击用户,完。在“PlayGame”布局中,我为标志定义了一个imageView,为答案定义了4个按钮。标志名称和答案来自外部数据库。当我调试应用程序时,countDownTimer实现空值,一切正常,Just Timer不等待使用,并且播放测验是如此之快。

这是我的数据库。

WorldCountryDatabase

webpack.config.js

这是我的ChoicGame课程。

ChoiceGame

const path = require('path')
const resolve = p => path.resolve(__dirname, p)
const webpack = require('webpack')

const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const isProd = process.env.NODE_ENV === 'production'

module.exports = {
    entry: {
        app: [
            resolve('src/js/main.js')
        ]
    },
    output: {
        path: resolve('public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: isProd
                    ? ExtractTextPlugin.extract({
                        fallback: 'style-loader',
                        use: ['css-loader', 'sass-loader']
                    })
                    : ['style-loader', 'css-loader', 'sass-loader']
            },
            {
                test: /\.js|jsx$/,
                use:  'babel-loader',
                exclude: /node_modules/
            }
        ]
    }
}

if (isProd) {
    module.exports.devtool = '#source-map'
    module.exports.output = Object.assign({}, module.exports.output, {
        filename: '[name].[chunkhash].js',
        chunkFilename: '[id].[chunkhash].js'
    })
    module.exports.plugins = (module.exports.plugins || []).concat([
        new ExtractTextPlugin({
            filename: '[name].[contenthash].css'
        }),
        new HtmlWebpackPlugin({
            template: 'index.ejs',
            inject: true,
            chunksSortMode: 'dependency'
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true
        }),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.LoaderOptionsPlugin({
            minimize: true,
            debug: false
        })
    ])
} else {
    module.exports.entry.app = [
        'webpack-hot-middleware/client',
        'react-hot-loader/patch'
    ].concat(module.exports.entry.app)
    module.exports.devtool = '#eval-source-map'
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.HotModuleReplacementPlugin()
    ])
}

}

最后这是我的PlayingGame课程。

PlayingGmae

public class WorldCountryDatabase extends SQLiteOpenHelper {

private static final String TAG = "databaseHelper";
private static final String DB_NAME = "worldCountries.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "country";
private static String DB_PATH = "";
private Context mContext;
private SQLiteDatabase database;

public WorldCountryDatabase(Context context) {
    super(context, DB_NAME, null, DB_VERSION);

    DB_PATH = context.getDatabasePath(DB_NAME).getPath();

    File file = new File(DB_PATH + "worldCountries.db");
    if (file.exists())

        openDataBase();

    this.mContext = context;


}

public void createDatabase() {

    boolean dbExist = checkDatabase();

    if (dbExist) {

        Log.d("MIN1", "Database already Exist");

    } else {
        this.getReadableDatabase();
    }
    try {
        copyDataBase();
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("MIN2", e.getMessage());

    }


}

private boolean checkDatabase() {
    SQLiteDatabase checkDB = null;

    try {


        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    } catch (SQLiteException e) {
        e.printStackTrace();
        Log.d("MIN3", e.getMessage());

    }
    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null;
}

public synchronized void close() {
    if (database != null) {
        database.close();
        SQLiteDatabase.releaseMemory();
    }
    super.close();

}


private void copyDataBase() throws IOException {

    try {


        InputStream in = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream out = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;

        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }


        out.flush();
        out.close();
        in.close();

        Log.d("MIN4", "Database copy");


    } catch (SQLiteException e) {
        Log.d("MIN5", e.getMessage());

    }
}

public Cursor QueryData(String query) {
    return database.rawQuery(query, null);
}


@Override
public void onCreate(SQLiteDatabase db) {

    Log.d("MIN6", "onCreate");



}

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


   db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);

    Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion +
            "Which will destroy all  oldest data");


    if (newVersion > oldVersion) {
        try {
            copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

public void openDataBase() {

    String myPath = DB_PATH + DB_NAME;
    database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    Log.d("MIN7", "Opened database");


}

// CRUD Table
public List<Questions> getAllQuestions() {

    List<Questions> questionsList = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c;

    try {
        c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null);
        if (c == null) return null;
        c.moveToFirst();
        do {
            int Id = c.getInt(c.getColumnIndex("id"));
            String Image = c.getString(c.getColumnIndex("Image"));
            String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
            String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
            String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
            String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
            String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));

            Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
            questionsList.add(question);


                } while (c.moveToNext());
                c.close();


    } catch (Exception e) {
        e.printStackTrace();
    }

    database.close();
    return questionsList;
}



// Insert Score to Ranking table.
public void insertScore(double score) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put("Score", score);
    db.insert("Ranking", null, content);
}

// Get score and sort Ranking.
public List<Ranking> getRanking() {

    List<Ranking> rankingList = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c;
    try {
        c = db.rawQuery("SELECT * FROM country ORDER BY Score DESC;", null);
        if (c == null) return null;
        c.moveToFirst();
        do {

            int ID = c.getInt(c.getColumnIndex("id"));
            int Score = c.getInt(c.getColumnIndex("Score"));

            Ranking ranking = new Ranking(ID, Score);
            rankingList.add(ranking);


        } while (c.moveToNext());
        c.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    db.close();
    return rankingList;
}



public int getPlayCount(int level)
{
    int result = 0;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c;
    try{
        c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null);
        if(c == null) return 0;
        c.moveToNext();
        do{
            result  = c.getInt(c.getColumnIndex("PlayCount"));
        }while(c.moveToNext());
        c.close();
    }catch (Exception ex)
    {
        ex.printStackTrace();
    }
    return result;
}

public void updatePlayCount(int level,int playCount)
{
    String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level);
    database.execSQL(query);
}

}

首先,我在WorldCountryDatabase中定义了“ getQuestionMode ”方法,但应用程序没有转到 PlayingCountryGame 布局并打开ScoreGame类。在 PlayingCountryGame 类中定义“getQuestionMode”方法之后。我希望能说清楚我的问题。

请帮助我,好朋友。 谢谢给大家。

1 个答案:

答案 0 :(得分:0)

我认为你的问题是构造函数和值。

https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)

构造函数需要的时间是毫秒而不是秒。你需要将1秒转换为1000毫秒。

final static long INTERVAL = 1000; // 1 second -> 1000 milliseconds
final static long TIMEOUT = 7000; // 7 seconds -> 7000 milliseconds

和params的顺序。

如果你想等待7秒,构造函数是:

countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL){ ... }