How to insert selected image in a SqlLite database ? - android

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.

Related

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

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.

Getting images from SQLite database and displaying them into GridView Android Studio

I am new to Android Studio and I have been having some trouble with getting images, which have been stored into a database, and then displaying them into a GridView. Is there a way I can get the number of images stored in the database and then displaying them one by one, each in a different cell within GridView? This is my code so far:
NewsAddImageActivity class
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class NewsAddImageActivity extends AppCompatActivity {
//public MyDatabaseHelper dbHelper;
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
Bitmap bitmap;
int tabNo;
Tab1Class t1;
Tab2Class t2;
Tab3Class t3;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsaddimage);
final ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadImagefromGallery(v);
}
});
Button submit = (Button) findViewById(R.id.addButton);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
dbHelper.addEntry(dbHelper.getBytes(bitmap)); //add image to database
byte[] image = cursor.getBlob(1); //get image from database as byte
dbHelper.getImage(image); //converts byte to bitmap
if(tabNo==0){
//place image in the grid view of tab1
}else if(tabNo==1) {
//place image in the grid view of tab2
}else if(tabNo==2){
//place image in the grid view of tab3
}
finish();
Toast.makeText(getApplicationContext(),"Added",Toast.LENGTH_LONG).show();
}
});
Button cancel = (Button) findViewById(R.id.cancelButton);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
finish();
Toast.makeText(getApplicationContext(),"Cancelled",Toast.LENGTH_LONG).show();
}
});
}
private byte[] imageButtonToByte(ImageButton image){
Bitmap bitmap=((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray=stream.toByteArray();
return byteArray;
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
bitmap = ((BitmapDrawable) imageButton.getDrawable()).getBitmap();
// Set the Image in ImageView after decoding the String
imageButton.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public void getTab(int num){
switch(num) {
case 0: tabNo=0;
case 1: tabNo=1;
case 2: tabNo=2;
}
}
}
MyDatabaseHelper Class
package com.example.mobilecomputingapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
public class MyDatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ImagesDB";
// Table Names
private static final String DB_TABLE = "imageTable";
// column names
private static final String KEY_NAME = "image_name";
private static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
/* public void addEntry( String name, byte[] image) throws SQLiteException {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE, null, cv );
}*/
public void addEntry( byte[] image) throws SQLiteException {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE, null, cv );
}
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
you can create a bitmap of images which you want to select to save in db < don't save images save the URI(Path) of image like this.In this code selectedd images is an array which holds the selected images .And you should make method of insert images in Dbhelper and pass the string like this ..
Bitmap bitmap = thumbnails[i];
Uri uri = Utility.getImageUri(getContext(),bitmap);
byte[] path = Utility.getBytes(bitmap);
cnt++;
selecteddimages.add(uri);
String s = uri.toString();
databaseHelper.insertContact(s);
DBHELPER method of insert
public void insertContact (String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
long result=db.insert("images", null, contentValues);
if (result==-1){
Toast.makeText(context,"not save",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"save",Toast.LENGTH_SHORT).show();
}
}
UTILITIES CLass for getimage URI
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
return stream.toByteArray();
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "title", null);
return Uri.parse(path);
}

how to close contact list after pick (android)

**im trying to do n sms app and im using this code to pick some data from contact my
probleam is when im closing my app the contact list is still opend.. how can i close it?
is there any way to pick the data and force close the contact list activity?
**
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnTouchListener{
TextView a1,a2;
EditText contact,message;
Button send;
String name,phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initilaize();
}
public void initilaize(){
a1 = (TextView)findViewById(R.id.tVContact);
a2 = (TextView)findViewById(R.id.tVMessage);
contact = (EditText)findViewById(R.id.eTContact);
message = (EditText)findViewById(R.id.eTMessage);
send = (Button)findViewById(R.id.button1);
name ="";
phoneNumber="";
contact.setOnTouchListener(this);
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri contactData = data.getData();
try {
String id = contactData.getLastPathSegment();
Cursor phoneCur = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
final ArrayList<String> phonesList = new ArrayList<String>();
while (phoneCur.moveToNext()) {
// This would allow you get several phone addresses
// if the phone addresses were stored in an array
String phone = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phonesList.add(phone);
}
phoneCur.close();
//
String name="";
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
}
c.close();
//
if (phonesList.size() == 0) {
} else{
phoneNumber = phonesList.get(0);
this.name = name;
contact.setText(name);
} } catch (Exception e) {
Log.e("FILES", "Failed to get phone data", e);
}
}
}
}
public boolean onTouch1(View v, MotionEvent arg1) {
switch(v.getId()){
case R.id.eTContact:{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent,0);
break;
}
case R.id.button1:{
}
}
return true;
}
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}

how to save image in sqllite database?

this is my code below which browse imagew gellery and pick image but how do insert image view in database? this code sucessfuly show on screen selected image but not store in database how to pass image parameter? in that line where i comment/what i write here/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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"));
imageView1.setImageURI(yourSelectedImage);
}
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()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
/* what i write here for image*/
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(), null
);
}
else
/* what i wirte here for image*/ {
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(), null
);
}
}
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);
}
}
}
}
First make field in sqlite as blob datatype
than get byte and store in databse image.getBytes();
or if you have bitmap than convert into byte array
and store into database
public static byte[] getBitmapAsByteArray(Bitmap bitmap, boolean type) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (type) {
bitmap.compress(CompressFormat.PNG, 0, outputStream);
} else {
bitmap.compress(CompressFormat.JPEG, 0, outputStream);
}
return outputStream.toByteArray();
}
Please use below code for store images into sqlite database, it will solve your problem.
MySQLActivity.java:-
public class MySQLActivity extends Activity implements OnClickListener
{
protected static TextView textView;
protected static ImageView bmImage;
protected Button start;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bmImage = (ImageView)findViewById(R.id.imageView1);
textView = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(this);
DownloadFile();
}
public void onClick(View v)
{
SQLiteDatabase myDb;
String MySQL;
int icount;
byte[] byteImage1 = null;
byte[] byteImage2 = null;
MySQL="create table emp1(_id INTEGER primary key autoincrement, fio TEXT not null, picture BLOB);";
myDb = openOrCreateDatabase("/sdcard/Nick/MyWeatherDB.db", Context.MODE_PRIVATE, null);
String s=myDb.getPath();
textView.append("\r\n" + s+"\r\n");
myDb.execSQL("delete from emp1");
ContentValues newValues = new ContentValues();
newValues.put("fio", "Иванов Петр Сергеевич");
/////////// insert picture to blob field /////////////////////
try
{
FileInputStream instream = new FileInputStream("/sdcard/Dipak/Keshariya.png");
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
textView.append("\r\n" + byteImage1.length+"\r\n");
newValues.put("picture", byteImage1);
long ret = myDb.insert("emp1", null, newValues);
if(ret<0) textView.append("\r\n!!! Error add blob filed!!!\r\n");
} catch (IOException e) {
textView.append("\r\n!!! Error: " + e+"!!!\r\n");
}
////////////Read data ////////////////////////////
Cursor cur = myDb.query("emp1",null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false)
{
textView.append("\r\n" + cur.getString(1)+"\r\n");
cur.moveToNext();
}
///////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2=cur.getBlob(cur.getColumnIndex("picture"));
bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0, byteImage2.length));
textView.append("\r\n" + byteImage2.length+"\r\n");
//////////////////////////
cur.close();
myDb.close();
}
public void DownloadFile()
{
Bitmap bitmap1 = null;
bitmap1 = BitmapFactory.decodeFile("/sdcard/Dipak/Dipak.jpg"); //weather.png");
bmImage.setImageBitmap(bitmap1);
}
}
i would suggest to avoid saving images to database , not only on android .
this makes sense since it will slow down anything that is related to the database . also , the cursor won't be able to cache the results in order to move between the rows of the tables.
instead , put a filename to point to a path on your app's storage . you could also add where it's stored (internal/external storage) .

My edittext not showing the callLog numbers when pressed eventhough i am able to get into callLog

After some research and coding, I am able to get into my callLog. after i added more codes so that I am able to retrieve the numbers from callLog to my edittext, there seem to be errors. I have googled on this but so far to no avail. Any advise? -Simon-
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SimonCallLogActivity extends Activity {
/** Called when the activity is first created. */
EditText display;
Button log;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//to go to Call Log//
log=(Button)findViewById(R.id.button1);
log.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent myIntent=new Intent();
myIntent.setAction(Intent.ACTION_CALL_BUTTON);
startActivity(myIntent);
}
});
}
//Call Log//
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final EditText number = (EditText) findViewById(R.id.editText1);
Cursor cursor = null;
String phoneNo = " ";
List<String> logNumbers = new ArrayList<String>();
String[] projection = new String[] {CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.CACHED_NAME};
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = managedQuery(contacts, projection, null, null, CallLog.Calls.DATE + " ASC");
getColumnData(managedCursor);
}
private void getColumnData(Cursor cur){
try{
if (cur.moveToFirst()) {
String name;
String number;
long date;
int nameColumn = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
int numberColumn = cur.getColumnIndex(CallLog.Calls.NUMBER);
int dateColumn = cur.getColumnIndex(CallLog.Calls.DATE);
System.out.println("Reading Call Details: ");
do {
name = cur.getString(nameColumn);
number = cur.getString(numberColumn);
date = cur.getLong(dateColumn);
System.out.println(number + ":"+ new Date(date) +":"+name);
// number.setText(numberColumn);
} while (cur.moveToNext());
}
}
finally
{
cur.close();
}
final String [] items = logNumbers.toArray(new String[logNumbers.size() ]) ;
AlertDialog.Builder builder = new AlertDialog.Builder(SimonCallLogActivity.this);
builder.setTitle("Choose a number: ");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
String selectedNumber = items[item].toString();
selectedNumber= selectedNumber.replace("-","");
selectedNumber= selectedNumber.replace("Home:", "");
selectedNumber= selectedNumber.replace("Mobile:", "");
selectedNumber= selectedNumber.replace("Work:", "");
selectedNumber= selectedNumber.replace("Other:", "");
//selectedNumber = selectedNumber.replace("+","");
number.setText(selectedNumber);
}
});
AlertDialog alert = builder.create();
if(logNumbers.size()>1){
alert.show();
}else{
String selectedNumber= phoneNo.toString();
selectedNumber=selectedNumber.replace("-", "");
number.setText(selectedNumber);
}
if(phoneNo.length()==0){
Log.d("SIMON", "No contact");
}
}
break;
}
}else
{
//gracefully handle failure
Log.w("SIMON","Warning activity not okay");
}
}
}
Declare logNumbers and number as members of your SimonCallLogActivity class.
public class SimonCallLogActivity extends Activity {
/** Member variables */
EditText display;
Button log;
List<String> logNumbers = new ArrayList<String>();
EditText number;
...
...
}
Remove their local declarations..

Categories

Resources