从sqlite数据库类传递单个字符串值到android中的另一个类?

时间:2012-12-21 12:35:56

标签: android sqlite

我正在为android制作一个hangman应用程序我的问题是我需要将一个单词从我的数据库类传递到我的游戏类中,我知道游戏类的工作原理是因为我创建它只是最初使用数组列表,然后我创建了一个我也知道的数据库类,因为我可以添加单词并查看它们。

问题是我似乎无法从我的数据库课程中传递一个单词到我的游戏课程,我现在花了3天时间尝试了很多不同的东西,但没有运气,可以给予任何帮助会很惊人,因为我觉得我可能需要很快把窗户扔出窗外。

这是我的数据库类

package com.example.hangpract;



import java.util.ArrayList;
import java.util.Random;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.ArrayAdapter;

public class mysteryWordDB {


    public static final String KEY_WORD="mystery_word";

    public static ArrayList<String> results = new ArrayList<String>();  
    private static final String DATABASE_NAME="HangManWords";
    private static final String DATABASE_TABLE="wordsTable";
    private static final int DATABASE_VERSION= 1;

    private DbHelper ourHelper;
    private final Context ourContext;
    private static SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper{

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                    KEY_WORD + " TEXT NOT NULL);"
                    );


        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);

        }

    }

public mysteryWordDB(Context c){
    ourContext = c;
}

public mysteryWordDB open()throws SQLException{
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

public void close(){
    ourHelper.close();
}
//method to add user words from the edit word class

public long createEntry(String word) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(KEY_WORD, word);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);

}
//method to display all words in the view class

public String getData() {
    // TODO Auto-generated method stub
    String[] columns = new String[]{KEY_WORD};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";


    int iWord = c.getColumnIndex(KEY_WORD);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
        result = result +  c.getString(iWord) + "\n";
    }
    return result;
}

//method that should set up an array of the words in the data base, can't get this bit right

public void getMysteryWord() {
    Cursor c = ourDatabase.rawQuery("SELECT KEY_WORD FROM " +
            DATABASE_TABLE, null);

    if (c != null ) {
        if  (c.moveToFirst()) {
            do {
                String mystWord = c.getString(c.getColumnIndex(KEY_WORD));

                results.add(mystWord.toString());
            }while (c.moveToNext());
        }}
    }



//method that is called from the game class to get a random string from the array to use in the game

    public static String  word(){
        Random rand = new Random();
    int i=rand.nextInt(results.size());
    if(i >-1)return results.get(i);

    return results.get(i);

}
}

问题领域是我尝试过的最新方法:

//method that should set up an array of the words in the data base, can't get this bit right

public void getMysteryWord() {
    Cursor c = ourDatabase.rawQuery("SELECT KEY_WORD FROM " +
            DATABASE_TABLE, null);

    if (c != null ) {
        if  (c.moveToFirst()) {
            do {
                String mystWord = c.getString(c.getColumnIndex(KEY_WORD));

                results.add(mystWord.toString());
            }while (c.moveToNext());
        }}
    }



//method that is called from the game class to get a random string from the array to use in the game

    public static String  word(){
        Random rand = new Random();
    int i=rand.nextInt(results.size());
    if(i >-1)return results.get(i);

    return results.get(i);

}
}

然后这是需要传入KEY_WORD随机实例的游戏类:

package com.example.hangpract;




import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;



    public class game extends Activity implements OnClickListener {


        private ImageView hangimg;
        private TextView word;
        private String mysteryWord = mysteryWordDB.word();
        private int numWrongGuesses;


        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.game);

            bindviews();
            inistMystword();
            initWrongGuesses();



            //set button views for letters
            Button aButton = (Button)
                    this.findViewById(R.id.buttonA);

                    aButton.setOnClickListener(this);


            Button bButton = (Button)
                    this.findViewById(R.id.buttonB);

                    bButton.setOnClickListener(this);

            Button cButton = (Button)
                    this.findViewById(R.id.buttonC);

                    cButton.setOnClickListener(this);

            Button dButton = (Button)
                    this.findViewById(R.id.buttonD);

                    dButton.setOnClickListener(this);

            Button eButton = (Button)
                    this.findViewById(R.id.buttonE);

                    eButton.setOnClickListener(this);

            Button fButton = (Button)
                    this.findViewById(R.id.buttonF);

                    fButton.setOnClickListener(this);

            Button gButton = (Button)
                    this.findViewById(R.id.buttonG);

                    gButton.setOnClickListener(this);

            Button hButton = (Button)
                    this.findViewById(R.id.buttonH);

                    hButton.setOnClickListener(this);

            Button iButton = (Button)
                    this.findViewById(R.id.buttonI);

                    iButton.setOnClickListener(this);

            Button jButton = (Button)
                    this.findViewById(R.id.buttonJ);

                    jButton.setOnClickListener(this);

            Button kButton = (Button)
                    this.findViewById(R.id.buttonK);

                    kButton.setOnClickListener(this);

            Button lButton = (Button)
                    this.findViewById(R.id.buttonL);

                    lButton.setOnClickListener(this);

            Button mButton = (Button)
                    this.findViewById(R.id.buttonM);

                    mButton.setOnClickListener(this);

            Button nButton = (Button)
                    this.findViewById(R.id.buttonN);

                    nButton.setOnClickListener(this);

            Button oButton = (Button)
                    this.findViewById(R.id.buttonO);

                    oButton.setOnClickListener(this);

            Button pButton = (Button)
                    this.findViewById(R.id.buttonP);

                    pButton.setOnClickListener(this);

            Button qButton = (Button)
                    this.findViewById(R.id.buttonQ);

                    qButton.setOnClickListener(this);

            Button rButton = (Button)
                    this.findViewById(R.id.buttonR);

                    rButton.setOnClickListener(this);

            Button sButton = (Button)
                    this.findViewById(R.id.buttonS);

                    sButton.setOnClickListener(this);

            Button tButton = (Button)
                    this.findViewById(R.id.buttonT);

                    tButton.setOnClickListener(this);

            Button uButton = (Button)
                    this.findViewById(R.id.buttonU);

                    uButton.setOnClickListener(this);

            Button vButton = (Button)
                    this.findViewById(R.id.buttonV);

                    vButton.setOnClickListener(this);

            Button wButton = (Button)
                    this.findViewById(R.id.buttonW);

                    wButton.setOnClickListener(this);

            Button xButton = (Button)
                    this.findViewById(R.id.buttonX);

                    xButton.setOnClickListener(this);

            Button yButton = (Button)
                    this.findViewById(R.id.buttonY);

                    yButton.setOnClickListener(this);

            Button zButton = (Button)
                    this.findViewById(R.id.buttonZ);

                    zButton.setOnClickListener(this);




            //sets button view for new game
            Button newbutton = (Button)
                    this.findViewById(R.id.buttNew);
                    newbutton.setOnClickListener(this);
            //sets button view for menu
            Button menuButton = (Button)
                    this.findViewById(R.id.buttMenu);
                    menuButton.setOnClickListener(this);
        }


        //set actions on buttons
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.buttonA:

                validate('a');
                    break;
                case R.id.buttonB:

                validate('b');
                break;
                case R.id.buttonC:

                    validate('c');
                    break;
                case R.id.buttonD:

                    validate('d');
                    break;

                case R.id.buttonE:

                    validate('e');
                    break;

                case R.id.buttonF:

                    validate('f');
                    break;

                case R.id.buttonG:

                    validate('g');
                    break;

                case R.id.buttonH:

                    validate('h');
                    break;

                case R.id.buttonI:

                    validate('i');
                    break;

                case R.id.buttonJ:

                    validate('j');
                    break;

                case R.id.buttonK:

                    validate('k');
                    break;

                case R.id.buttonL:

                    validate('l');
                    break;

                case R.id.buttonM:

                    validate('m');
                    break;

                case R.id.buttonN:

                    validate('n');
                    break;

                case R.id.buttonO:

                    validate('o');
                    break;

                case R.id.buttonP:

                    validate('p');
                    break;

                case R.id.buttonQ:

                    validate('q');
                    break;

                case R.id.buttonR:

                    validate('r');
                    break;

                case R.id.buttonS:

                    validate('s');
                    break;

                case R.id.buttonT:

                    validate('t');
                    break;

                case R.id.buttonU:

                    validate('u');
                    break;

                case R.id.buttonV:

                    validate('v');
                    break;

                case R.id.buttonW:

                    validate('w');
                    break;

                case R.id.buttonX:

                    validate('x');
                    break;

                case R.id.buttonY:

                    validate('y');
                    break;

                case R.id.buttonZ:

                    validate('z');
                    break;




            case R.id.buttNew:


                Intent newGame = new Intent(v.getContext(), game.class);
                startActivityForResult(newGame,0);

            break;

            case R.id.buttMenu:
                Intent menu = new Intent(v.getContext(), MainActivity.class);
                startActivityForResult(menu,0);

            }


        }
        //get mystery word
        public void inistMystword(){
            word = (TextView) findViewById(R.id.mysteryword);
            word.setText(mysteryWord);

            word.setText(underscore());
        }


        //method to display the mystery word as underscores
        public String underscore() {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < mysteryWord.length(); i++) {
            result.append("_ ");
            }
            return result.toString();
            }


        //method to validate guess



        private void validate(char ch) {
            if (mysteryWord.indexOf(ch)== -1){


                if (numWrongGuesses < 6){
                    numWrongGuesses++;
                }
                checkLose();
                }
            else {
            if (numWrongGuesses <6){
                updateMystWord(ch);
                checkWin();
            } else {
                checkLose();
            }

        }}






            //method to reveal letter

            private void updateMystWord(char ch) {
                char[] updatedWord =
                word.getText().toString().toCharArray();
                for (int i = 0; i < mysteryWord.length(); i++) {

                if (ch == mysteryWord.charAt(i)) 
                updatedWord[i * 2] = mysteryWord.charAt(i);
                word.setText(new String(updatedWord));

                }



            }
            //sets number of wrong guesses to zero at game start
        private void initWrongGuesses() {
            numWrongGuesses = 0;
        }




        //checks when game is lost and displays lose screen

        private void checkLose() {
             if (numWrongGuesses == 6)
                hangimg.setImageResource(R.drawable.lose);


            }
        //checks when game is won and displays win screen
        private void checkWin() {
            if (word.getText().toString().indexOf("_") == -1) {
            hangimg.setImageResource(R.drawable.win);
            }
            }
        //binds the views
        private void bindviews(){
            hangimg = (ImageView)
                    this.findViewById(R.id.imageView1);
        }

      }

游戏类肯定有效,数据库也可以工作,我只是无法弄清楚我在错误的地方尝试传递单个值来在游戏类中使用任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

在数据库文件中创建一个方法为。

static String str = "data";   // ASSUME TO PASS THIS STRING

public static String passData()
{
    return str;
}

在您的活动课程中执行此操作。

  String str = dbClassName.passData();

多数民众赞成。