简体   繁体   English

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

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

I have this app that when the MainActivity is called, the a textview will show the current data information or rather the score, if the COL1 (stars) is null it should write 0 in the column stars. 我有这个应用程序,当调用MainActivity时,一个textview将显示当前数据信息或更确切地说是分数,如果COL1(星号)为null,则应在星号列中写入0。 Then when played and reached it's point when the score should change, like adding score, it should overwrite the data in the column. 然后,当播放并到达分数时,应该改变分数,例如添加分数,它将覆盖列中的数据。

Here's my code for my 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;
}

}

So how can I show it in textview and also how to read the data, compute, then overwrite it with new data? 那么如何在textview中显示它,以及如何读取数据,计算然后用新数据覆盖呢?

As for my MainActivity 至于我的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
  }
}

And as for the Activity which will compute if the answer is correct 至于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();
          }
        }
      }
    );
  }

}

I've been stuck here for weeks, can somebody help me? 我已经被困在这里好几个星期了,有人可以帮我吗?

Thanks a lot. 非常感谢。

I think to update your table and add points you can create a function "add points" that works similar to this: 我认为要更新表并添加点,您可以创建一个功能类似于此功能的“添加点”:

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

Now to show in a textView you must read the value you can make a function that returns the number of stars: 现在要显示在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;

And then set the textView text: 然后设置textView文本:

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

Let me know if this helped, maybe I didn't understand the question as well as I thought. 让我知道这是否有帮助,也许我没有像我想的那样理解这个问题。

As you requested, to make the DatabaseHelper class a subclass you can proceed like this: 根据您的要求,要使DatabaseHelper类成为子类,可以像下面这样进行:

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

As you can see, the class DatabaseHelper is inside the class Functions, that is called a subclass, it has the advantage you can do any function you want in the Functions class using all the variables (even if they are private) and functions of the DatabaseHelper class, and the class DatabseHelper cannot be used anywhere else in the program except from the Functions class. 如您所见,类DatabaseHelper类在函数类内部,即子类,它的优点是您可以使用所有变量(即使它们是私有的)和函数来在函数类中执行所需的任何函数。 DatabaseFunctioner类和DatabseHelper类不能在程序中的其他任何地方使用,除了Functions类。

The Loader class will monitor your data source and deliver the new results. Loader类将监视您的数据源并提供新结果。 If you implement the 如果您实施

LoaderManager.LoaderCallbacks<Cursor>

interface in your activity, you will then be able to get your data from the cursor that is passed to the onLoadFinished override method and update your TextViews from there also. 界面,您将能够从传递给onLoadFinished覆盖方法的游标中获取数据,并从那里也更新TextViews。

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

to check out some information you can use this code: 要查看一些信息,可以使用以下代码:

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

then in your mainactivity or wherever you want it 然后在您的主要活动或任何您想要的地方

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

finally, if you want to update, use this: 最后,如果要更新,请使用以下命令:

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