简体   繁体   中英

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

As for my 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

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:

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:

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:

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.

The Loader class will monitor your data source and deliver the new results. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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