繁体   English   中英

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

[英]How to write/overwrite and read data integer in SQLite and show in TextView?

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

这是我的数据库助手的代码

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
  }
}

至于Activity,它将计算答案是否正确

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();
          }
        }
      }
    );
  }

}

我已经被困在这里好几个星期了,有人可以帮我吗?

非常感谢。

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

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));

让我知道这是否有帮助,也许我没有像我想的那样理解这个问题。

根据您的要求,要使DatabaseHelper类成为子类,可以像下面这样进行:

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

如您所见,类DatabaseHelper类在函数类内部,即子类,它的优点是您可以使用所有变量(即使它们是私有的)和函数来在函数类中执行所需的任何函数。 DatabaseFunctioner类和DatabseHelper类不能在程序中的其他任何地方使用,除了Functions类。

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

LoaderManager.LoaderCallbacks<Cursor>

界面,您将能够从传递给onLoadFinished覆盖方法的游标中获取数据,并从那里也更新TextViews。

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

要查看一些信息,可以使用以下代码:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM