Android : Unable to Access Function From Other Class (Service) - java

I am a php developer learning my way around android development.
I have a dbhelper helper class which has the below coding.
package com.example.bootstart;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
private static final String LOGTAG = "THEDBHELPER";
private static final String DATABASE_NAME = "geolocation.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_LOCATIONS = "locations";
private static final String COLUMN_ID = "id";
private static final String COLUMN_welawa = "welawa";
private static final String COLUMN_lati = "latitude";
private static final String COLUMN_longi = "longitude";
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_LOCATIONS + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_welawa + " TEXT, " + COLUMN_lati
+ " TEXT, " + COLUMN_longi + " TEXT)";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
Log.i(LOGTAG, "TABLE HAS BEEN CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
onCreate(db);
}
public void insert_records(String lati, String longi) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
sqLiteDatabase.execSQL("INSERT INTO " +
TABLE_LOCATIONS +
"(welawa,latitude,longitude) Values (" + ts + ","+ lati +"," + longi + ");");
Log.i(LOGTAG, "Data Entered");
}
}
However, when I try to access the insert_records function from another class by using
dbhelper = new DBHelper(this); //I can't even get the insert_records function in the suggestions in the drop here OR DBHelper dbh= new DBHelper(this); dbh.insert_records("12.2323", "25.22222"); lovely eclipse throws the error message The constructor DBHelper(new Runnable(){}) is undefined.
I simply have no idea on how to access my function.
I have
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
defined at the top of the class I am trying to access from.
Below is the class im trying to access the dbhelper function from.
package com.example.bootstart;
import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class GPSService extends Service {
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
GPSTracker gps;
private int mInterval = 10000;
private Handler mHandler;
#Override
public void onCreate()
{
Log.v("StartServiceAtBoot", "StartAtBootService Created");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
//Service Will Start until stopped
mHandler = new Handler();
Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
mStatusChecker.run();
return START_STICKY;
}
public void onDestroy(){
super.onDestroy();
Toast.makeText(this,"Service Stopped",Toast.LENGTH_LONG).show();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
gps = new GPSTracker(GPSService.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
//new AsyncSendData().execute("http://www.accuretta.lk/nv/maps/track_post"); Sending Info Code Is Working Fine
DBHelper dbh= new DBHelper(this);
dbh.insert_records("12.2323", "25.22222");
dbh.insert_records("55.2222", "11.256");
}
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
}
I haven't seen any runnables created in any of the tutorials.
Your help is greatly appreciated.

You are passing the wrong parameter type to the DBHelper constructor. You have to do like this
DBHelper dbh= new DBHelper(getApplicationContext());
inside your void run() method of the mStatusChecker Runnable instance. if you look into the error message, you can understand that compiler is not able to find an appropriate constructor for DBHelper class with parameter type Runnable. that's why this error is thrown by eclipse.
Hope you understand now.

Related

Accessing Methods from Another Class Android

I am creating an android application that will be using a SQLite database. I have created a separate class called DBAdapter that holds all the methods relating to the database.
My issue comes when I try to access these methods from the main activity. I am still learning but I would normally instantiate the DBAdapter class and then I would be able to reference the methods. However the approach I am taking isnt working. Below is the single line of how I am trying to instantiate the class and under that is the rest of the class.
The error I am getting is cannot resolve method 'open()'
Instantiate Line and method
DBAdapter db = new DBAdapter(this);
db.open();
Main Class
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ContentFrameLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
final Context context = this;
private FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBAdapter db = new DBAdapter(this);
db.open();
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_box);
dialog.setTitle("Add new Location!");
dialog.show();
final EditText NameEdit = (EditText) findViewById(R.id.NameInput);
final EditText LatEdit = (EditText) findViewById(R.id.LatInput);
final EditText LongEdit = (EditText) findViewById(R.id.LongInput);
final EditText PhoneEdit = (EditText) findViewById(R.id.PhoneInput);
final Button OkButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
final Button CancelButton = (Button) dialog.findViewById(R.id.dialogButtonCancel);
OkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String RealName = NameEdit.getText().toString();
String Lat = LatEdit.getText().toString();
Float realLat = Float.parseFloat(Lat);
String Long = LongEdit.getText().toString();
Float realLong = Float.parseFloat(Long);
String Phone = PhoneEdit.getText().toString();
Double realPhone = Double.parseDouble(Phone);
//Use above to create a new Geofence
}
});
CancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
}
DBAdpater Class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Rory on 09/09/2016.
*/
public class DBAdapter {
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
//Database Version & name
private static final String DATABASE_NAME = "OpenSesame";
private static final int DATABASE_VERSION = 1;
private static final String TAG = "DBMain";
private static final String GEOTABLE = "geoTable";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
private static final String KEY_LAT = "lat";
private static final String KEY_LONG = "long";
private static final String KEY_RADIUS = "radius";
private static final String KEY_PHONE = "phone";
private static final String CREATE_GEO_TABLE = "CREATE TABLE "
+ GEOTABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTO INCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_LAT + " FLOAT,"
+ KEY_LONG + " FLOAT,"
+ KEY_RADIUS + " INTEGER,"
+ KEY_PHONE + " INTEGER" + ")";
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Method for updating the database
* #param db
* #param newVersion
* #param oldVersion
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public DatabaseHelper open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public Cursor DeleteGeo(String name) {
return db.rawQuery("delete from geoTable where name = " + name, null);
}
public long AddGeo(String name, float lat, float lon, double phone, int radius) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_LAT, lat);
initialValues.put(KEY_LONG, lon);
initialValues.put(KEY_PHONE, phone);
initialValues.put(KEY_RADIUS, radius);
return db.insert(GEOTABLE, null, initialValues);
}
public Cursor GetAllGeos() {
return db.rawQuery("select * from geoTable order by name ASC", null);
}
}
}
Your DBAdapter class does not have the open() method. It is the private inner class DatabaseHelper that has that method. You have two options to expose open() to be able to call it the way you are expecting.
Option 1: add an open() method to DBAdapter that calls DatabaseHelper's open() method
public void open() {
DBHelper.open();
}
Option 2: remove DatabaseHelper entirely, and have DBAdapter extends SQLiteOpenHelper instead
public class DBAdapter extends SQLiteOpenHelper {
...
public DBAdapter(Context ctx) {
this.context = ctx;
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// add all the code from inside DatabaseHelper below
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
// you will have to change this method to work
public DBAdapter open() throws SQLException
{
db = getWritableDatabase();
return this;
}
...
}

Android app stalls when implementing SQLite database

At first the app would just crash when I started it with an emulator, Not sure what I changed to get it to run but now it will run the onCreate method however, when I implement the addButtonClicked method the app just stalls and the Android Monitor displays "Suspending all threads" every few seconds and I'm not sure where to even begin debugging. Any pointers in the right direction would be greatly appreciated as I'm fairly new to Android development.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText testInput;
TextView testText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testInput = (EditText) findViewById(R.id.testInput);
testText = (TextView) findViewById(R.id.testText);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add product to database
public void addButtonClicked(View view){
Products product = new Products((testInput.getText().toString()));
dbHandler.addProduct(product);
printDatabase();
}
// Delete Items
public void deleteButtonClicked(View view){
String inputText = testText.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
testText.setText(dbString);
testInput.setText("");
}
}
Products.java
public class Products {
private int _id;
private String _productname;
public Products(){
}
public Products(String productname) {
this._productname = productname;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public int get_id() {
return _id;
}
public String get_productname() {
return _productname;
}
}
MyDBHandler.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS +"(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLUMN_PRODUCTNAME +" TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete product from database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
//Print of DB as sting
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname"))!= null){
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
for your databaseToString method you are performing a retrieve operation. You should be doing a read operation in a thread other than UI thread. Try fetching in AsyncTask. It should work. Implementation for your databaseToString should be handled by AsyncTask.
Happy Coding..

Updating specific column using a spinner widget

I am trying to update current credits column of the only row in the database using a drop down spinner which gets values from an arraylist. Very unsure about how to go about doing this operation. Thank you for any help in advance.
My database code:
package com.example.parkangel;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " TEXT NOT NULL, " + KEY_CREDITS + " TEXT
NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
}
My main activity code I will be doing the operation through:
package com.example.parkangel;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class Balance extends Activity{
Button add;
TextView display;
Spinner spinner3;
String[] money = {"Select amount", "£1", "£2", "£5", "£10"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
db.close();
tv.setText(data);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
Your question is fairly compound, getting selected field from spinner, updating database... I'm not going to provide a complete answer, but this should get you started:
This is how you would get the selected field from the spinner, which you can then use to update your database. One word of warning, I believe setOnItemSelectedListener is called when it is initially set, so you may need to ignore the first call.
Spinner spinner;
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2,
long arg3) {
if(! (view instanceof TextView)){
// view is probably a textview, but record type if not.
System.out.println("incorrect view type " + view.getClass().getSimpleName());
return;
}
EditText et = (EditText) view;
String fieldName = et.getText().toString().trim();
//Now we got selected name, send name
//to a function that updates our database.
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I didn't find the problem but I can tell you that your code is VERY INEFFICIENT. You are using String to build your result in the getData method. Each time you try to append the new data (Row) to the old one you are creating a new string to hold the new data. If you are retrieving 1000 row from the database, this means that you are creating 1000 string to build the final one. I recommend using StringBuilder instead as following:
StringBuilder strBuilder= new StringBuilder();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
strBuilder.append( c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n");
}
return str= strBuilder.toString();
Here is an example of how to insert into your DB:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PFNAME , editText1.getText().toString());
values.put(KEY_PSNAME , stringArrayList.get(position));
values.put(KEY_CARD , "12345677");
values.put(KEY_CREDITS , "55");
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
db.close(); // Closing database connection

Android Saving String to Database

I am new in Android development, And right now what I am trying to do is to save Message that I type and Username. I got this code from vogella.com, but it was written only for messages. And I have tried to add Username, but I get an error "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdatabaseactivity/com.example.testdatabaseactivity.TestDatabaseActivity}: android.database.sqlite.SQLiteException: no such column: SENDER (code 1): , while compiling: SELECT _id, SENDER, MESSAGE FROM MESSAGES"
And I can't figure out what Is wrong. Need a little help.
MessagesDataSource.java
package com.example.testdatabaseactivity;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class MessagesDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_SENDER, MySQLiteHelper.COLUMN_MESSAGE};
public MessagesDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Message createMessage(String sender, String message) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_MESSAGE, message);
values.put(MySQLiteHelper.COLUMN_SENDER, sender);
long insertId = database.insert(MySQLiteHelper.TABLE_MESSAGES, null,values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,null, null, null);
cursor.moveToFirst();
Message newMessage = cursorToMessage(cursor);
cursor.close();
return newMessage;
}
public List<Message> getAllMessages() {
List<Message> messages = new ArrayList<Message>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Message message = cursorToMessage(cursor);
messages.add(message);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return messages;
}
private Message cursorToMessage(Cursor cursor) {
Message message = new Message();
message.setId(cursor.getLong(0));
message.setMessage(cursor.getString(2));
message.setSender(cursor.getString(1));
return message;
}
}
Message.java
package com.example.testdatabaseactivity;
public class Message {
private long id;
private String message;
private String sender;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return message;
}
}
MySQLiteHelper.java
package com.example.testdatabaseactivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_MESSAGES = "MESSAGES";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_MESSAGE = "MESSAGE";
public static final String COLUMN_SENDER = "SENDER";
private static final String DATABASE_NAME = "message.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_SENDER + "sender not null, "
+ COLUMN_MESSAGE + " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),"Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
onCreate(db);
}
}
TestDatabaseActivity.java
package com.example.testdatabaseactivity;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class TestDatabaseActivity extends ListActivity {
private MessagesDataSource datasource;
public String sender = "Suren";
EditText edittext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittext = (EditText) findViewById(R.id.txt_message);
datasource = new MessagesDataSource(this);
datasource.open();
List<Message> values = datasource.getAllMessages();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(this,android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
String text = edittext.getText().toString();
ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
Message message = null;
if(edittext.length() == 0){
return;
}else{
// save the new message to the database
message = datasource.createMessage(sender, text);
adapter.add(message);
edittext.getText().clear();
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Correct your CREATE Table Query need space between Column Name and Column Type
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_SENDER + " text not null, "
+ COLUMN_MESSAGE + " text not null);";
You Forget to add space over here in your Query COLUMN_SENDER + "sender not null, "
// Database creation sql statement
private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_MESSAGES + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SENDER + " text not null, "
+ COLUMN_MESSAGE + " text not null)";
"sender" is not a type. You need put "text".
And give the appropriate spaces.

Content of the result of aggregation query not returned

I am a begineer and I want to allow just one user to sign up as per the demand of my project.
The SIGNUP.java is meant to accomplish it using DbHelper.java but things work fine for
c.getCount()
but not for
Integer.parseInt(c.getString(0))
SIGNUP.java reads:
package com.bishal.android.taskmanager;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SIGNUP extends Activity {
Button register;
private EditText etName;
private EditText etEmail;
//private EditText etUsername;
private EditText etPassword;
private DbHelper dbhelper;
AlertDialogManager alert = new AlertDialogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
dbhelper=new DbHelper(this);
etName=(EditText)findViewById(R.id.edit_name);
etEmail=(EditText)findViewById(R.id.edit_email);
etPassword=(EditText)findViewById(R.id.edit_signup_password);
register=(Button)findViewById(R.id.signup);
final boolean bregister=(dbhelper.NoOfUser()==0)?true:false;
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//String UserNameValue=etUsername.getText().toString();
String NameValue=etName.getText().toString();
String EmailValue=etEmail.getText().toString();
String PasswordValue=etPassword.getText().toString();
//Toast.makeText(SIGNUP.this,dbhelper.ThereIsUser(), Toast.LENGTH_LONG).show();
if (bregister){
ACCOUNT_INFO account=new ACCOUNT_INFO(NameValue,EmailValue,PasswordValue);
if(NameValue.trim().length()>0 && EmailValue.trim().length() > 0 && PasswordValue.trim().length() >0){
if(dbhelper.eMailValidation(EmailValue)){
if(dbhelper.validateregister(EmailValue)){
dbhelper.addAccount(account);
Toast.makeText(SIGNUP.this, "Your account has been sucessfully created.", Toast.LENGTH_LONG).show();
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Username/Email already exists.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this,"Signup failed..", "Email address is not in such form.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Please enter empty fields.", false);
}
}
}
});
}
}
DbHelper.java reads(why 'count' is not returned as count of number of rows in table?):
package com.bishal.android.taskmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
//import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DbHelper extends SQLiteOpenHelper{
private static final String TAG=DbHelper.class.getSimpleName();
public static final String DB_NAME="Store Account.db";
public static final int DB_VERSION=1;
public static final String TABLE="Account_Info";
public static final String COL_ID="Id"; //special for ID
public static final String COL_NAME="Name";
public static final String COL_EMAIL="Email";
//public static final String COL_UNAME="Username";
public static final String COL_PASSWORD="Password";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_ACCOUNT_INFORMATION = "CREATE TABLE " + TABLE + "("
+ COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " String,"
+ COL_EMAIL + " String," + COL_PASSWORD + " String" + ")";
Log.d(TAG, "onCreate sql: "+CREATE_ACCOUNT_INFORMATION);
db.execSQL(CREATE_ACCOUNT_INFORMATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exists " + TABLE);
Log.d(TAG,"onUpdate dropped table "+ TABLE);
onCreate(db);
}
void addAccount(ACCOUNT_INFO account){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(COL_NAME,account.getNAME());
values.put(COL_EMAIL,account.getEMAIL());
//values.put(COL_UNAME, account.getUSERNAME());
values.put(COL_PASSWORD, account.getPASSWORD());
db.insert(TABLE, null, values);
db.close();
}
public boolean validateuser(String email,String password){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email +"'AND "+COL_PASSWORD+"='" + password+"'" , null);
if(c.getCount()>0)
return true;
else
return false;
}
public boolean validateregister(String email){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email+"'" , null);
if(c.getCount()>0)
return false;
else
return true;
}
public boolean eMailValidation(String emailValue) {
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern=Pattern.compile(EMAIL_PATTERN);;
Matcher matcher;
matcher = pattern.matcher(emailValue);
return matcher.matches();
}
public int NoOfUser() {
Cursor c=getReadableDatabase().rawQuery("SELECT count(*) FROM " + TABLE, null);
int count=Integer.parseInt(c.getString(0));
return count;
}
}

Categories