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.
Related
I want to add a new button in my project that can delete some of the number and names that I saved.
I am totally new to Android Studio, so I donĀ“t know how to write my code that it will work the way I want it.
MainActivity(Register) :
public class MainActivity extends Activity {
EditText name,number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void display(View v) {
Intent i_view=new Intent(MainActivity.this,Display.class);
startActivity(i_view);
}
public void storeInDB(View v) {
Toast.makeText(getApplicationContext(), "Start Save",Toast.LENGTH_LONG).show();
name = (EditText) this.findViewById(R.id.textView1);
number = (EditText) this.findViewById(R.id.textView2);
String str_name=name.getText().toString();
String str_number=number.getText().toString();
SQLiteDatabase db;
db=openOrCreateDatabase("NumDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS details(name VARCHAR,number VARCHAR);");
Cursor c=db.rawQuery("SELECT * FROM details", null);
if(c.getCount()<20)
{
db.execSQL("INSERT INTO details VALUES('"+str_name+"','"+str_number+"');");
Toast.makeText(getApplicationContext(), "Save successfuly",Toast.LENGTH_SHORT).show();
}
db.close();
}
}
And Display :
public class Display extends Activity {
Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
SQLiteDatabase db;
db=openOrCreateDatabase("NumDB", Context.MODE_PRIVATE, null);
c=db.rawQuery("SELECT * FROM details", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found.");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append(" "+c.getString(0)+"\n");
buffer.append(" "+c.getString(1)+"\n");
}
showMessage("Contact", buffer.toString());
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
The code is working fine but I want to add a button that allows me to delete all the numbers and names that I saved,'your text'
I am new in Java, I want to show the username value from my Table in SQLite Database after successful login into my TextView in layout activity_home.xml
I don't know how to get username value with my code here.
The code for my TextView in my activity_home.xml layout's
<TextView
android:id="#+id/nameuser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="32dp"/>
And here's the code :
DBHelper
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "myapp.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USERNAME + " TEXT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String username,String email,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, username);
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String username, String email, String pass){
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
if(email != null)
selectQuery += "and " + COLUMN_EMAIL + " = " + "'"+email+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
}
HomeActivity
public class HomeActivity extends AppCompatActivity {
TextView nameuser, walletuser, mainmenus,
pagetitle, pagesubtitle;
Button btnguide;
Animation atg, atgtwo, atgthree;
ImageView imageView3;
SharedPreferences sharedpreferences;
Intent intent;
private Session session;
TextView btnLogout, btnDaftarBarang, btnTambah;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
if(!session.loggedin()){
logout();
}
atg = AnimationUtils.loadAnimation(this, R.anim.atg);
atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);
nameuser = findViewById(R.id.nameuser);
walletuser = findViewById(R.id.walletuser);
btnDaftarBarang = (TextView) findViewById(R.id.btnDaftarBarang);
btnTambah = (TextView) findViewById(R.id.btnTambah);
btnLogout = (TextView) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
}
});
imageView3 = findViewById(R.id.imageView3);
mainmenus = findViewById(R.id.mainmenus);
pagetitle = findViewById(R.id.pagetitle);
pagesubtitle = findViewById(R.id.pagesubtitle);
btnguide = findViewById(R.id.btnguide);
btnguide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(HomeActivity.this,PackageAct.class);
startActivity(a);
}
});
// pass an animation
imageView3.startAnimation(atg);
pagetitle.startAnimation(atgtwo);
pagesubtitle.startAnimation(atgtwo);
btnguide.startAnimation(atgthree);
btnTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent tambah = new Intent(HomeActivity.this, CrudActivity.class);
startActivity(tambah);
}
});
btnDaftarBarang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//start recordlist activity
startActivity(new Intent(HomeActivity.this, RecordListActivity.class));
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(HomeActivity.this,LoginActivity.class));
}
}
Session.java
public class Session {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context ctx;
public Session(Context ctx){
this.ctx = ctx;
prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
editor = prefs.edit();
}
public void setLoggedin(boolean logggedin){
editor.putBoolean("loggedInmode",logggedin);
editor.commit();
}
public boolean loggedin(){
return prefs.getBoolean("loggedInmode", false);
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private Button login;
private EditText etUsername, etPass;
private DbHelper db;
private Session session;
TextView RegisterDisini;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new DbHelper(this);
session = new Session(this);
login = (Button)findViewById(R.id.btnLogin);
etUsername = (EditText)findViewById(R.id.etUsername);
etPass = (EditText)findViewById(R.id.etPass);
login.setOnClickListener(this);
RegisterDisini = (TextView) findViewById(R.id.RegisterDisini);
RegisterDisini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerHere = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerHere);
}
});
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this,HomeActivity.class));
finish();
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
login();
break;
default:
}
}
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
}
1. Add the line, as per the comment, as below to the LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
public static final String INTENTEXTRAKEY_LOGGEDINUSERNAME = "iek_loggedinusername"; //<<<<<<<<<< ADDED THIS LINE
private Button login;
2. In LoginActivity Change your login method as below :-
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
//startActivity(new Intent(LoginActivity.this, HomeActivity.class)); <<<<<<<<< OLD CODE
Intent intent = new Intent(LoginActivity.this,HomeActivity.class); //<<<<<<<<<< NEW CODE
intent.putExtra(INTENTEXTRAKEY_LOGGEDINUSERNAME,username); //<<<<<<<<<< NEW CODE
startActivity(intent); //<<<<<<<<<< NEW CODE
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
3. In the HomeActivity add the line as commented :-
public class HomeActivity extends AppCompatActivity {
TextView nameuser, walletuser, mainmenus,
pagetitle, pagesubtitle;
Button btnguide;
Animation atg, atgtwo, atgthree;
ImageView imageView3;
SharedPreferences sharedpreferences;
Intent intent;
private Session session;
TextView btnLogout, btnDaftarBarang, btnTambah;
String loggedinusername; //<<<<<<<<<< ADDED
4. Also in HomeActivity add the line as commented :-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
loggedinusername = this.getIntent().getStringExtra(LoginActivity.INTENTEXTRAKEY_LOGGEDINUSERNAME); //<<<<<<<<<<ADDED
5. Again also in HomeActivity add the line as commented :-
atg = AnimationUtils.loadAnimation(this, R.anim.atg);
atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);
nameuser = findViewById(R.id.nameuser);
nameuser.setText(loggedinusername); //<<<<<<<<<< ADDED
Explanation
adds a constant for a value that will be used to define the key part of a key/value pair.
Adds an Intent Extra that has the constant as defined in 1 as the key and the username as the value.
Adds a class variable, loggedinusername, for the username (optional as you could get the Inten Extra directly, but this allows the username to be utilised elsewhere if need be.)
sets the loggedinusername variable according to the Intent Extra
sets the TextView to display the username as per the loggedinusername variable.
This is the recommended way of passing data from one activity to the next. You can pass many Intent Extras of varying types.
After login success pass username to your HomeActivity using intent
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
Intent intent=new Intent(this,HomeActivity.class);
intent.putExtra("username",username);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
// now get Username in HomeActivity like this
String username=getIntent().getStringExtra("username");
if(!TextUtils.isEmpty(username)){
// and set on your textview here
nameuser.setText(""+username);
}
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();
}
}
}
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
}
MainActivity.java
public class MainActivity extends ListActivity implements OnGesturePerformedListener {
static SQLiteDatabase db;
public static String TABEl_CREATE="CONTACTS";
public static String DATA_BASE_TABLE_CREATE = "create table if not exists " +TABEl_CREATE+ "(Name text not null ,Number number unique not null)";
GestureLibrary lib;
private ArrayList<String> results = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = openOrCreateDatabase("contacts", MODE_PRIVATE, null);
db.execSQL(DATA_BASE_TABLE_CREATE);
lv = (ListView) findViewById (android.R.id.list);
populatelv();
lib = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!lib.load()) {
finish();
}
GestureOverlayView gesture = (GestureOverlayView)
findViewById(R.id.gestures);
gesture.addOnGesturePerformedListener(this);
}
private void populatelv() {
// TODO Auto-generated method stub
Cursor c = db.rawQuery("SELECT Name FROM " +TABEl_CREATE, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String Name = c.getString(c.getColumnIndex("Name"));
results.add( Name );
}while (c.moveToNext());
}
}
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1,results);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
// TODO Auto-generated method stub
ArrayList<Prediction> predictions = lib.recognize(gesture);
if (predictions.size() > 0)
{
String action = predictions.get(0).name;
if (predictions.get(0).score > 1.0)
{
if ("ADD".equals(action))
{
Toast.makeText(this, "Adding a contact",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,Database.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
else
if ("delete".equals(action))
{
Toast.makeText(this, "Removing a contact",Toast.LENGTH_SHORT).show();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
// Here,how can i get the position of the specific listitem where gesture action took place..?
// String str = lv.getItemAtPosition(arg2).toString();
//Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
// String delete = "delete from contacts where Name = '"+str+"'";
//db.execSQL(delete);
//Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
}
}) ;
}
else if ("refresh".equals(action))
{
Toast.makeText(this, "Reloading contacts",
Toast.LENGTH_SHORT).show();
}
}
}
}
}
Database.java
public class Database extends Activity {
Button add;
EditText name,number;
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
db= MainActivity.db;
db = openOrCreateDatabase("contacts", MODE_PRIVATE, null);
add = (Button) findViewById(R.id.button1);
name = (EditText) findViewById(R.id.editText1);
number = (EditText) findViewById(R.id.editText2);
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nval,nbval;
nval = name.getText().toString();
nbval = number.getText().toString();
if(nval.length()>0 && nbval.length()>0)
{
ContentValues cv = new ContentValues();
cv.put("Name", nval);
cv.put("Number", nbval);
db.insert("CONTACTS","title", cv);
Toast.makeText(getApplicationContext(), "Inserted sucessfully",Toast.LENGTH_SHORT ).show();
}
else
{
Toast.makeText(getApplicationContext(), "Please fill all fields!!!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onBackPressed()
{
Intent intent=new Intent(Database.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
};
}
Here,i'm trying to display contacts in listview by retrieving from database which is done by Database.java.I'm able add the contacts into database using gesture but when i tried to delete the specific contact from list using gesture,i can't able to do..I'm new to development of android applications..please suggest me..here is my code.