Related
I have build an app that can insert and retrieve data into listview. i used database that placed on assets folder. When i run my app on device (xiaomi redmi note4) via usb debug but I can not sign up user when I click sign up button. this also happens to the emulator if I delete the database file in "/data/data/com.example.ibtb.bmkg/databases/" with logcat like this
04-12 12:09:27.789 16299-16299/? E/SQLiteLog: (1) no such table: tb_user
04-12 12:09:27.794 16299-16299/? E/SQLiteDatabase: Error inserting email=t password=t nip=t username=t nama=t
android.database.sqlite.SQLiteException: no such table: tb_user (code 1): , while compiling: INSERT INTO tb_user(email,password,nip,username,nama) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1470)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.example.ibtb.bmkg.database.DatabaseHelper.insertUser(DatabaseHelper.java:73)
at com.example.ibtb.bmkg.SignUp$1.onClick(SignUp.java:68)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22295)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6342)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
here is my database code
package com.example.ibtb.bmkg.database;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.ibtb.bmkg.model.Instrumen;
import com.example.ibtb.bmkg.model.User;
import com.example.ibtb.bmkg.model.Pengecekan;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IBTB on 08/02/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DB_PATH = "/data/data/com.example.ibtb.bmkg/databases/";
public static String DB_NAME = "bmkgdb.db";
SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDataBase() {
String dbPath = myContext.getDatabasePath(DB_NAME).getPath();
if (myDataBase != null && myDataBase.isOpen()) {
return;
}
myDataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (myDataBase != null) {
myDataBase.close();
}
}
public long insertUser(User c){
myDataBase = this.getWritableDatabase();
ContentValues values = new ContentValues();
/*String query = "select * from tb_user";
Cursor cursor = myDataBase.rawQuery(query,null);
int count = cursor.getCount();
values.put("id_user", count); */
values.put("nama", c.getName());
values.put("nip", c.getNip());
values.put("email", c.getEmail());
values.put("username", c.getUname());
values.put("password", c.getPass());
openDataBase();
long returnValue = myDataBase.insert("tb_user", null, values);
closeDatabase();
return returnValue;}
public String searchPass(String uname) {
myDataBase = this.getReadableDatabase();
String query = "select username, password from tb_user";
Cursor cursor = myDataBase.rawQuery(query, null);
String a, b;
b = "not found";
if (cursor.moveToFirst()) {
do {
a = cursor.getString(0);
//b= cursor.getString(1);
if (a.equals(uname)) {
b = cursor.getString(1);
break;
}
}
while (cursor.moveToNext());
}
return b;
}
public List<Pengecekan> getListPengecekan() {
// String[] whereargs = new String[]{String.valueOf(id)};
Pengecekan pengecekan = null;
List<Pengecekan> PengecekanList = new ArrayList<>();
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat FROM tb_pengecekan A, tb_alat B, tb_instrumen C " +
"WHERE C.id_instrumen = B.id_instrumen AND A.id_alat = B.id_alat AND C.id_instrumen = '9' ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
PengecekanList.add(pengecekan);
/* if (cursor.moveToFirst()) {
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
PengecekanList.add(pengecekan);*/
cursor.moveToNext();}
cursor.close();
close();
return PengecekanList;
}
public Pengecekan getPengecekanId(int id) {
Pengecekan pengecekan = null;
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat FROM tb_pengecekan A, tb_alat B, tb_instrumen C " +
"WHERE A.id_pengecekan = ?", new String[]{String.valueOf(id)});
cursor.moveToFirst();
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
//Only 1 resul
cursor.close();
closeDatabase();
return pengecekan;
}
public long updatePengecekan(Pengecekan pengecekan) {
ContentValues contentValues = new ContentValues();
contentValues.put("pengecekan", pengecekan.getPengecekan());
contentValues.put("normal", pengecekan.getNormal());
contentValues.put("nama_alat", pengecekan.getNama_alat());
String[] whereArgs = {Integer.toString(pengecekan.getId_pengecekan())};
openDataBase();
long returnValue = myDataBase.update("tb_pengecekan",contentValues, "id_pengecekan=?", whereArgs);
closeDatabase();
return returnValue;
}
public long addPengecekan(Pengecekan pengecekan) {
ContentValues contentValues = new ContentValues();
contentValues.put("ID", pengecekan.getId_pengecekan());
contentValues.put("pengecekan", pengecekan.getPengecekan());
contentValues.put("normal", pengecekan.getNormal());
contentValues.put("nama_alat", pengecekan.getNama_alat());
openDataBase();
long returnValue = myDataBase.insert("tb_pengecekan", null, contentValues);
closeDatabase();
return returnValue;
}
public boolean deletePengecekanById(int id) {
openDataBase();
int result = myDataBase.delete("tb_pengecekan", "id_pengecekan =?", new String[]{String.valueOf(id)});
closeDatabase();
return result !=0;
}
public List<Instrumen> getListInstrumen() {
Instrumen instrumen = null;
List<Instrumen> InstrumenList = new ArrayList<>();
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tb_instrumen ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
instrumen = new Instrumen(cursor.getInt(0), cursor.getString(1));
InstrumenList.add(instrumen);
cursor.moveToNext();
}
cursor.close();
close();
return InstrumenList;
}
public Instrumen geInstrumenId(int id) {
Instrumen instrumen = null;
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tb_instrumen WHERE id_instrumen = ?", new String[]{String.valueOf(id)});
cursor.moveToFirst();
instrumen = new Instrumen(cursor.getInt(0), cursor.getString(1));
//Only 1 resul
cursor.close();
closeDatabase();
return instrumen;
}
}
copy database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
if(false == database.exists()) {
myDbHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
SignUp.Java
package com.example.ibtb.bmkg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.User;
/**
* Created by IBTB on 08/02/2018.
*/
public class SignUp extends Activity {
private Button reg;
private DatabaseHelper dbHelper;
private EditText name, nip, email, uname, pass1, pass2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
dbHelper = new DatabaseHelper(getApplicationContext());
reg = (Button)findViewById(R.id.Bsignupbutton);
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (EditText) findViewById(R.id.Tfname);
nip = (EditText) findViewById(R.id.Tfnip);
email = (EditText) findViewById(R.id.Tfemail);
uname = (EditText) findViewById(R.id.Tfuname);
pass1 = (EditText) findViewById(R.id.Tfpass1);
pass2 = (EditText) findViewById(R.id.Tfpass2);
String namestr = name.getText().toString();
String nipstr = nip.getText().toString();
String emailstr = email.getText().toString();
String unamestr = uname.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
User c = new User(namestr, nipstr, emailstr, unamestr, pass1str);
if (namestr.isEmpty() || nipstr.isEmpty() || emailstr.isEmpty() || unamestr.isEmpty() || pass1str.isEmpty() || pass2str.isEmpty()) {
Toast full = Toast.makeText(SignUp.this, "Please fill all the coloumn", Toast.LENGTH_SHORT);
full.show();
} else if (!pass1str.equals(pass2str)) {
Toast pass = Toast.makeText(SignUp.this, "Password dont match", Toast.LENGTH_SHORT);
pass.show();
} else {
/*c.setName(namestr);
c.setNip(nipstr);
c.setEmail(emailstr);
c.setUname(unamestr);
c.setPass(pass1str);*/
long result = dbHelper.insertUser(c);
Intent j = new Intent(SignUp.this, MainActivity.class);
startActivity(j);
if (result > 0) {
Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_SHORT).show();
//back to main activity
finish();
} else {
Toast.makeText(getApplicationContext(), "Add failed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
MainActivity.Java
package com.example.ibtb.bmkg;
import android.content.Intent;
import android.app.Activity;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ibtb.bmkg.database.DatabaseHelper;
public class MainActivity extends Activity {
private Session session;
//private Button button;
DatabaseHelper myDbHelper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
// button = (Button)findViewById(R.id.button);
if(session.loggedin()){
startActivity(new Intent(MainActivity.this,Home.class));
finish();
}
}
public void onButtonClick(View v)
{
if(v.getId()==R.id.Blogin)
{
EditText a = (EditText)findViewById(R.id.Tfusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.Tfpassword);
String pass = b.getText().toString();
String password = myDbHelper.searchPass(str);
if (pass.isEmpty() || str.isEmpty()) {
Toast full = Toast.makeText(MainActivity.this, "Please enter username and password", Toast.LENGTH_SHORT);
full.show();
}
else if(pass.equals(password))
{
session.setLoggedin(true);
Intent i = new Intent (MainActivity.this, Home.class);
i.putExtra("Username",str);
startActivity(i);
finish();
}
else
{
Toast temp = Toast.makeText(MainActivity.this, "Username and Password dont match", Toast.LENGTH_SHORT);
temp.show();
}
}
if (v.getId()==R.id.Bsignup)
{
Intent i = new Intent (MainActivity.this, SignUp.class);
startActivity(i);
}
}
/*
public void press (View v){
Intent i = new Intent (MainActivity.this, ListPengecekan2.class);
startActivity(i);
}*/
}
Session.java
package com.example.ibtb.bmkg;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by IBTB on 06/04/2018.
*/
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);
}
}
ListPengecekan.java
package com.example.ibtb.bmkg;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ibtb.bmkg.adapter.ListPengecekanAdapter;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.Pengecekan;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
public class ListPengecekan extends AppCompatActivity {
private ListView lvPengecekan;
private TextView instrumen;
private ListPengecekanAdapter adapter;
private List<Pengecekan> mPengecekanList;
private Button btnAdd;
private DatabaseHelper myDbHelper;
//Cursor c = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pengecekan);
lvPengecekan = (ListView) findViewById(R.id.listview_pengecekan);
btnAdd = (Button)findViewById(R.id.Badd);
myDbHelper = new DatabaseHelper(this);
String instrumen = getIntent().getStringExtra("ins");
TextView tv = (TextView) findViewById(R.id.tv_instrumen);
tv.setText(instrumen);
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
if(false == database.exists()) {
myDbHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//String id = getIntent().getStringExtra("id");
mPengecekanList = myDbHelper.getListPengecekan();
adapter = new ListPengecekanAdapter (this, mPengecekanList);
lvPengecekan.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
mPengecekanList = myDbHelper.getListPengecekan();
//Init adapter
adapter.updateList(mPengecekanList);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DB_NAME);
String outFileName = DatabaseHelper.DB_PATH + DatabaseHelper.DB_NAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("ListPengecekan", "DB copied");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
// });
}
public void onRadioButtonClicked(View view) {
String kondisi="";
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.B:
if (checked)
kondisi = "Baik";
break;
case R.id.RR:
if (checked)
kondisi = "Rusak ringan";
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ListPengecekan.this);
View mView = getLayoutInflater().inflate(R.layout.dialogrusak, null);
mBuilder.setTitle("Keterangan kerusakan");
final Spinner mSpinner = (Spinner) mView.findViewById(R.id.Spenanganan);
final Spinner mSpinner1 = (Spinner) mView.findViewById(R.id.Shasil);
final EditText kronologi = (EditText) mView.findViewById(R.id.ekro);
final EditText lapor = (EditText) mView.findViewById(R.id.elapor);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner1.setAdapter(adapter1);
mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String Kronologi = kronologi.getText().toString();
Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
Toast.makeText(ListPengecekan.this, mSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
Toast.makeText(ListPengecekan.this, mSpinner1.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
String Lapor = lapor.getText().toString();
Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
}
});
mBuilder.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
break;
case R.id.RB:
if (checked)
kondisi = "Rusak berat";
AlertDialog.Builder mBuilder1 = new AlertDialog.Builder(ListPengecekan.this);
View mView1 = getLayoutInflater().inflate(R.layout.dialogrusak, null);
mBuilder1.setTitle("Keterangan kerusakan");
final Spinner mSpinner2 = (Spinner) mView1.findViewById(R.id.Spenanganan);
final Spinner mSpinner3 = (Spinner) mView1.findViewById(R.id.Shasil);
final EditText kronologi1 = (EditText) mView1.findViewById(R.id.ekro);
final EditText lapor1 = (EditText) mView1.findViewById(R.id.elapor);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner2.setAdapter(adapter2);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner3.setAdapter(adapter3);
mBuilder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String Kronologi = kronologi1.getText().toString();
Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();
if (!mSpinner2.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
Toast.makeText(ListPengecekan.this, mSpinner2.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
if (!mSpinner3.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
Toast.makeText(ListPengecekan.this, mSpinner3.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
String Lapor = lapor1.getText().toString();
Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
}
});
mBuilder1.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder1.setView(mView1);
AlertDialog dialog1 = mBuilder1.create();
dialog1.show();
break;
}
//myDbHelper.execSQl
}
}
Ok your issue could be that the onCreate method does nothing. if you delete an existing/useable database then there are no tables created.
You need to use db.execSql(a_string_with_the_sql_to_create_your_tables); in the onCreate method.
Something like :-
#Override
public void onCreate(SQLiteDatabase db) {
crtsql = "CREATE TABLE IF NOT EXISTS tb_user (id INTEGER PRIMARY KEY,nama TEXT,nip TEXT, email TEXT, password TEXT)";
db.execSQL(crtsql);
}
Note you'd need to do the same for all the other tables. Noting that you need a db.execSQL for each as you can only run 1 SQL statement at a time.
An exception would be if you have other code that copies the database from the assets folder. If so including that would be relevant as if this is the case, this not working could be the issue.
Edit re comments
It has been determined that issue is highly likely that the copy of the database from the assets folder is not being invoked.
To simplify the fix the following is suggested (rather than edit code) :-
Create a Java Class named CopyDBFromAssets i.e. file CopyDBFromAssets.java and copt the following into that class
:-
public class CopyDBFromAssets {
private static final String TAG = "DBASSETCOPY";
String mDBPath, mDatabasename;
CopyDBFromAssets(Context context, String databasename) {
mDatabasename = databasename;
mDBPath = context.getDatabasePath(mDatabasename).getPath();
if(!ifDatabaseExists(mDBPath)) {
Log.d(TAG,
"Attempting to copy database " +
mDatabasename +
" from assets folder."
);
if (copyDatabase(context)) {
Log.d(TAG,"Database " +
mDatabasename + " successfully copied.");
} else {
Log.e(TAG,"Database " + mDatabasename + " NOT COPIED!!!");
}
}
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(mDatabasename);
String outFileName = mDBPath;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v(TAG, "DB copied");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private boolean ifDatabaseExists(String dbpath) {
File db = new File(dbpath);
if(db.exists()) return true;
File dir = new File(db.getParent());
if (!dir.exists()) {
dir.mkdirs();
}
return false;
}
}
Edit MainActivity.java to add a single line to invoke the above as per
:-
public class MainActivity extends Activity {
private Session session;
//private Button button;
//DatabaseHelper myDbHelper = new DatabaseHelper(this); //<<<< COMMENTED OUT
DatabaseHelper myDbHelper; //<<<< ADDED
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CopyDBFromAssets cdbfa = new CopyDBFromAssets(this,DatabaseHelper.DB_NAME); //<<<< ADDED LINE
myDbHelper = new DatabaseHelper(this); //<<<< ADDED LINE
session = new Session(this);
// button = (Button)findViewById(R.id.button);
if(session.loggedin()){
startActivity(new Intent(MainActivity.this,Home.class));
finish();
}
}
........ the rest of MainActivity.Java
Notes
DatabaseHelper myDbHelper = new DatabaseHelper(this); has been commented out and split into declaration and instantiation (set)
check all lines with //<<<<
After making the changes above delete the App's data and run. Check the log you should see something along the lines of
:-
04-12 12:39:31.672 1568-1568/soanswers.soanswers D/DBASSETCOPY: Attempting to copy database mydb from assets folder.
04-12 12:39:31.672 1568-1568/soanswers.soanswers V/DBASSETCOPY: DB copied
04-12 12:39:31.672 1568-1568/soanswers.soanswers D/DBASSETCOPY: Database mydb successfully copied.
In the above the database used was called mydb rather than bmkgdb.db
You are inserting record into table which is not exist. Create table before performing insert operation.
Hello Techie :) i am new to android . i'm developing one app where user is registering with all personal detail and mobile device detail and after user login all the things working fine and met with result but when i'm moving to admin section here i have issue and i'm not getting any idea about this .
Parts of Admin section where i am stuck :-
1) after admin login , all table records should be shown in one table layout here u can say i want to populate all table records in Table Layout .
i try with specific user name and its showing in the table layout but it's not my requirement , i have to show all users in Table layout .
i'm sharing my code here , will u all suggest me what to do next and how can i achieve my requirement.
Thanks for your valuable time :)
//MainActivity.java
package com.example.yadapras.mobiltyemp;
import android.content.Context;
import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.VectorEnabledTintResources; import android.telephony.TelephonyManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;
/** * Created by yadapras on 6/26/2016. */ public class MainActivity extends AppCompatActivity {
EditText a,b;
String usr,pass;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v)
{
if (v.getId() == R.id.BLogin)
{
a = (EditText)findViewById(R.id.userName);
usr = a.getText().toString();
b = (EditText)findViewById(R.id.userPassword);
pass = b.getText().toString();
String password = null;
if( a.getText().toString().length() == 0 || usr == "" || usr == null)
a.setError( " User name is required!" );
if( b.getText().toString().length() == 0 || pass =="" || pass == null)
b.setError( "Password is required!" );
else{
password = helper.searchPass(usr);
}
if (a.getText().toString().equals("admin") && b.getText().toString().equals("admin"))
{
Intent intent = new Intent(getApplicationContext(), AdminDisplay.class);
startActivity(intent);
}else{
if (pass.equals(password) && password != null) {
Intent intent = new Intent(getApplicationContext(), EmpDetail.class);
intent.putExtra("usr", usr);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String uid = telephonyManager.getDeviceId();
String manufacturer = Build.MANUFACTURER; // Not used in current scenario
String model = Build.MODEL;
int version = Build.VERSION.SDK_INT;
String versionRelease = Build.VERSION.RELEASE; // not used in current scenario
String msg = "IMEI No: " + uid + "\n" + "Manufacturer is :" + manufacturer + "\n" + "Model is :" + model + "\n" + "Os Version is :" + version + "\n" + "VersionRelease is :" + versionRelease;
Toast toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG);
toast.show();
Register r = new Register();
r.setImei_no(uid);
r.setDev_model(model);
r.setOs_version(version);
r.setUname(usr);
helper.updateTable(r); /*For updating table with new Coloumn*/
startActivity(intent);
}
else
{
Toast err_pass = Toast.makeText(MainActivity.this,"UserName and Password don't Match",Toast.LENGTH_SHORT);
err_pass.show();
}
}
}
if (v.getId() == R.id.BSignup)
{
Intent intent = new Intent(getApplicationContext(), Registration.class);
startActivity(intent);
}
}
}
//DatabaseHelper.java
package com.example.yadapras.mobiltyemp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.ArrayMap;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by yadapras on 7/8/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "registrationDB.db";
public static final String TABLE_NAME = "registrations";
public static final String COLUMN_ID = "id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_PASSWORD= "password";
public static final String COLUMN_RE_PASSWORD= "re_password";
public static final String COLUMN_NAME= "name";
public static final String COLUMN_EMAIL= "email";
public static final String COLUMN_PHONE_NO= "phone_no";
/*Adding three coloumn IMEI_NO,OS_Version,Model_Device Respectively*/
public static final String COLUMN_IMEI_NO = "imei_no";
public static final String COLUMN_DEV_MODEL = "dev_model";
public static final String COLUMN_OS_VERSION = "os_version";
SQLiteDatabase sqLiteDatabase;
private static final String TABLE_CREATE = "create table registrations(id integer primary key not null, " +
"username text not null, password text not null, re_password text not null, name text not null, email text not null," +
"phone_no number not null,imei_no text, dev_model text, os_version text);";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);
this.sqLiteDatabase=sqLiteDatabase;
Log.d("#####Table Value",TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS " +TABLE_NAME ;
sqLiteDatabase.execSQL(query);
this.onCreate(sqLiteDatabase);
}
public void registerUser(Register r) {
/*Inserting anything in to the dataBase make sure it should be writable*/
sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
int count = cursor.getCount();
Log.d("##count",""+count);
values.put(COLUMN_ID,count);
Log.d("##id",r.getUname());
values.put(COLUMN_USERNAME,r.getUname());
values.put(COLUMN_PASSWORD,r.getPassword());
values.put(COLUMN_RE_PASSWORD,r.getRe_password());
values.put(COLUMN_NAME,r.getName());
values.put(COLUMN_EMAIL, r.getEmail());
values.put(COLUMN_PHONE_NO, r.getPhone_no());
sqLiteDatabase.insert(TABLE_NAME, null,values); /*this will insert Register object in to the Database*/
sqLiteDatabase.close();
}
public String searchPass(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query = "select username,password from "+TABLE_NAME;
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
String a,b ; // a and b will be userName and Password respectively
b = "Not Found";
if (cursor.moveToFirst())
{
do {
a = cursor.getString(0);
Log.d("##username from db",a);
if (a.equals(usr))
{
b = cursor.getString(1);
break;
}
}while (cursor.moveToNext());
}
return b;
}
public JSONObject showDetail(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p";
// String query = "SELECT * FROM registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
JSONObject data = new JSONObject();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
for (int idx=0; idx<columnsQty; ++idx) {
try {
data.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
public void updateTable(Register r) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
db.update(TABLE_NAME,cv,"username = ?",new String[]{r.getUname()});; /*Working for all fields*/
/*SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
String updateQuery = "Update registrations set " + COLUMN_IMEI_NO + " = '"+ r.getImei_no() +"' where " + COLUMN_USERNAME + "="+"'"+ r.getUname() +"'";
db.execSQL(updateQuery);
db.close();*/
}
}
//AdminDisplay.java
package com.example.yadapras.mobiltyemp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class AdminDisplay extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
TextView id,name,email,mobileno,imei_no,dev_model ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_display);
TableLayout table = (TableLayout)findViewById(R.id.tableLayout1) ;
id = (TextView)findViewById(R.id.admin_usr_id);
name = (TextView)findViewById(R.id.admin_Uname);
email = (TextView)findViewById(R.id.admin_usr_email);
mobileno = (TextView)findViewById(R.id.admin_usr_phone);
imei_no = (TextView)findViewById(R.id.admin_usr_imeiNo);
dev_model = (TextView)findViewById(R.id.admin_usr_dev_model);
JSONObject details = helper.showDetail("pcu9044"); // ***Here i'm trying registered user so i'm getting only this user field in TableLayout .***
for (int i=0; i<details.length();i++){
TableRow row = (TableRow)findViewById(R.id.tableRow1);
try {
table.removeView(row);
((TextView)row.findViewById(R.id.admin_usr_id)).setText(details.getString("id"));
((TextView)row.findViewById(R.id.admin_usr_email)).setText(details.getString("email"));
((TextView)row.findViewById(R.id.admin_Uname)).setText(details.getString("name"));
((TextView)row.findViewById(R.id.admin_usr_phone)).setText(details.getString("phone_no"));
((TextView)row.findViewById(R.id.admin_usr_imeiNo)).setText(details.getString("imei_no"));
((TextView)row.findViewById(R.id.admin_usr_dev_model)).setText(details.getString("dev_model"));
table.addView(row);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i'm attaching screen shot of my output, if yup people have nay doubt please feel free to ask . Thank u in advance .
Result output with my code
The problem that I see here is that when you say:
"i try with specific user name and its showing in the table layout but
it's not my requirement , i have to show all users in Table layout".
By searching for one single user from the database, you are only retrieving a single record in the database that is associated with the username you are searching for. Your method helper.showDetail() returns a single JSONObject - this object corresponds to the record in the database where username = pcu9044.
If I am understanding your situation correctly, you need to call a method that selects ALL of the records from the database in order to display what you want on the screen. Your helper.showDetail() will be a good start, but you can modify code slightly to achieve what you'd like.
I would recommend using either a list or array of JSONObjects instead of a single JSONObject. Initialize your data structure before you enter the if (cursor.moveToFirst()) conditional (like you have it now), but within each iteration of the loop, you create a new object, fill it with what the cursor returns for that row, and then add it to the structure. The code would look something like this:
public JSONArray showDetail() {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations";// * THIS WILL RETURN ALL RECORDS IN REGISTRATIONS
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
//JSONObject data = new JSONObject(); *change this to an array
JSONArray data = new JSONArray();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
// Must create a new object each time you iterate to a new row to add to the array
JSONObject record = new JSONObject();
for (int idx=0; idx<columnsQty; ++idx) {
try {
// Fill the object
record.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
// Add the object to the array and repeat
data.put(record);
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
If you do it this way, your helper.showDetail() will return an array filled with objects that each symbolize a row. From there, your AdminDisplay.java should then cycle through the array, grab each object, and fill a new row with the information you need.
Hope this helps!
Hello Techie :) I solved my problem after reading many articles on Table Layout over Internet. i'm giving this problems solution with Table-Layout hope this will help others .
AdminDisplay.java # Editable Version
package com.example.yadapras.mobiltyemp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class AdminDisplay extends AppCompatActivity {
TableLayout tableLayout;
private SQLiteDatabase db;
private Context context ;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_display);
context = this;
DatabaseHelper helper = new DatabaseHelper(this);
tableLayout = (TableLayout)findViewById(R.id.tableLayout1) ;
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText={"ID","USERNAME","EMAIL","PHONE_NO","IMEI_NO","DEV_MODEL"};
for(String c:headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
SQLiteDatabase db = helper.getReadableDatabase();
db.beginTransaction();
try
{
String selectQuery = "SELECT * FROM "+ DatabaseHelper.TABLE_NAME;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor.getCount() >0)
{
while (cursor.moveToNext()) {
// Read columns data
int id = cursor.getInt(cursor.getColumnIndex("id"));
String user_name= cursor.getString(cursor.getColumnIndex("username"));
String email= cursor.getString(cursor.getColumnIndex("email"));
String phone_no = cursor.getString(cursor.getColumnIndex("phone_no"));
String imei_no = cursor.getString(cursor.getColumnIndex("imei_no"));
String dev_model = cursor.getString(cursor.getColumnIndex("dev_model"));
// dara rows
TableRow row = new TableRow(context);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] colText={id+"",user_name,email,phone_no,imei_no,dev_model};
for(String text:colText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5, 5, 5, 5);
tv.setText(text);
row.addView(tv);
}
tableLayout.addView(row);
}
}
db.setTransactionSuccessful();
}
catch (SQLiteException e)
{
e.printStackTrace();
}
finally
{
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
}
Remove table.removeView(row); from the loop, if not you will get only one row at the end of the loop as it removes the previous row when a new row is added
for (int i=0; i<details.length();i++){
TableRow row = (TableRow)findViewById(R.id.tableRow1);
try {
((TextView)row.findViewById(R.id.admin_usr_id)).setText(details.getString("id"));
((TextView)row.findViewById(R.id.admin_usr_email)).setText(details.getString("email"));
((TextView)row.findViewById(R.id.admin_Uname)).setText(details.getString("name"));
((TextView)row.findViewById(R.id.admin_usr_phone)).setText(details.getString("phone_no"));
((TextView)row.findViewById(R.id.admin_usr_imeiNo)).setText(details.getString("imei_no"));
((TextView)row.findViewById(R.id.admin_usr_dev_model)).setText(details.getString("dev_model"));
table.addView(row);
} catch (JSONException e) {
e.printStackTrace();
}
}
Hi try this method i have just updated a method of your code, You can replace with your own method by.
Valiable isAdmin is true when admin get detail and false when user.
public JSONObject showDetail(String usr, boolean isAdmin)
{
sqLiteDatabase = this.getReadableDatabase();
String query = "";
if (isAdmin)
query = "SELECT * FROM registrations";
else
query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
JSONObject data = new JSONObject();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
for (int idx=0; idx<columnsQty; ++idx) {
try {
data.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
It may help you and Let me know if any query you have.
I am trying to write an app that has two buttons - the first brings up a list of contacts and the second sends a message to the selected contact. I am able to select a contact using startActivityForResult and onActivityResult, but I cannot return the contact's number to my main code where it would be read by the second button's onClick method. When running the code below, I get the toast message with the phone number but when I try to send a message I get the "Please select a contact first" message. I don't know how to make the "phoneNumber" variable in onActivityResult to send it to "phoneNumber" in my main activity. Thanks!
package com.example.testa;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidAlarmService extends Activity {
private PendingIntent pendingIntent;
private static final int PICK_CONTACT_REQUEST = 0;
private static final Uri CONTACTS_CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
static String phoneNumber = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button contacts_button = (Button) findViewById(R.id.getContacts);
contacts_button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(Intent.ACTION_PICK, CONTACTS_CONTENT_URI);
intent.setType(Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
} catch (Exception e) {
Log.e("AAS", "Found an error in contacts button");
}
}
});
final Button send_button = (Button) findViewById(R.id.send_button);
send_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
final String yourtext = "my message";
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
if (phoneNumber == ""){
Toast.makeText(AndroidAlarmService.this, "Please select a contact first" , Toast.LENGTH_SHORT).show();
//This is the message I get
return;
}
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("yourtext", yourtext);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
//this part is working
}
}
Change
String number = c.getString(0);
to
phoneNumber = c.getString(0);
This will store the phone number in the member variable rather than in a local variable. Now you can use this phoneNumber member variable in the click listener for your second button.
Note that phoneNumber == "" is an error. You should use equals() to compare String instances for equality.
I'm trying to create a Log in screen for an app in Android. I have stored information about users in a 'users' table in a database.
I'm trying to match the username and password entered at the log in screen with the values in the database using the cursor object but it doesnt work , causing the app to crash.
Can someone please recommend or revise the approach, if possible with some code snippets.
Will appreciate it big time, thanks.
Below is the code for the LoginForm class. (it uses a DBAdapter class to connect to the database)
package com.androidbook.LoginForm;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;
public class LoginForm extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DBAdapter db = new DBAdapter(getBaseContext());
final AutoCompleteTextView username = (AutoCompleteTextView)this.findViewById(R.id.AutoComUsernameLogin);
final AutoCompleteTextView password = (AutoCompleteTextView)this.findViewById(R.id.AutoComPasswordLogin);
Button Register = (Button) findViewById(R.id.ClicktoRegister);
Register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), RegistrationForm.class);
startActivityForResult(myIntent, 0);
}
});
//************************** LOG IN LOGIC******************************//
Button Login = (Button) findViewById(R.id.LoginButton);
Login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String Username = username.getText().toString();
final String Password= password.getText().toString();
db.open();
Cursor c = db.getAllTitles();
while(c.moveToNext())
{
String c1=c.getString(2);
String c2=c.getString(3);
if(c1 == Username)
{
if(c2 == Password)
{
Toast.makeText(LoginForm.this,
"You are succesfully logged in.",
Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(view.getContext(), Menu.class);
startActivityForResult(myIntent, 0);
}
else
{
Toast.makeText(LoginForm.this, "Incorrect password",Toast.LENGTH_LONG).show();
}
Intent myIntent = new Intent(view.getContext(), LoginForm.class);
startActivityForResult(myIntent, 0);
}
else
Toast.makeText(LoginForm.this, "Incorrect",Toast.LENGTH_LONG).show();
}
db.close();
}
});
}
}
The answer by Chirag Raval above functions but is vulnerable to SQL injection. A malicious user could easily bypass the authentication mechanism with a basic SQLi payload (as long as there were at least a single entry in the database being checked against).
A parameterized query with bounded values is the more secure approach.
Fixing the code snippet:
public int Login(String username,String password)
{
String[] selectionArgs = new String[]{username, password};
try
{
int i = 0;
Cursor c = null;
c = db.rawQuery("select * from login_table where username=? and password=?", selectionArgs);
c.moveToFirst();
i = c.getCount();
c.close();
return i;
}
catch(Exception e)
{
e.printStackTrace();
}
return 0;
}
This simple improvement is more secure and easier to code.
You can make one function in database class that will return the int number . if integer number is 1 then we can say that the user name and password is match other wise we can say login failed . There is no need to write complex code.
public int Login(String username,String password)
{
try
{
int i = 0;
Cursor c = null;
c = db.rawQuery("select * from login_table where username =" + "\""+ username.trim() + "\""+" and password="+ "\""+ password.trim() + "\""+, null);
c.moveToFirst();
i = c.getCount();
c.close();
return i;
}
catch(Exception e)
{
e.printStackTrace();
}
return 0;
}
When we try this code it asks to change type to boolean...
public int Login(String username,String password)
{
try
{
int i = 0;
Cursor c = null;
c = db.rawQuery("select * from login_table where username =" + "\""+ username.trim() + "\""+" and password="+ "\""+ password.trim() + "\""+, null);
c.moveToFirst();
i = c.getCount();
c.close();
return i;
}
catch(Exception e)
{
e.printStackTrace();
}
return 0;
}
I am having trouble getting a contact phone number, i keep getting an error in the log cat saying
02-24 19:40:42.772: ERROR/CursorWindow(21467): Bad request for field slot 0,-1. numRows = 1, numColumns = 24
here is my code
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.os.Bundle;
public class Contacts extends Activity {
private ListView mContactList;
private Button mAddContact;
private boolean mShowInvisible = false;
boolean set;
public String name = "";
public String id;
public String phone;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_listview);
mContactList = (ListView) findViewById(R.id.contactList);
mAddContact = (Button) findViewById(R.id.addContactButton);
mAddContact.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i,1);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode == RESULT_OK){
getContactData(data);
}
}
public void getContactData(Intent data){
ContentResolver cr = getContentResolver();
Uri contactData = data.getData();
Log.v("Contact", contactData.toString());
Cursor c = managedQuery(contactData,null,null,null,null);
if(c.moveToFirst()){
id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
Log.v("Contact", "ID: " + id.toString());
name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Contact", "Name: " + name.toString());
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
phone = c.getString(c.getColumnIndex(Phone.NUMBER));
Log.v("getting phone number", "Phone Number: " + phone);
}
}
}
}
everything reads fine up until the point where i try to get the phone number
Shouldn't it be:
while(pCur.moveToNext()){
phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
Log.v("getting phone number", "Phone Number: " + phone);
}
That is, pCur instead of the 'c' cursor, which holds the contacts?
You need to reset the cursor before calling "moveToNext()". Just call "pCur.moveToFirst();" right before the while. That should help.
i got it, i took out the while loop and i get the number fine now