如何在SQLite中编写/覆盖和读取数据整数并在TextView中显示?

时间:2016-01-26 17:09:21

标签: java android sqlite

我有这个应用程序,当调用MainActivity时,文本视图将显示当前数据信息或更确切地说是分数,如果COL1(星号)为空,则应在列星中写入0。然后当播放并达到分数应该改变的时候,比如添加分数,它应该覆盖列中的数据。

这是我的DatabaseHelper的代码

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

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "star.db";
public static final String TABLE_NAME = "stars_table";
public static final String COL1 = "stars";


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table" + TABLE_NAME + "("+COL1+")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
    onCreate(db);
}

public boolean insertData(Integer stars){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL1, stars);
    long result =  db.insert(TABLE_NAME, null, contentValues);
    if(result == -1)
        return false;
    else
        return true;
}

public Cursor getAllData(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select stars from" + TABLE_NAME, null);
    return res;
}

}

那么如何在textview中显示它,以及如何读取数据,计算,然后用新数据覆盖它?

至于我的MainActivity

public class MainActivity extends Activity {

  private static TextView txt_stars;
  DatabaseHelper mydb;

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

    mydb = new DatabaseHelper(this);

    txt_stars = (TextView) findViewById(R.id.txtStars);
    //this where the score will show
  }

  public void onButtonClickListener() {
    //some buttons
    //game start
  }
}

至于将计算答案是否正确的活动

public class OneFifteenActivity extends Activity {

  private static Button button_next;
  private static TextView txt_ans;
  final Context context = this;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.one_fifteen);
    onButtonClickListener();
  }
  public void onButtonClickListener() {

    txt_ans = (EditText) findViewById(R.id.edittxtAns);
    button_next = (Button) findViewById(R.id.btnNext);
    button_next.setOnClickListener(
      new View.OnClickListener() {@
        Override
        public void onClick(View v) {
          if (txt_ans.getText().toString().equals("dai")) {

            AlertDialog.Builder alert = new AlertDialog.Builder(context);
            alert.setMessage("Message here");
            alert.setCancelable(false);
            alert.setPositiveButton("next", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                  Intent nextForm = new Intent(".MainActivity");
                  startActivity(nextForm);
                  //computation here

                } 
            }); 
            AlertDialog alertDialog = alert.create();
            alertDialog.show();

          } else {
            AlertDialog.Builder alert = new AlertDialog.Builder(context);
            alert.setMessage("Message here");
            alert.setCancelable(false);
            alert.setPositiveButton("next", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                  AlertDialog.Builder alert = new AlertDialog.Builder(context);
                  alert.setTitle("Congratulations!");
                  alert.setMessage("You have earned 50 stars");
                  alert.setCancelable(false);
                  alert.setPositiveButton("next", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Intent nextForm = new Intent(".MainActivity");
                        startActivity(nextForm);
                      }
                  });
                  AlertDialog alertDialog = alert.create();
                  alertDialog.show();
                } 
            }); 
            AlertDialog alertDialog = alert.create();
            alertDialog.show();
          }
        }
      }
    );
  }

}

我已经被困在这里好几个星期,有人能帮助我吗?

非常感谢。

4 个答案:

答案 0 :(得分:1)

我认为更新你的表并添加点你可以创建一个与此类似的功能“添加点”:

public void _addPoints(){ 
db.rawQuery("UPDATE ? FROM "+TABLE_NAME+" SET ?=?+1", new String[]{COL1, COL1, COL1}); //Here I don't know if you have multiple users or players where this query must be used, if there are 
please add the needed WHERE x=y and subsitute the 1 for your desired increase value.
}

现在要在textView中显示你必须读取的值,你可以创建一个返回星数的函数:

Cursor c=db.query(TABLE_NAME, COL1, null, null, null, null); //if you have only 1 player, if you have more you must fill the WHERE parameters (check API for that).
c.moveToNext();
int points=c.getInt(0); //or anything else you need
return points;

然后设置textView文本:

txt_stars.setText(Integer.toString(points));

如果这有帮助,请告诉我,也许我并不理解这个问题。

答案 1 :(得分:1)

根据您的要求,要使DatabaseHelper类成为子类,您可以这样继续:

class Functions{
public update (){
//the update code I already provided
}
class DatabaseHelper extends SQLiteOpenHelper{
//the code of your databaseHelper
}
}

正如您所看到的,DatabaseHelper类位于Function类中,称为子类,它的优点是您可以使用所有变量(即使它们是私有的)在Functions类中执行您想要的任何功能。除了Functions类之外,DatabaseHelper类的函数和类DatabseHelper不能在程序中的任何其他地方使用。

答案 2 :(得分:0)

Loader类将监视您的数据源并提供新结果。如果你实施

LoaderManager.LoaderCallbacks<Cursor>
在您的活动中的

接口,您将能够从传递给onLoadFinished覆盖方法的光标获取数据,并从那里更新TextViews。

http://www.vogella.com/tutorials/AndroidSQLite/article.html#loader_definition

答案 3 :(得分:0)

查看一些可以使用此代码的信息:

private String[] checkAll(){
    String tam[] = new String[5];
    Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
    if (cursor.getCount() != 0) {
        if (cursor.moveToFirst()) {
            do {
                tam[0] = cursor.getString(cursor
                        .getColumnIndex("_id"));

                tam[1] = cursor.getString(cursor
                        .getColumnIndex("column1Name"));

                tam[2] = cursor.getString(cursor
                        .getColumnIndex("column2Name"));

                tam[3] = cursor.getString(cursor
                        .getColumnIndex("column3Name"));

                tam[4] = cursor.getString(cursor
                        .getColumnIndex("column4Name"));
            } while (cursor.moveToNext());
        }
    } else {
        // Toast.makeText(getApplicationContext(), "No data", Toast.LENGTH_LONG).show();
    }
    cursor.close();
    return tam;
}// checkAll

然后在你的主动或任何你想要的地方

String arrray[] = checkAll();
textview.setText(arrray[SomePosition]);
Toast.makeText(getApplicationContext,"HERE IS A MESSAGE TO THE USER "+arrray[SomePosition], Toast.LENGTH_LONG).show();

最后,如果你想更新,请使用:

String[] args = new String[]{"1"}; // String to complete the condition(where)
        db.execSQL("UPDATE " + TABLE_NAME + " SET Column1Name='" + someVariable + "', Column2Name='"+SomeOtherVariable+"' WHERE idNameColumn=?", args);