Inserting and fetching data into SQLite [duplicate] - java

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I am having difficulty inserting data into my SQLite database. When I call my addData() method my app crashes. I call my addData method (which is in MainActivity) from my GameView class inside my onTouchEvent method. I need to insert my turns integer into the COLUMN_SCORES column in my database. Appreciate any help!
DatabaseHelper.java:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "scores.db";
public static final String TABLE_NAME = "scores_table";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, SCORE INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_SCORE, score);
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 * from " + TABLE_NAME, null);
return res;
}
public boolean updateData(String id, String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_SCORE, score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}
}
GameView.java:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
public static int turns;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
//Bitmap s = BitmapFactory.decodeResource(getResources(), R.drawable.straight);
//Bitmap dl = BitmapFactory.decodeResource(getResources(), R.drawable.downleft);
int cellContent;
//square = get width / col
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
//Paint paint = new Paint();
//paint.setColor(Color.WHITE);
// paint.setStyle(Paint.Style.FILL);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
canvas.drawText("High score: ", 10, 1280, tp);
}
}
}
//SoundPoolPlayer sound = new SoundPoolPlayer(getContext());
#Override
public boolean onTouchEvent(MotionEvent event) {
//boolean eventConsumed = mGestureDetector.onTouchEvent(event);
//GameView mGameView = new GameView(getApplicationContext());
//if (eventConsumed) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
turns++;
MainActivity main = new MainActivity();
//main.setTurns();
main.addData();
//main.getData();
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
//main.setTurns();
//main.AddData();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
//sound.playShortResource(R.raw.click);
// sound.release();
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getCols() {
return mcolumns;
}
public void setColRow(int columns, int rows) {
this.mcolumns = columns;
this.mrows = rows;
}
public int getTurns() {
return turns;
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private GestureDetector mGestureDetector;
private ImageView imageView;
private RadioGroup radioGroup;
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
String highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
//GameView mGameView = new GameView(getApplicationContext());
this.turns = GameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void addData() {
boolean isInserted = myDb.insertData(test);
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
public void getData() {
Cursor res = myDb.getAllData();
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append(res.getString(1));
}
System.out.println(buffer.toString());
}
}

In your onTouchEvent in the GameView class instead of creating a new instance of MainActivity, which I suspect is casuing the failiure, you could call the insertData method of the DatabaseHelper class directly. e.g. instead of using :-
MainActivity main = new MainActivity();
//main.setTurns();
main.addData();
//main.getData();
Try
DatabaseHelper mydb = new DatabaseHelper(this);
mydb.insertData("test");

Related

pass data from one activity to another and save it

i have two activities, each one have a listview. The first one contain the data and i want the other one to be as a favorite list. Right now i can pass the data with intent but its not saving. it shows when i start the intent but when i exit the second activity and go back to it with a custom button nothing is saved in the listview. Please tell me what to do. here is my code
public class MainActivity extends AppCompatActivity {
DB_Sqlite dbSqlite;
ListView listView;
String fav_name;
long fav_id;
ArrayAdapter adapter;
ArrayList arrayList;
String[] number;
Button button;
StringResourcesHandling srh;
Cursor getAllDataInCurrentLocale,getDataInCurrentLocaleById;
SimpleCursorAdapter favourites_adapter,non_favourites_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
arrayList = new ArrayList<String>();
listView.setAdapter(adapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, cc.class);
startActivity(intent);
}
});
/* Show the resources for demo */
for (String s : StringResourcesHandling.getAllStringResourceNames()) {
Log.d("RESOURCEDATA", "String Resource Name = " + s +
"\n\tValue = " + StringResourcesHandling.getStringByName(this, s)
);
}
dbSqlite = new DB_Sqlite(this);
Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
getAllDataInCurrentLocale.close();
}
#Override
protected void onResume() {
super.onResume();
manageNonFavouritesListView();
}
private void manageNonFavouritesListView() {
getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);
if (non_favourites_adapter == null) {
non_favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
getAllDataInCurrentLocale,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(non_favourites_adapter);
setListViewHandler(listView,false);
} else {
non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
}
}
private void setListViewHandler(ListView listView, boolean favourite_flag) {
if (!favourite_flag) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent = new Intent(MainActivity.this,tc.class);
startActivity(intent);
}
if (i == 1) {
Intent intent = new Intent(MainActivity.this,vc.class);
startActivity(intent);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
startActivity(intent);}
String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
}}
}
public class DB_Sqlite extends SQLiteOpenHelper {
public static final String BDname = "data.db";
public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
public static final String TABLE_FAVOURITES = "mytable";
public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
public static final String FAVOURITES_COL_NAME = "name";
public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */
public DB_Sqlite(#Nullable Context context) {
super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_FAVOURITES + " (" +
FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
FAVOURITES_COL_NAME + " TEXT, " +
FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
")");
/* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
ContentValues cv = new ContentValues();
for (String s: StringResourcesHandling.getAllStringResourceNames()) {
cv.clear();
cv.put(FAVOURITES_COL_NAME,s);
db.insert(TABLE_FAVOURITES,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
onCreate(db);
}
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FAVOURITES_COL_NAME, name);
long result = db.insert(TABLE_FAVOURITES,null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getFavouriteRows(boolean favourites) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
String compare = "<1";
if (favourites) {
compare =">0";
}
return db.query(
TABLE_FAVOURITES,null,
FAVOURITES_COL_FAVOURITEFLAG + compare,
null,null,null,null
);
}
private int setFavourite(long id, boolean favourite_flag) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
}
public int setAsFavourite(long id) {
return setFavourite(id,true);
}
public int setAsNotFavourite(long id) {
return setFavourite(id, false);
}
/* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names */
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
public class cc extends AppCompatActivity {
String fav_name;
long fav_id;
DB_Sqlite dbSqlite;
SimpleCursorAdapter favourites_adapter;
ListView listView1;
ArrayList<String> arrayList1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cc);
listView1 = (ListView) findViewById(R.id.list_view1);
arrayList1 = new ArrayList<String>();
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
if (fav_id == 0) {
}
dbSqlite = new DB_Sqlite(this);
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
if (cursor.moveToFirst()) {
fav_name = cursor.getString(cursor.getColumnIndex(FAVOURITES_COL_NAME));
manageNonFavouritesListView();
}
cursor.close();
}
private void manageNonFavouritesListView() {
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
cursor,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView1.setAdapter(favourites_adapter);
setListViewHandler(listView1,true);
} else {
favourites_adapter.swapCursor(cursor);
}
}
private void setListViewHandler(ListView listView1, boolean b) {
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (fav_id == 1) {
Intent intent = new Intent(cc.this, tc.class);
startActivity(intent);
}
if (fav_id == 2) {
Intent intent = new Intent(cc.this, vc.class);
startActivity(intent);
}
}
});
}
}
public class StringResourcesHandling {
private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
private static boolean loaded = false;
private static Field[] fields = R.string.class.getFields();
private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();
private static void loadStringResources() {
if (loaded) return;
for (Field f: fields) {
if (isResourceNameAllowedPrefix(f.getName())) {
allowedStringResourceNames.add(f.getName());
}
}
loaded = true;
}
private static boolean isResourceNameAllowedPrefix(String resourceName) {
if (allowedStringResourcePrefixes.length < 1) return true;
for (String s: allowedStringResourcePrefixes) {
if (resourceName.substring(0,s.length()).equals(s)) return true;
}
return false;
}
public static String getStringByName(Context context, String name) {
String rv = "";
boolean nameFound = false;
if (!loaded) {
loadStringResources();
}
for (String s: allowedStringResourceNames) {
if (s.equals(name)) {
nameFound = true;
break;
}
}
if (!nameFound) return rv;
return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
}
public static List<String> getAllStringResourceNames() {
if (!loaded) {
loadStringResources();
}
return allowedStringResourceNames;
}
}
note: i get the data in 1st listview from strings.xml
please help me thank u in advance
You can add a column say 'isFavourite' in your db table which has list vew data. When user mark listitem as favourite, save the change in db table . When user navigates to favourite list populate the list from. db table with favourite filter in select query.
I suggest using SharedPreferences. You stated that your value gets overwritten. That won't be the case if you create multiple keys.
Example:
Say you have an ArrayList of String you want to pass from ClassA to ClassB:
ClassA:
for (int i = 0; i < list.size(); i++) {
sharedPref.edit().putString("text" + i, "abcde").apply();
}
ClassB:
for (int i = 0; i < list.size(); i++) {
sharedPref.getString("text" + i, null);
}
If you have problems with the listsize, you can also pass the listsize to sharedpref and retrieve it again.

Setter/Getter method not working

Hi I am having a problem accessing variables/methods in my view class from my main activity. I just need to return the turns int from GameView.java and be able to access it in MainActivity and then insert it into my database. I try to use GameView mGameView = new GameView(getApplicationContext()); but this doesn't work and I can't access any methods from GameView with this.
My GameView class:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
int turns = 0;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
int cellContent;
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
turns++;
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getTurns() {
return turns;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
GameView mGameView = new GameView(getApplicationContext());
this.turns = mGameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void AddData() {
boolean isInserted = myDb.insertData(Integer.toString(turns));
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
}
In MainAcivity, inside setTurns()
Replace this
this.turns = mGameView.turns; //you can't access this variable directly
with
this.turns = mGameView.getTurns(); // Calling the public method getTurns()
please see this answer for explanation about Access modifiers in Java
There are two ways to fix this.
1. Preferred way:
Add a new Method in GameView class
public int getTurns() {
return turns;
}
And use this method where you want to access turns like:
this.turns = mGameView.getTurns();
2. Bad way:
Make turns variable public.

parse.com query to sqlite query

I am trying to develop a crossword puzzle with parse.com backend to sqlite backed. I have difficulty in converting the code.
Following code is the database table i had created.
public class puzzle extends SQLiteOpenHelper {
public static final String db_name = "crossword.db";
public static final String Table1_name = "puz";
public static final String Table2_name = "item";
public static final String Table3_name = "clue";
public puzzle(final Context context){
super(context, db_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS" + Table1_name + "hash INTEGER, title TEXT, author TEXT,copyright TEXT,height INTEGER ,width INTEGER");
db.execSQL("CREATE TABLE IF NOT EXISTS"+ Table2_name + "hash INTEGER, x INTEGER ,y INTEGER, cell position INTEGER , black BOOLEAN , letter TEXT");
db.execSQL("CREATE TABLE IF NOT EXISTS" + Table3_name + "hash INTEGER, x INTEGER ,y INTEGER, cellposition INTEGER, cluenumber INTEGER, position INTEGER,clue TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + Table1_name);
db.execSQL("DROP TABLE IF EXISTS" + Table2_name);
db.execSQL("DROP TABLE IF EXISTS" + Table3_name);
onCreate(db);
}
public boolean insertitem(int hash, int x, int y, int cellposition, boolean black, String letter) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues itemvalues = new ContentValues();
itemvalues.put("hash", hash);
itemvalues.put("X", x);
itemvalues.put("Y", y);
itemvalues.put("CellPosition", cellposition);
itemvalues.put("Black", black);
itemvalues.put("Letter", letter);
long itemresult = db.insert(Table2_name, null, itemvalues);
if (itemresult == -1)
return false;
else
return true;
}
public boolean isinsertpuz(int hash,String title,String author,String copyright,int height,int width)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues puzvalues = new ContentValues();
puzvalues.put("hash",hash);
puzvalues.put("Title",title);
puzvalues.put("author",author);
puzvalues.put("copyright",copyright);
puzvalues.put("Height",height);
puzvalues.put("Width",width);
long puzresult = db.insert(Table1_name, null, puzvalues);
if (puzresult == -1)
return false;
else
return true;
}
public boolean isinsertclue(int hash,int x,int y,int cellposition,int cluenumber,String clue)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cluevalues = new ContentValues();
cluevalues.put("hash",hash);
cluevalues.put("X",x);
cluevalues.put("Y",y);
cluevalues.put("Cellposition",cellposition);
cluevalues.put("Cluenumber",cluenumber);
cluevalues.put("Clue",clue);
long clueresult=db.insert(Table3_name,null,cluevalues);
if(clueresult==-1)
return false;
else
return true;
}
public Cursor getpuzdata()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor puzquery=db.rawQuery("select * from" +Table1_name,null);
return puzquery;
}}
I want the following code in sqlite: I tried but it's showing some errorr, kindly help me!.
public CustomAdapter(Context context, int screenWidth, final int width,int screenHeight, int height, int hash, TextView clueTextView, TextView titleTextView){
this.context = context;
this.width = width;
this.height = height;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
activity = (Activity)context;
this.hash = hash;
this.clueTextView = clueTextView;
this.titleTextView = titleTextView;
clueNumber = 0;
//cell count
count = width*height;
//to store each cell view
view = new View[count];
//contains solution
letterChar = new char[count];
clueAcross = new HashMap<>();
clueDown = new HashMap<>();
Log.d("parseSize", String.valueOf(letterChar.length));
//fetch data saved locally
query = ParseQuery.getQuery("Item").fromLocalDatastore();
query.whereEqualTo("hash", hash);
query.orderByAscending("cellPosition");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null)
for (ParseObject parseObject : objects) {
if(parseObject.getString("letter").equals(""))
letterChar[parseObject.getInt("cellPosition")] = ' ';
else
letterChar[parseObject.getInt("cellPosition")] = parseObject.getString("letter").charAt(0);
}
ParseQuery.getQuery("Clue").fromLocalDatastore().whereEqualTo("hash", CustomAdapter.this.hash).orderByDescending("clueNumber").getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if(e == null)
clueSize = object.getInt("clueNumber");
Log.d("clueNumber", String.valueOf(clueSize));
}
});
ParseQuery.getQuery("Clue").fromLocalDatastore().whereEqualTo("hash", CustomAdapter.this.hash).orderByAscending("cellPosition").findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null)
for (ParseObject object : objects) {
//int pos = (object.getInt("y")*width)+object.getInt("x");
if(object.getString("position").equals("Hor"))
clueAcross.put(object.getInt("cellPosition"), object.getString("clue"));
else
clueDown.put(object.getInt("cellPosition"), object.getString("clue"));
Log.d("clue", object.getInt("cellPosition")+" "+object.getString("clue")+" "+object.getString("position"));
}
//will populate the griview
Game.gridView.setAdapter(Game.customAdapter);
//to adjust layout on keyboard up
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//dismiss progress dialog on UI thread
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Game.progress.dismiss();
}
});
}
});
}
});
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
}
#Override
public int getCount() {
return count;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
view[position] = convertView;
if(view[position] == null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
view[position] = layoutInflater.inflate(R.layout.grid_cell, null);
view[position].setLayoutParams(new RelativeLayout.LayoutParams(screenWidth / width, screenHeight / height));
}
//to shade black on cells containing no letters
view[position].setBackgroundResource(R.drawable.shape);
TextView cellNumberTextView = (TextView)view[position].findViewById(R.id.cellNumber);
final EditText letter = (EditText)view[position].findViewById(R.id.letter);
/*letter.setCursorVisible(false);
letter.setClickable(false);
letter.setLongClickable(false);
letter.setFocusable(false);
letter.setSelected(false);
letter.setKeyListener(null);
letter.setBackgroundResource(android.R.color.transparent);*/
//letter.setText(Character.toString(letterChar[position]));
// cellNumberTextView.setTextSize(cellNumberTextView.getTextSize() / 1.5f);
//set clue number on cells
if(clueAcross.get(position) != null){
cellNumberTextView.setText(String.valueOf(clueNumber));
clueNumber++;
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
Log.d("clueNumber", position+" "+clueNumber+ " "+clueSize);
}
else if(clueDown.get(position) != null){
cellNumberTextView.setText(String.valueOf(clueNumber));
clueNumber++;
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
Log.d("clueNumber", position+" "+clueNumber+ " "+clueSize);
}
//to disable EditText operations on black cells
if(letterChar[position] == ' ') {
view[position].setBackgroundColor(Color.BLACK);
letter.setClickable(false);
letter.setLongClickable(false);
letter.setFocusable(false);
letter.setSelected(false);
letter.setKeyListener(null);
}else
view[position].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//update clues on view click
clueTextView.setText(getClueDown(position));
titleTextView.setText(getClueAcross(position));
//to open keyboard and focus on the letter to edit
letter.requestFocus();
letter.setCursorVisible(true);
((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(letter, InputMethodManager.SHOW_IMPLICIT);
}
});
//update clues on letter click
letter.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
letter.setText("");
clueTextView.setText(getClueDown(position));
titleTextView.setText(getClueAcross(position));
}
}
});
//check value and change color of cell accordingly
letter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//letter.setText(s.toString().toUpperCase());
if(s.toString().isEmpty())
return;
Log.d("letter", "input "+s.toString()+"position "+String.valueOf(position)+Character.toString(letterChar[position]));
if (s.toString().equals(Character.toString(letterChar[position]))) {
view[position].setBackgroundResource(R.drawable.correct);
focusNext(position);
}
else
view[position].setBackgroundResource(R.drawable.wrong);
}
#Override
public void afterTextChanged(Editable s) {
/* if(s.toString().isEmpty())
return;*/
//view[0].setBackgroundResource(R.drawable.correct);
}
});
return view[position];
}
//to focus next cell
public void focusNext(int position) {
for (int i = position; i < count; i++) {
if (letterChar[i+1] == ' ')
continue;
else {
EditText editText = (EditText) ((ViewGroup) view[i + 1]).getChildAt(0);
editText.requestFocus();
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
return;
}
}
}
//get ACROSS clue based on position
public String getClueAcross(int position){
for(int i=position; i>=0; i--)
if(clueAcross.get(i) != null)
return "(across): "+clueAcross.get(i);
return "";
}
//get DOWN clue based on position
public String getClueDown(int position){
for(int i=position; i>=0; i-=width)
if(clueDown.get(i) != null)
return "(down): "+clueDown.get(i);
return "";
}
#Override
public Object getItem(int position) {
return view[position];
}
#Override
public long getItemId(int position) {
return position;
}
}
The following code is how i tried to change the code from parse.com to sqlite
public class CustomAdapter extends BaseAdapter {
int count, hash;
int width, height, screenWidth, screenHeight;
Activity activity;
Context context;
private static final String SELECTitem_SQL = "SELECT * FROM item";
private static final String SELECTpuz_SQL = "SELECT * FROM puz";
private static final String SELECTclue_SQL = "SELECT * FROM clue";
private SQLiteDatabase db,db1 ;
puzzle ca=new puzzle(context);
char[] letterChar;
HashMap<Integer, String> clueAcross, clueDown;
TextView clueTextView, titleTextView;
int clueNumber, clueSize;
View view[];
public CustomAdapter(Context context, int screenWidth, final int width,int screenHeight, int height, int hash, TextView clueTextView, TextView titleTextView) {
this.context = context;
this.width = width;
this.height = height;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
activity = (Activity) context;
this.hash = hash;
this.clueTextView = clueTextView;
this.titleTextView = titleTextView;
clueNumber = 0;
letterChar = new char[100];
//cell count
count = width * height;
//to store each cell view
view = new View[count];
//contains solution
letterChar = new char[count];
clueAcross = new HashMap<>();
clueDown = new HashMap<>();
Log.d("parseSize", String.valueOf(letterChar.length));
Cursor c1=db.rawQuery(SELECTitem_SQL,null);
Cursor c2=db.rawQuery(SELECTclue_SQL,null);
c1.moveToFirst();
c2.moveToFirst();
db= openOrCreateDatabase("item", null);
db1=openOrCreateDatabase("clue",null);
String hashid=c1.getString(0);
String cluehash=c2.getString(0);
String cluenum=c2.getString(4);
String hashpos=c1.getString(3);
String hashletter=c1.getString(5);
String hashblack=c1.getString(4);
int id=hashid.length();
for(int i=0;i<id;i++)
{
if(hashletter== "")
{
letterChar[Integer.parseInt(hashpos)]=' ';
}
else
{
letterChar[Integer.parseInt(hashpos)]=hashletter.charAt(0);
}
}
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
This is my code to convert from parse to sqlite but when i build the project it stays still.
I'm not sure if this helps you but there is a sql syntax error in your code:
db.execSQL("CREATE TABLE IF NOT EXISTS " + Table1_name + " (hash INTEGER, title TEXT, author TEXT,copyright TEXT,height INTEGER ,width INTEGER)");
db.execSQL("CREATE TABLE IF NOT EXISTS "+ Table2_name + " (hash INTEGER, x INTEGER ,y INTEGER, cell position INTEGER , black BOOLEAN , letter TEXT)");
db.execSQL("CREATE TABLE IF NOT EXISTS " + Table3_name + " (hash INTEGER, x INTEGER ,y INTEGER, cellposition INTEGER, cluenumber INTEGER, position INTEGER,clue TEXT)");
you missed "(" before "hash",a space after "EXISTS" and ")" at the end of each statement

Enter Data in TextBox save and show in another Activity Using Intent

Hello I'm new to android programming. I would like to ask how can I pass data to another activity using intent? My case here is, I have a 2 TextBox , if the user clicks on the button it should be retrieved(the text) to the database.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqlcon = new SQLController(this);
firstname_et = (EditText) findViewById(R.id.fistname_et_id);
lastname_et = (EditText) findViewById(R.id.lastname_et_id);
addmem_btn = (Button) findViewById(R.id.addmem_btn_id);
table_layout = (TableLayout) findViewById(R.id.tableLayout1);
BuildTable();
addmem_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
table_layout.removeAllViews();
String firstname = firstname_et.getText().toString();
String lastname = lastname_et.getText().toString();
firstname_et.setText("");
lastname_et.setText("");
// inserting data
sqlcon.open();
sqlcon.insertData(firstname, lastname);
BuildTable();
}
});
}
private void BuildTable() {
sqlcon.open();
Cursor c = sqlcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
// outer for loop
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setBackgroundResource(R.drawable.abc_btn_borderless_material);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
table_layout.addView(row);
}
sqlcon.close();
}
SQLitecontroller.java
public SQLController(Context c) {
ourcontext = c;
}
public SQLController open() throws SQLException {
dbhelper = new DatabaseHelper(ourcontext);
database = dbhelper.getWritableDatabase();
return this;
}
public void close() {
dbhelper.close();
}
public void insertData(String name, String lname) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.MEMBER_FIRSTNAME, name);
cv.put(DatabaseHelper.MEMBER_LASTNAME, lname);
database.insert(DatabaseHelper.TABLE_MEMBER, null, cv);
}
public Cursor readEntry() {
// TODO Auto-generated method stub
String[] allColumns = new String[] { DatabaseHelper.MEMBER_ID, DatabaseHelper.MEMBER_FIRSTNAME,
DatabaseHelper.MEMBER_LASTNAME };
Cursor c = database.query(DatabaseHelper.TABLE_MEMBER, allColumns, null, null, null,
null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String TABLE_MEMBER = "member";
public static final String MEMBER_ID = "_id";
public static final String MEMBER_FIRSTNAME = "firstname";
public static final String MEMBER_LASTNAME = "lastname";
// DATABASE INFORMATION
static final String DB_NAME = "MEMBER.DB";
static final int DB_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static final String CREATE_TABLE = "create table " + TABLE_MEMBER
+ "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MEMBER_FIRSTNAME + " TEXT NOT NULL ," + MEMBER_LASTNAME
+ " TEXT NOT NULL);";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
onCreate(db);
}
}
please help me.
i have try many time but error will generated so please help me.
show all data in TableView.

Android Close() was never explicitly called on database

I keep getting the error message Close() was never explicitly called on database. From what I've read I'm not closing the database once the activity is destroyed, but I don't know how to implement it:
Database Helper:
public class ResultsDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "results.db";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_NAME = "results";
public static final String _ID = BaseColumns._ID;
public static final String SAVED_NAME = "name";
public static final String COLUMN_NAME_CREATE_DATE = "date";
public static final String RIGHT_EAR = "right_ear";
public static final String LEFT_EAR = "left_ear";
public ResultsDatabase(Context context) {
// calls the super constructor, requesting the default cursor factory.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ SAVED_NAME + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ RIGHT_EAR + " BLOB,"
+ LEFT_EAR + " BLOB"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
}
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
}
}
I call this helper in my Tabbed Results Activity which displays the data in two different fragments as follows:
public class TabbedResultsActivity extends SherlockFragmentActivity{
TabHost mTabHost;
TabManager mTabManager;
public static final String IS_RIGHT_EAR = "is_right_ear";
private ArrayList<EarSrt> leftAnswerList;
private ArrayList<EarSrt> rightAnswerList;
private final static String TAG = "HearingTest";
private boolean isRightEarTab = true;
private boolean bothEarsBad;
private boolean leftEarBad;
private boolean rightEarBad;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
ActionBar ab = this.getSupportActionBar();
SherlockHelper.setupActionBar(ab, this);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
Intent intent = getIntent();
int rowId = intent.getIntExtra(ResultsDatabase._ID, -1);
if ( rowId != -1 ) {
ResultsDatabase db = new ResultsDatabase(this);
String select = "(" + ResultsDatabase._ID + " == " + rowId + ")";
Cursor c = db.getReadableDatabase().query(ResultsDatabase.TABLE_NAME, null, select, null, null, null,null);
if ( c.moveToFirst() ) {
int leftEarColumn = c.getColumnIndex(ResultsDatabase.LEFT_EAR);
byte[] leftEarByteArray = c.getBlob(leftEarColumn);
int rightEarColumn = c.getColumnIndex(ResultsDatabase.RIGHT_EAR);
byte[] rightEarByteArray = c.getBlob(rightEarColumn);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
} else {
byte[] leftEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.LEFT_EAR);
byte[] rightEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.RIGHT_EAR);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
isRightEarTab = getIntent().getBooleanExtra(IS_RIGHT_EAR, true);
GraphView graphView = new GraphView(this);
graphView.setPoints(rightAnswerList);
float leftAverage = calculateAverage(rightAnswerList);
graphView.setAverage(leftAverage);
graphView.setPoints(leftAnswerList);
float rightAverage = calculateAverage(leftAnswerList);
graphView.setAverage(rightAverage);
setResults(leftAnswerList, rightAnswerList);
String results = setResultCaption(bothEarsBad, leftEarBad, rightEarBad).toString();
Log.d(TAG, "The results were " + results);
Bundle leftbundle = new Bundle();
leftbundle.putString("results", results);
leftbundle.putParcelableArrayList("graph", leftAnswerList);
leftbundle.putFloat("average", leftAverage);
Bundle rightbundle = new Bundle();
rightbundle.putString("results", results);
rightbundle.putParcelableArrayList("graph", rightAnswerList);
rightbundle.putFloat("average", rightAverage);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
mTabManager.addTab(mTabHost.newTabSpec(getString(R.string.Left_ear)).setIndicator(getString(R.string.Left_ear)),
LeftEarResults.class, leftbundle);
mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator(getString(R.string.Right_ear)),
RightEarResults.class, rightbundle);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
private float calculateAverage(List<EarSrt> steps) {
float srt = 0.0f;
int length = steps.size();
for (int i = (int)Math.ceil( (float)length/(float)2); i < length; i++) {
EarSrt es = steps.get(i);
srt += es.getSrt();
}
srt = srt / (length-(float)Math.ceil( (float)length/(float)2));
return srt;
}
private void setResults(List<EarSrt> leftEar, List<EarSrt> rightEar) {
float esLeft = calculateAverage(leftEar);
float esRight = calculateAverage(rightEar);
leftEarBad = (esLeft > 24.0);
rightEarBad = (esRight > 24.0);
bothEarsBad = (leftEarBad && rightEarBad);
}
private StringBuilder setResultCaption(boolean bothEarsBad, boolean leftEarBad, boolean rightEarBad) {
String resultCaption;
StringBuilder resultsText = new StringBuilder();
if (bothEarsBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else{
if (leftEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_left_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
} else if (rightEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_Right_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else {
resultsText.append(getString(R.string.There_is_no_indication_of_hearing_loss));
}
}
resultsText.append(getString(R.string.The_results_of_the_hearing_test_are_not_to_be_utilized_as_an_official_outcome_for_assessing_levels_of_hearing_loss_True_hearing_loss_assessments_can_only_be_determined_by_a_licensed_hearing_healthcare_provider));
Log.d(TAG, "The results were " + resultsText);
return resultsText;
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}
My quesiton is how and where should I close the connection?
Thanks
Just alter your storeResults method as follows
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase(); // opens the database connection
try {
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
catch(Exception e) {
e.printStackTrace();
// furher error handling
}
finally {
db.close(); // closes the database every time after access
}
}

Categories

Resources