Can't run app on device when click sign up button - android

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.

Related

Passing data from one listview to another

I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the checkbox.But the data doesn't get transferred. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
}
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artist.sender/com.example.artist.sender.contacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
This is the logcat for the error. It keeps showing that the setitemOnClickListener keeps referring to a null object whereas, I've already assigned the listview to its respective id.
EDIT:**I've fixed part of the error, by renaming the setContentView(R.layout.activity_main); in the contacts class to setContentView(R.layout.contacts); But now after that, it shows this error, **java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
If the data in the database, or some other storage, only pass the _id or the location, respectively.
Instead of passing many extras, Android way is, actually, Parcable. Here a nice tutorial from Vogella
public class TestModel implements Parcelable {
String name;
String phoneNumber;
//.....
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.phoneNumber);
}
public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
#Override
public TestModel createFromParcel(Parcel source) {
return new TestModel(source);
}
#Override
public TestModel[] newArray(int size) {
return new TestModel[size];
}
};
}

Passing data from one listview to another textview

I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the data.But the app crashes just on clicking the contacts button. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
{
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.artist.sender.contacts.getContacts(contacts.java:236)
at com.example.artist.sender.contacts$1.run(contacts.java:57)
at java.lang.Thread.run(Thread.java:818)
This is the logcat for the error. It keeps showing that the findViewById keeps referring to a null object whereas, I've already assigned all the variables to their respective ids.

How to add row dynamically in table layout or How to show full db Records in single table Layout

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.

How to insert selected image in a SqlLite database ?

My code is not inserting image in database. How can I insert selected image in the database, and also retrieve it ? I'm following this tutorial:
http://vimaltuts.com/android-tutorial-for-beginners/android-sqlite-database-example
What modifications the code below requires to insert selected image in database ?
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private EditText Donedate;
private EditText Notes;
private EditText Person;
private ImageView imageView1;
Bitmap yourSelectedImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.Address);
capEt = (EditText) findViewById(R.id.Stage);
codeEt = (EditText) findViewById(R.id.Dueby);
Donedate = (EditText) findViewById(R.id.Donedate);
Notes = (EditText) findViewById(R.id.Notes);
Person = (EditText) findViewById(R.id.Person);
imageView1 = (ImageView) findViewById(R.id.imageView1);
Button Browse = (Button) findViewById(R.id.Browse);
Browse.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
Donedate.setText(extras.getString("Location"));
Notes.setText(extras.getString("Notes"));
Person.setText(extras.getString("Person"));
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new
AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
// ByteArrayOutputStream outStr = new ByteArrayOutputStream();
// yourSelectedImage.compress(CompressFormat.PNG, 100, outStr);
// byte[] blob = outStr.toByteArray();
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString()
//,blob
);
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString()
//, blob
);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path
of selected image
cursor.close();
// Convert file path into bitmap image using below
line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imageView1.setImageBitmap(yourSelectedImage);
}
}
}
}
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}
public void insertContact(String name, String cap, String code, String
LocationEd, String Notes, String Person)
///,byte[] blob)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("code", code);
newCon.put("Location",LocationEd);
newCon.put("Notes",Notes);
newCon.put("Person",Person);
// newCon.put("Image", blob);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String
cap,String code,String LocationEd, String Notes, String Person)
//,byte[] blob)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("code", code);
editCon.put("Location", LocationEd);
editCon.put("Notes", Notes);
editCon.put("Person", Person);
// editCon.put("Image", blob);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id",
"name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null,
null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE country (_id integer primary key
autoincrement,name text,cap text,code text,Location double,Notes text,Person
text,blob BLOB);";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
import java.io.ByteArrayInputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ViewCountry extends Activity {
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView Locationlb;
private TextView Noteslb;
private TextView Personlb;
byte[] byteImage2 = null;
private ImageView imageView2;
Bitmap yourSelectedImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
codeTv = (TextView) findViewById(R.id.codeText);
Locationlb = (TextView) findViewById(R.id.Location_lbl);
Noteslb = (TextView) findViewById(R.id.Notes_lbl);
Personlb = (TextView) findViewById(R.id.Person_lbl);
imageView2= (ImageView) findViewById(R.id.imageView2);
Button Browse2 = (Button) findViewById(R.id.Browse2);
Browse2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onResume()
{
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params)
{
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result)
{
super.onPostExecute(result);
result.moveToFirst();
// get the column index for each data item
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int LocationIndex = result.getColumnIndex("Location");
int NotesIndex = result.getColumnIndex("Notes");
int PersonIndex = result.getColumnIndex("Person");
// byte[] blob = result.getBlob("image");
// byte[] data = result.getBlob(result.getColumnIndex("image"));
// byte[] blob result.getColumnIndex(MyBaseColumn.MyTable.ImageField));
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
codeTv.setText(result.getString(codeIndex));
Locationlb.setText(result.getString(LocationIndex));
Noteslb.setText(result.getString(NotesIndex));
Personlb.setText(result.getString(PersonIndex));
// ByteArrayInputStream input = new ByteArrayInputStream(byteImage2);
// Bitmap bit = BitmapFactory.decodeStream(input);
// imageView2.setImageBitmap(bit);
// imageView2.setImageURI(byteImage2);
imageView2.setImageBitmap(yourSelectedImage);
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("Location", Locationlb.getText());
addEditContact.putExtra("Notes", Noteslb.getText());
addEditContact.putExtra("Person", Personlb.getText());
// addEditContact.putExtra("blob", yourSelectedImage);
startActivity(addEditContact);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact()
{
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DatabaseConnector dbConnector =
new DatabaseConnector(ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#Override
protected Object doInBackground(Long... params)
{
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path
of selected image
cursor.close();
// Convert file path into bitmap image using below
line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imageView2.setImageBitmap(yourSelectedImage);
}
}
}
}
Do not put images into database. Keep the file on the filesystem (SD card or internal storage) and put reference to it into database. But do not put images directly.
There's no need to put a binary blob in a database. The primary goal of a database is to be queried, ie it organizes data so that it's fast to locate it later. An image is a sequence of bytes, and you won't be able to filter your query based on it, so simply store the image in the filesystem, and maybe adopt a convention that it will be named after the row's ID.

listview items disappearing

So.. my listview items are disappearing after they're scrolled off the screen. They're there, you scoll down, back up, and they're gone. After rotation they reappear, but I have no idea why this is happening.
package com.teslaprime.prirt;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.content.ContentValues;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ListView;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
public class TaskList extends Activity {
List<Task> tasks = new ArrayList<Task>();
TaskAdapter adapter = null;
SQLiteDatabase db = null;
public void populateList(){
adapter = new TaskAdapter();
adapter.clear();
Cursor cur = db.query("tasks",null,null,null,null,null,"timestamp");
cur.moveToFirst();
int anchor = 0;
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 1) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
task.completed = 1;
adapter.add(task);
anchor = anchor+1;
}
cur.moveToNext();
}
cur.moveToFirst();
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 0) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
adapter.add(task);
}
cur.moveToNext();
}
cur.close();
for (int i = tasks.size(); i <= 8; i++) {
adapter.add(new Task());
}
ListView list = (ListView) findViewById(R.id.tasks);
list.setAdapter(adapter);
list.setSelection(anchor);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent setupProcess = new Intent (TaskList.this, SetupWelcome.class);
boolean first = checkDatabase() ? true : false;
db = openOrCreateDatabase("priRT.db",
SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.setVersion(1);
db.setLockingEnabled(true);
db.execSQL("create table if not exists tasks ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "time integer,"
+ "completed integer,"
+ "timestamp integer,"
+ "spacer integer,"
+ "type text);");
db.execSQL("create table if not exists schedule ("
+ "id integer primary key autoincrement,"
+ "hours_free integer);");
if (first) { startActivityForResult(setupProcess,0); }
populateList();
Button add = (Button) findViewById(R.id.addTask);
add.setOnClickListener(onAdd);
}
public View.OnClickListener closeTaskListener = new View.OnClickListener(){
public void onClick(View v){
int pos = (Integer) (v.getTag());
Task task = adapter.getItem(pos);
ContentValues values = new ContentValues();
if (task.completed == 1){
values.put("completed", 0);
task.completed = 0;
} else {
values.put("completed", 1);
task.completed = 1;
}
Long time = new Date().getTime();
values.put("timestamp", time);
db.update("tasks", values, "id='"+task.id+"'", null);
populateList();
}
};
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(
"/data/data/com.teslaprime.prirt/databases/priRT.db", null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {}
return checkDB == null ? true : false;
}
private View.OnClickListener onAdd = new View.OnClickListener() {
public void onClick(View view) {
Intent addTask = new Intent (view.getContext(), TaskEntry.class);
startActivityForResult(addTask, 2);
}
};
protected void onActivityResult(int req, int res, Intent data) {
if (req == 0 && res == RESULT_OK) {
Intent setup = new Intent (TaskList.this, SetupWizard.class);
startActivityForResult(setup, 1);
}
if (req == 2 && res == RESULT_OK) {
Task task = new Task(data.getStringExtra("name"),data.getStringExtra("type"));
adapter.add(task);
ContentValues values = new ContentValues();
values.put("name", data.getStringExtra("name"));
values.put("type", data.getStringExtra("type"));
values.put("completed", 0);
values.put("spacer", 0);
db.insert("tasks", null, values);
Cursor cur = db.query("tasks", null, null, null, null, null, null);
cur.moveToLast();
task.id = cur.getInt(cur.getColumnIndex("id"));
cur.close();
populateList();
}
}
class TaskAdapter extends ArrayAdapter<Task> {
TaskAdapter() {super(TaskList.this,R.layout.task,tasks);}
private List<Task> taskList;
private Context context;
public View getView(int pos, View convertView, ViewGroup parent) {
View task = convertView;
if (convertView == null) {
LayoutInflater inflater = getLayoutInflater();
task = inflater.inflate(R.layout.task,null);
}
if (tasks.get(pos).spacer == 0) {
TextView taskName = (TextView) task.findViewById(R.id.name);
TextView taskType = (TextView) task.findViewById(R.id.type);
taskName.setText(tasks.get(pos).name);
taskType.setText(tasks.get(pos).type);
Task taskList = adapter.getItem(pos);
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
if (taskList.completed == 0) {
closeTask.setChecked(false);
} else {
closeTask.setChecked(true);
}
closeTask.setTag(pos);
closeTask.setOnClickListener(closeTaskListener);
} else {
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
task.setVisibility(View.GONE);
task.setFocusable(false);
task.setClickable(false);
}
return task;
}
}
}
It may be happening because of the background color of surface in which list appears. Try setting the background color to white in linerlayout and text view coolr black then scroll the through the list view again.

Categories

Resources