Im trying to build an app that sets many alarm clocks and i want to save the alarms with an SQLite database. Already watched many tutorials for this but still having a problem using the database. Firstly i want to save the alarm one by one by pushing a button. I tried also to insert manually 2 alarms but it didnt worked either. What am i doing wrong? I am pretty new to this!
DBHelper Class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String ALARMS_TABLE_NAME = "alarms";
public static final String ALARMS_COLUMN_ID = "id";
public static final String ALARMS_COLUMN_HOUR = "hour";
public static final String ALARMS_COLUMN_MINUTES = "minutes";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 33);
}
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+ALARMS_TABLE_NAME+" ("+ALARMS_COLUMN_ID+ " INTEGER PRIMARY KEY , "+
ALARMS_COLUMN_HOUR+ " INTEGER, "+ALARMS_COLUMN_MINUTES+" INTEGER)");
InsertAlarms(db);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+ALARMS_TABLE_NAME);
onCreate(db);
}
void AddAlarm(Alarm alarm)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_HOUR, alarm.getHour());
cv.put(ALARMS_COLUMN_MINUTES, alarm.getMinutes());
db.insert(ALARMS_TABLE_NAME, null, cv);
db.close();
}
Cursor getAllAlarms()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("SELECT * FROM "+ALARMS_TABLE_NAME,null);
return cur;
}
void InsertAlarms(SQLiteDatabase db) //insert manually 2 alarms
{
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_ID, 1);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
cv.put(ALARMS_COLUMN_ID, 2);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
}
int getAlarmCount()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select * from "+ALARMS_TABLE_NAME, null);
int x= cur.getCount();
cur.close();
return x;
}
Class Alarm:
public class Alarm {
int _id;
int _hour;
int _minutes;
public Alarm(int Hour, int Minutes)
{
this._hour=Hour;
this._minutes=Minutes;
}
public int getID()
{
return this._id;
}
public void SetID(int ID)
{
this._id=ID;
}
public int getHour()
{
return this._hour;
}
public int getMinutes()
{
return this._minutes;
}
public void setHour(int Hour)
{
this._hour=Hour;
}
public void setMinutes(int Minutes)
{
this._minutes=Minutes;
}
Activity AddAlarm
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour=(EditText)findViewById(R.id.txtHour);
txtMinutes=(EditText)findViewById(R.id.txtMinutes);
Button button1 = (Button)findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view)
{
boolean ok=true;
try
{
int hour=Integer.parseInt(txtHour.getText().toString());
int minutes=Integer.parseInt(txtMinutes.getText().toString());
Alarm al=new Alarm(hour,minutes);
Toast.makeText(AddAlarm.this,"ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
}
catch(Exception ex)
{
Toast.makeText(AddAlarm.this,"ERROR! ", Toast.LENGTH_LONG).show();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
Intent intent=getIntent();
DBHelper mydb;
TextView xupnitiria;
String hour;
public static boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.set_alarm_button);
//Bundle extras=intent.getExtras();
mydb=new DBHelper(this);
xupnitiria =(TextView)findViewById(R.id.xupnitiria);
xupnitiria.setText(xupnitiria.getText()+String.valueOf(mydb.getAlarmCount()));
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Intent a= new Intent(MainActivity.this, AddAlarm.class);
startActivity(a);
}
});
}
Errors on android Monitor
10-04 15:07:26.592 2625-2625/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1336)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1231)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1450)
at android.app.ContextImpl.bindService(ContextImpl.java:1422)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms:0)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms:1)
at bvq.run(:com.google.android.gms:9)
at bvn.run(:com.google.android.gms:10)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Add following in onCreate() of AddAlarm.java:
dbHelper=new DBHelper(this);
Also to see error log in logcat add following in try-catch block:
ex.printStackTrace();
AddAlarm Activity:
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour = (EditText) findViewById(R.id.txtHour);
txtMinutes = (EditText) findViewById(R.id.txtMinutes);
dbHelper=new DBHelper(this);
Button button1 = (Button) findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view) {
boolean ok = true;
try {
int hour = Integer.parseInt(txtHour.getText().toString());
int minutes = Integer.parseInt(txtMinutes.getText().toString());
Alarm al = new Alarm(hour, minutes);
Toast.makeText(AddAlarm.this, "ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
} catch (Exception ex) {
Toast.makeText(AddAlarm.this, "ERROR! ", Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}
Related
My problem is the app crash, it shows, unfortunately, the app has stopped.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
Button btnAdd;
Button btnList;
TextView tvView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnList = (Button) findViewById(R.id.btnList);
tvView = (TextView) findViewById(R.id.Textview);
editText = (EditText) findViewById(R.id.editText);
myDB=new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = editText.getText().toString();
if (newEntry.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
Toast.makeText(MainActivity.this, "You must put something in the text field", Toast.LENGTH_LONG).show();
}
}
});
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = myDB.addData(newEntry);
// check inserted successfully
if (insertData == true) {
Toast.makeText(MainActivity.this, "Successfully Entered Data!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
}
ListAcitivity.java
public class ListDataActivity extends AppCompatActivity {
DatabaseHelper myDB;
ListView listView;
ArrayAdapter<String>listAdapter;
#Override
protected void onCreate( Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
listView=(ListView)findViewById(R.id.listView);
myDB= new DatabaseHelper(this);
//populate an ArrayList<String> from the databases and then view it
ArrayList<String> theList=new ArrayList<>();
Cursor data=myDB.getListContent();
if(data.getCount()==0){
Toast.makeText(ListDataActivity.this,"The database was empty",Toast.LENGTH_LONG).show();
}else{
while(data.moveToNext()){
theList.add(data.getString(1));
listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mylist.db";
public static final String TABLE_NAME = "mylist_data";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM1";
public DatabaseHelper(Context context){
super (context, DATABASE_NAME, null , 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable="CREATE TABLE"+ TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT,"+
"ITEM1 TEXT)";
db.execSQL(createTable);
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXITS "+ TABLE_NAME);
onCreate(db);
db.close();
}
public boolean addData(String item1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item1);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as instered incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Return all the data from database
* #return
*/
public Cursor getListContent() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data =db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
return data;
}
}
LOGCAT show
12-27 07:29:26.268 24636-24636/sg.edu.rp.c346.todolist E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.rp.c346.todolist, PID: 24636
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/sg.edu.rp.c346.todolist/databases/mylist.db
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:520)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:263)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at sg.edu.rp.c346.todolist.DatabaseHelper.addData(DatabaseHelper.java:45)
at sg.edu.rp.c346.todolist.MainActivity.AddData(MainActivity.java:58)
at sg.edu.rp.c346.todolist.MainActivity$1.onClick(MainActivity.java:39)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
12-27 07:29:28.078 24636-24636/? I/Process: Sending signal. PID: 24636 SIG: 9
It looks like you did not initialize your myDB instance.
Call myDB = new DatabaseHelper(this) somewhere in your onCreate method before you try to add entry into your LocalDB.
You must initialize the myDB variable before access it. In your MainActivity.java you not initialize Helper class.
myDB= new DatabaseHelper(this);
Just do this.
Also change this condition
if (editText.length() != 0) { // Change this to newEntry.length() !=0
AddData(newEntry);
editText.setText("");
} else {
Toast.makeText(MainActivity.this, "You must put something in the text field", Toast.LENGTH_LONG).show();
}
Hope this will work.
You should not close() the SQLiteDatabase given to you in SQLiteOpenHelper onCreate() and onUpgrade(). Only close() database handles you have obtained yourself.
I want to print the whole database data so that I can check if my SQLite code is working or not.
I am fetching the user login details from login.java and want to show that at loggedin.java
login.java
public class login extends AppCompatActivity {
EditText e1, e2;
ImageView i1, i2;
Retrofit retrofit;
TextView t;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText);
if( e1.getText().toString().length() == 0 ){
e1.setError( "email is required" );}
e2 = (EditText) findViewById(R.id.editText2);
if( e2.getText().toString().length() == 0 ){
e2.setError( "password is required" );}
i1 = (ImageView) findViewById(R.id.email);
i2 = (ImageView) findViewById(R.id.password);
Button b1= (Button) findViewById(R.id.button);
t=(TextView)findViewById(R.id.textView5);
retrofit = new Retrofit.Builder()
.baseUrl("http://funnytadka.com:8060")
.addConverterFactory(GsonConverterFactory.create())
.build();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.insertEntry(e1.getText().toString(),e2.getText().toString());
loginApi thisapi = retrofit.create(loginApi.class);
Call<Pvideos> call = thisapi.loadData(e1.getText().toString(), e2.getText().toString());
call.enqueue(new Callback<Pvideos>() {
#Override
public void onResponse(Response<Pvideos> response, Retrofit retrofit) {
if (response.isSuccess())
{
Intent intent = new Intent(login.this, loggedin.class);
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(),"login unsuccessful",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(getApplicationContext(),"login unsuccessful",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
loggedin.java
public class loggedin extends AppCompatActivity
{
View view;
// public static final String DEFAULT = "N/A";
TextView t1, t2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accinfo);
t1 = (TextView) findViewById(R.id.textView3);
t2 = (TextView) findViewById(R.id.textView4);
}
databasehandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "logindb";
static SQLiteDatabase db;
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,email text,password text);";
DatabaseHandler(Context context) {
super(context, "logindb", null, DATABASE_VERSION);
db = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
db = this.db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void closeDb() {
db.close();
;
}
public static boolean insertEntry(String email, String password) {
ContentValues cv = new ContentValues();
cv.put("email", email);
cv.put("password", password);
Log.e("email", email);
Log.e("pass", password);
long rowsEffected = db.insert(DICTIONARY_TABLE_NAME, null, cv);
return rowsEffected > 0 ? true : false;
}}
Write a Method to retrieve data from DB table in
databasehandler.java
public Cursor getUserDetails( ) throws SQLException {
logger.debug("MYDATABASE_TABLE :- "+MYDATABASE_TABLE );
String q = "SELECT * FROM "+MYDATABASE_TABLE+" ;";
logger.debug("query :- "+q);
Cursor mCursor = db.rawQuery(q, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
db.close();
return mCursor;
}
public DBTariffHandler openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
db = sqLiteHelper.getReadableDatabase();
return this;
}
loggedin.java
databasehandler handler = new databasehandler(context);
handler.openToRead();
Cursor cursor_next = handler.getUserDetails();
handler.close() ;
if(cursor_next != null && cursor_next.moveToFirst())
{
cursor_next.getColumnIndex(databasehandler.KEY_USERNAME)
//..ETC
}
I am trying to implement a app which updates user location at every 15 seconds,stores data to database and show it to listview in my activity.
Location should always update even activity destroys,for that i have created LocationService class.
The problem is I am able to get updates and also able to store into database but i am unable to show these updates in listview at runtime means i want list should refresh at every 15 sec and show it to UI..
Also when I get details from database I am unable to get latest detail instead i get whole arraylist every time which affects my activity response.I want that only newly added data will be fetch from database so that it will take less time in loading but I want to display all data to list everytime.
I have implement a thread (Commented code)which fetch data and show to listview but this is not right way to update UI..please suggest me a way so that i can refresh my list when new data is added into database
This is my activity
public class MainActivity extends Activity {
List<MyLocation> locationList = new ArrayList();
ListView mList;
LocationAdapter adapter;
BroadcastReceiver receiver;
LocationService mService;
boolean mBound = false;
private DbHelper dbHelper;
private Button updateLocation;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
LocationService.LocalBinder binder = (LocationService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateLocation = (Button) findViewById(R.id.update_location);
mList = (ListView) findViewById(R.id.listView);
dbHelper = new DbHelper(this);
updateLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationList = mService.displayLocation();
adapter = new LocationAdapter(MainActivity.this, locationList);
mList.setAdapter(adapter);
}
});
/*
Thread mThread = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
locationList = dbHelper.getLocationDetails();
Collections.reverse(locationList);
adapter = new LocationAdapter(MainActivity.this, locationList);
mList.setAdapter(adapter);
}
});
}
} catch (InterruptedException e) {
}
}
};
mThread.start();*/
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, LocationService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
}
LocationService
public class LocationService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks {
private final IBinder mBinder = new LocalBinder();
ArrayList<MyLocation> locationList = new ArrayList<>();
private DbHelper dbHelper;
private Location mLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private String TAG = "Service";
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
dbHelper = new DbHelper(this);
createLocationRequest();
displayLocation();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "service destroy");
}
public List<MyLocation> displayLocation() {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
String lastUpdateTime = DateFormat.getTimeInstance().format(new Date());
dbHelper.insertLocationDetails(longitude, latitude, lastUpdateTime);
locationList = dbHelper.getLocationDetails();
return locationList;
} else {
return null;
}
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Connected to update");
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void onLocationChanged(Location location) {
mLocation = location;
Toast.makeText(getApplicationContext(), "Location changed",
Toast.LENGTH_SHORT).show();
displayLocation();
}
public void onConnected(Bundle arg0) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
public class LocalBinder extends Binder {
public LocationService getService() {
return LocationService.this;
}
}
}
Dbhelper
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String LONGITUDE = "longitude";
private static final String LATITUDE = "latitude";
private static final String LOCATION_CHANGE_TIME = "location_change_time";
private static final String LOCATION_DETAIL_TABLE = "location_detail_table";
private static final String CREATE_TABLE_LOCATION = "CREATE TABLE "
+ LOCATION_DETAIL_TABLE + " (" + LONGITUDE + " TEXT,"
+ LOCATION_CHANGE_TIME + " TEXT,"
+ LATITUDE + " TEXT)";
public static String DATABASE_NAME = "Location_database";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_TABLE_LOCATION);
}
public void insertLocationDetails(double longitude, double latitude, String time) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LONGITUDE, longitude);
values.put(LATITUDE, latitude);
values.put(LOCATION_CHANGE_TIME, time);
long id= database.insert(LOCATION_DETAIL_TABLE, null, values);
System.out.println("Newly added item id "+id);
database.close();
}
public ArrayList<MyLocation> getLocationDetails() {
ArrayList<MyLocation> locationList = new ArrayList();
String selectQuery = "SELECT * FROM " + LOCATION_DETAIL_TABLE;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToNext()) {
do {
MyLocation location = new MyLocation();
String longitude = cursor.getString(cursor
.getColumnIndexOrThrow(LONGITUDE));
String latitude = cursor.getString(cursor.getColumnIndexOrThrow(LATITUDE));
String time = cursor.getString(cursor
.getColumnIndexOrThrow(LOCATION_CHANGE_TIME));
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setLastUpdatedTime(time);
locationList.add(location);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
database.close();
return locationList;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
In your case, you can use ContentProvider and implements LoaderManager.LoaderCallbacks in your activity.
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
db = dbHelper.getWritableDatabase();
String table = uri.getLastPathSegment();
long rowID = db.insert(table, null, values);
Uri CONTENT_URI = Uri.parse("content://"
+ AUTHORITY + "/" + table);
Uri resultUri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(resultUri, null);
return resultUri;
}
Line
getContext().getContentResolver().notifyChange(resultUri, null);
in ContentProvider will cause requery data. And using SimpleAdapter in activity will update your UI.
You can use Callback for this purpose.
Define some interface like
public class LocationInterface(){
public void sendLocationDetails(Long lat, Long lon, String time);
}
Now let your Activity implement this interface.
public class MyActivity implements LocationInterface {
#Override
public void sendLocationDetails(Long lat, Long lon, String time){
//At this point, you have the required details
}
}
Now in LocationService.java you need to pass this interface as an argument.
public class LocationService {
private LocationInterface locationInterface;
LocationInterface(LocationInterface locationInterface){
this.locationInterface = locationInterface;
}
}
Now whenever you call displayLocation() method, you can call this interface and send data to the activity.
public List<MyLocation> displayLocation() {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
String lastUpdateTime = DateFormat.getTimeInstance().format(new Date());
//At this point, you are calling the interface.
locationInterface.sendDetails(latitude,longitude,lastUpdateTime);
dbHelper.insertLocationDetails(longitude, latitude, lastUpdateTime);
locationList = dbHelper.getLocationDetails();
return locationList;
} else {
return null;
}
}
In My android program I have NumberList.java with list_layout.xml
In xml there is a edit text field,and a button ..in edit text we can enter a phone number and with the button we can save..
But my requirement is I want to fetch the number from contacts and save them through a button..MainActivity.java is the program which fetchs the selected contact number..But I cant save as like NumberList.java.
How can I implement???
NumberList.java
public class NumberList extends Activity implements OnClickListener{
private RemindersDbAdapter mDbAdapter;
private EditText numbr;
private Button btnAdd;
private Button btnTree;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mDbAdapter=new RemindersDbAdapter(this);
mDbAdapter.open();
numbr=(EditText) findViewById(R.id.editNumber);
btnAdd=(Button) findViewById(R.id.btnSave);
btnAdd.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSave:
if((numbr.getText().toString()!=null)&&(numbr.getText().toString().length()>=7))
{ mDbAdapter.createReminder(numbr.getText().toString(), "", "");
mDbAdapter.close();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "plz enter correct number", Toast.LENGTH_SHORT).show();
}
default:
break;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mDbAdapter.close();
}}
and the another one which fetchs the contacts number from contact list
MainActivity.java
public class MainActivity extends Activity {
Button buttonReadContact;
TextView textPhone;
EditText ed;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
ed = (EditText)findViewById(R.id.phno1);
buttonReadContact.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
//Start activity to get contact
final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK){
if(requestCode == RQS_PICKCONTACT){
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if(cursor.moveToNext()){
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
ed.setText(stringNumber);
}
}else{
textPhone.setText("NO Phone Number");
}
}else{
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}
}
this is what you need just create a table and with name and phone_no and fill db details in below code
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
readContacts(getApplicationContext());
}
});
public void readContacts(Context ctx, String no) {
ContentValues cvs cvs = new ContentValues();
Cursor phones = ctx.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (phones.getCount() > 0) {
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!TextUtils.isEmpty(phoneNumber)) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
cvs.put("name", name );
cvs.put("phone_no", phoneNumber );
}
}
}
insertItem(cvs, "readtables");
}
private void insertItem(ContentValues cbs, String Tablename) {
SQLiteDatabase db = dbl.getWritableDatabase();
try {
CreateTablenew(Tablename);
db.insert("Tablename", null, cbs);
} catch (SQLException e) {
}
}
below is the code which i made to insert an integer value into database. this code is to help the user to keep track of his/her account balance. in this code the content of the database is displayed as a toast message on button click. i want the content to be displayed in a text field when this activity is called. the textfield to display the content and the update button are on the same activity. so when the user enters the value to be added or subtracted from the database and when the update button is pressed the textfield should be refreshed with the updated value. plz make the sufficient changes in the code.
thank you
Main Activity.java
package com.sqltut;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save,load,deposit,withdraw;
EditText balance,updatevalue;
DataHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save=(Button) findViewById(R.id.save);
load=(Button) findViewById(R.id.load);
deposit=(Button) findViewById(R.id.deposit);
withdraw=(Button) findViewById(R.id.withdraw);
balance=(EditText) findViewById(R.id.balance);
updatevalue=(EditText) findViewById(R.id.updatevalue);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getbalance=balance.getText().toString();
int bal=Integer.parseInt(getbalance);
handler=new DataHandler(getBaseContext());
handler.open();
long id=handler.insertData(bal);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int getbalance;
getbalance=0;
handler=new DataHandler(getBaseContext());
handler.open();
Cursor C=handler.returnData();
if(C.moveToFirst())
{
do
{
getbalance=C.getInt(0);
}while(C.moveToNext());
}
handler.close();
Toast.makeText(getBaseContext(), "Balance:"+getbalance,Toast.LENGTH_LONG).show();
}
});
withdraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String updt=updatevalue.getText().toString();
int value=Integer.parseInt(updt);
int flag=0;
handler=new DataHandler(getBaseContext());
handler.open();
handler.updateData(value,flag);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
handler.close();
}
});
deposit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String updt=updatevalue.getText().toString();
int value=Integer.parseInt(updt);
int flag=1;
handler=new DataHandler(getBaseContext());
handler.open();
handler.updateData(value,flag);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
handler.close();
}
});
//to call next activity
Button createAppointment = (Button)findViewById(R.id.Next);
createAppointment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, Page2.class);
MainActivity.this.startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
DataHandler.java
package com.sqltut;
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;
public class DataHandler {
public static final String BALANCE="balance";
public static final String TABLE_NAME="mytable";
public static final String DATA_BASE_NAME="mydatabase";
public static final int DATABASE_VERSION=1;
public static final String TABLE_CREATE="create table mytable(balance integer not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx)
{
this.ctx = ctx;
dbhelper=new DataBaseHelper(ctx);
}
private static class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context ctx)
{
super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS mytable ");
onCreate(db);
}
}
public DataHandler open()
{
db=dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(Integer balance)
{
ContentValues content=new ContentValues();
content.put(BALANCE, balance);
return db.insert(TABLE_NAME, null, content);
}
public void updateData(Integer value,Integer flag)
{
db = dbhelper.getReadableDatabase();
String selectQuery = "select balance from " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
int current = 0;
if (cursor.moveToFirst()) {
current= Integer.parseInt(cursor.getString(0));
}
if(flag==0){
current = current-value;
}else {
current = current+value ;
}
cursor.close();
db.close();
try{
db = dbhelper.getWritableDatabase();
String rawQuery = "update mytable set balance="+current;
db.execSQL(rawQuery);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public Cursor returnData()
{
return db.query(TABLE_NAME, new String[] {BALANCE}, null, null, null, null, null);
}
}
write a method in database like this.
public int getValue(){
//get present value from your crud operations
//you have to relate with CRUD values and get the int value
//call the method to get you required value, ex; If delete operation is done then you have give updated value to this method or insert is done then you have to call this method and you have to send the updated value to this, similarly you have to do this for update operation also. then you will get the value into this method whether any operation has done on database.
}
step1:call the method from you button click.
step2:inside getValue() invoke each crud method to get updated value.
try in this way.
call the method in the onClick of Button.
hope this may helps you