Adding Data to SQLiteDatabase - java

I have a SQLite DB file in assets which is then imported in the application.
The select query works fine and shows the results but at the same time if I try to insert data into the table it does not work. I get no error so that I can identify the problem.
DatabaseHelper class: addProject() method is to insert data.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DB_VERSION=1;
private static String DB_PATH="";
private static final String DB_NAME="AndroidProject.sqlite";
//Projects Table attrib
String TABLE_PROJECT="Project";
String KEY_PROJECT_ID = "_id";
String KEY_PROJECT_NAME = "project_name";
String KEY_PROJECT_DESC = "project_desc";
String KEY_PROJECT_TYPE = "project_type";
String KEY_PROJECT_START_DATE = "start_date";
String KEY_PROJECT_END_DATE = "end_date";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (Build.VERSION.SDK_INT>=15){
DB_PATH=context.getApplicationInfo().dataDir + "/databases/";
}
else {
DB_PATH= Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/databases/";
}
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void checkAndCopyDatabase(){
boolean doExists=checkDatabase();
if (doExists){
Log.d("TAG", "Database alredy exists");
}
else{
this.getReadableDatabase();
}
try {
copyDatabase();
} catch (IOException e) {
e.printStackTrace();
Log.d("TAG", "Error Copying DATABASE");
}
}
public boolean checkDatabase(){
SQLiteDatabase checkDB=null;
try {
String myPath=DB_PATH+DB_NAME;
checkDB=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
}catch (SQLiteException e){
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public void copyDatabase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase(){
String myPath = DB_PATH + DB_NAME;
myDatabase=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close(){
if (myDatabase != null){
myDatabase.close();
}
super.close();
}
public Cursor QueryData(String query){
return myDatabase.rawQuery(query,null);
}
public void addProject(SqlProjects blog){
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PROJECT_NAME, blog.get_project_name());
values.put(KEY_PROJECT_DESC, blog.get_project_desc());
values.put(KEY_PROJECT_TYPE, blog.get_project_type());
values.put(KEY_PROJECT_START_DATE, blog.get_project_start_date());
values.put(KEY_PROJECT_END_DATE, blog.get_project_end_date());
try {
Log.d("TAG", "Adding data");
myDatabase.insertOrThrow(TABLE_PROJECT, null, values);
} catch (SQLiteException e) {
e.printStackTrace();
}
myDatabase.close();
}
}
SqlProjects class Constructor, getters and setters
public class SqlProjects {
private DatabaseHelper helper;
int _id;
String _project_name, _project_desc,_project_type;
String _project_start_date,_project_end_date;
public SqlProjects() {
}
public SqlProjects(String _project_name, String _project_desc, String _project_type, String _project_start_date, String _project_end_date) {
this._project_name = _project_name;
this._project_desc = _project_desc;
this._project_type = _project_type;
this._project_start_date = _project_start_date;
this._project_end_date = _project_end_date;
}
public SqlProjects(int _id, String _project_name, String _project_desc, String _project_type, String _project_start_date, String _project_end_date) {
this._id = _id;
this._project_name = _project_name;
this._project_desc = _project_desc;
this._project_type = _project_type;
this._project_start_date = _project_start_date;
this._project_end_date = _project_end_date;
}
public int get_project_id() {
return _id;
}
public void set_project_id(int _project_id) {
this._id = _project_id;
}
public String get_project_name() {
return _project_name;
}
public void set_project_name(String _project_name) {
this._project_name = _project_name;
}
public String get_project_desc() {
return _project_desc;
}
public void set_project_desc(String _project_desc) {
this._project_desc = _project_desc;
}
public String get_project_type() {
return _project_type;
}
public void set_project_type(String _project_type) {
this._project_type = _project_type;
}
public String get_project_start_date() {
return _project_start_date;
}
public void set_project_start_date(String _project_start_date) {
this._project_start_date = _project_start_date;
}
public String get_project_end_date() {
return _project_end_date;
}
public void set_project_end_date(String _project_end_date) {
this._project_end_date = _project_end_date;
}
}
Main Class
final DatabaseHelper db = new DatabaseHelper(Add_Project.this);
btnAddProjects.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!(TextUtils.isEmpty(editName.getText().toString())) && !(TextUtils.isEmpty(editDesc.getText().toString())) && !(tvStartDate.getText().equals("")) && !(tvEndDate.getText().equals(""))) {
db.addProject(new SqlProjects(editName.getText().toString(), editDesc.getText().toString(), editType.getSelectedItem().toString(), tvStartDate.getText().toString(), tvEndDate.getText().toString()));
editName.setText("");
editDesc.setText("");
tvStartDate.setText("");
tvEndDate.setText("");
Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
});

I think you have forgot to open the database before insert operation.
btnAddProjects.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!(TextUtils.isEmpty(editName.getText().toString())) && !(TextUtils.isEmpty(editDesc.getText().toString())) && !(tvStartDate.getText().equals("")) && !(tvEndDate.getText().equals(""))) {
//open db before any operation
db.openDatabase();
db.addProject(new SqlProjects(editName.getText().toString(), editDesc.getText().toString(), editType.getSelectedItem().toString(), tvStartDate.getText().toString(), tvEndDate.getText().toString()));
editName.setText("");
editDesc.setText("");
tvStartDate.setText("");
tvEndDate.setText("");
Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
onBackPressed();
}
}
});
Seems like the issue anyways check it out!

Related

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database- Logic issue in application

I am learning android yet and not expert. I think I have some logic issue in handle my sqllite database. Let me explain what I am doing and what I am getting.
I have one application of quotes. I am providing local database as well online. I have included database file in Assets and copying database from it during first time when user open application from splash screen. After that I am checking last author and last quote number of local database which are stored in user's device and comparing with online database. If there new data in online then I am downloading and storing it in splash screen.
Now my splash screen code for do same is like below
DAO database=DAO.getInstance(this);
int lastAuthor =database.getLastAuthor();
String updatesUrl = constant.MainUrl + String.valueOf(lastAuthor)+ "/" + String.valueOf(lastQuote);
My DAO class is looking like this
public class DAO {
private SQLiteDatabase database;
private DBHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_TIME = "qu_time";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
private static DAO dBObject;
private final Object lockObj=new Object();
public static DAO getInstance(Context context){
if(dBObject==null)dBObject=new DAO(context);
return dBObject;
}
private DAO(Context context) {
synchronized (lockObj) {
dbHandler = new DBHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
dbHandler.openDataBase();
open();
}
}
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
int tmp = cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
cursor.close();
return tmp;
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
int tmp = cursor.getInt(cursor.getColumnIndex(QU_ID));
cursor.close();
return tmp;
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int _quid, String qu_time) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_ID, _quid);
v.put(QU_TIME, qu_time);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
//method changed
private void open() throws SQLException {
if(database!=null&&database.isOpen())return; //changed line
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDAO(){
synchronized (lockObj){
if(dbHandler!=null)dbHandler.close();
dbHandler=null;
database=null;
}
}
public static void dispose(){
if(dBObject!=null){
dBObject.closeDAO();
}
dBObject=null;
}
}
And My database handler class looking like this
public class DBHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "xxx";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DBHandler(Context context) {
super(context, DB_NAME, null, constant.DATABASE_VERSION);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I am getting errors in logcat like this
Failed to open database '/data/user/0/com.newdeveloper.test/databases/xxx'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:835)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:820)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:723)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:692)
at com.newdeveloper.test.utility.DBHandler.checkDataBase(DBHandler.java:69)
at com.newdeveloper.test.utility.DBHandler.createDataBase(DBHandler.java:32)
at com.newdeveloper.test.utility.DAO.<init>(DAO.java:41)
at com.newdeveloper.test.utility.DAO.getInstance(DAO.java:31)
at com.newdeveloper.test.activities.SplashScreensActivity.checkForUpdate(SplashScreensActivity.java:111)
at com.newdeveloper.test.activities.SplashScreensActivity.access$000(SplashScreensActivity.java:41)
at com.newdeveloper.test.activities.SplashScreensActivity$1.onAnimationEnd(SplashScreensActivity.java:98)
at android.view.animation.AnimationSet.getTransformation(AnimationSet.java:400)
However application does not getting crashed and working fine as I
need. But This errors are confusing me what I need to change for
resolve this errors. I am trying to solve from last two days but not
found any working solution for it. Let me know if any senior developer
can help me for come out from this. Thanks
If you are not already using a bundled database with your apk, you have not actually created the database here in your code.
#Override
public void onCreate(SQLiteDatabase db) {
//you must create the database here
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Handle the database update here
}
You need to do something like this.
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_STRING);
} catch (SQLException e) {
e.printStackTrace();
}
Log.e(TAG, "Table Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_STRING);
onCreate(db);
Log.d(TAG, "Table upgraded to Version :" + newVersion);
}
I would also recommend to start using ROOM Android Architecture Component, which provides much better abstraction level for the Sqlite for the pattern are using.

how to pass Position wise object data one activity to another using recyclerview and databse in android

I have create the recycerview and this recycerview display the Person image ,person name and + button when i have press + button change the button image like true.and after recycerview bottom one button this button click all data show the next activity..
My Adapter
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
public BuildCustomAdapter(List<People> buildList) {
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.isSelected());
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// public ImageView ivPeopleImage;
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
}
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
People people = peopleList.get(mPosition);
people.setSelected(!people.isSelected());
notifyDataSetChanged();
}
}
Activity
public class BulidActivity extends AppCompatActivity {
private List<People> peopleList = new ArrayList<>();
private List<People> peopleListCopy = new ArrayList<>();
private RecyclerView recyclerView;
private BuildCustomAdapter buildCustomAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bulid);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BuildData();
peopleListCopy.addAll(peopleList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
AddTxt();
BtnBuildNow();
}
private void BtnBuildNow() {
Button btnnuildnow = (Button) findViewById(R.id.btn_build_now);
btnnuildnow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BulidActivity.this, AlertList.class);
startActivity(intent);
}
});
}
private void AddTxt() {
EditText editTxt = (EditText) findViewById(R.id.etSearch);
editTxt.setTextColor(Color.WHITE);
editTxt.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.setFocusable(true);
v.setFocusableInTouchMode(true);
return false;
}
});
editTxt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() <= 0) {
peopleList.clear();
peopleList.addAll(peopleListCopy);
recyclerView.setAdapter(null);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
recyclerView.setAdapter(buildCustomAdapter);
} else {
buildCustomAdapter.getFilter().filter(s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<People> BuildData() {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
if (db.open()) {
peopleList = db.getPeople();
}
return peopleList;
}
Model class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private boolean selected;
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
DatabaseHelper.class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/databasename/databases/";
private static final String DB_NAME = "alertme.db";
private final String TABLE_PEOPLE = "people";
private final String TABLE_CATEGORY = "category";
private final String CATEGORY_NAME = "name";
private final String ID = "id";
private final String CATEGORY_ID = "category_id";
private final String PEOPLE_IMAGE = "image";
private final String PEOPLE_NAME = "name";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch (SQLException sqle) {
myDataBase = null;
return false;
}
}
public List<People> getPeople(String category_id) {
List<People> peoples = new ArrayList<>();
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery("select * from people where category_id = " + category_id, null);
while (cursor.moveToNext()) {
String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));
String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
People people = new People();
people.setPeopleName(peopleName);
people.setPeopleImage(peopleImage);
peoples.add(people);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return peoples;
}
public List<Category> getCategory() {
List<Category> categoryList = new ArrayList<>();
try {
String query = " SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int categoryID = cursor.getInt(cursor.getColumnIndex(ID));
String categoryName = cursor.getString(cursor.getColumnIndex(CATEGORY_NAME));
Category category = new Category();
category.setId(categoryID);
category.setCategoryName(categoryName);
categoryList.add(category);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return categoryList;
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
First you should implement Serializable interface in your Build model class like this :-
public class Build implements Serializable{
//Content will be as it is
}
Change your clickListener like this :-
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("build",build);
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
In the onCreate method of receiving activity write this :-
Build build = (Build) getIntent().getSerializableExtra("build");
Add Intent in below Method,
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("key","value");
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
Huge mistak that you register to the click event on your ViewHolder! you will get diffrent position from the actual because when android use notifyItemMoved the viewBindHolder will not be called and than you got the wrong position.
and in the click listener implementation you should pass Intent with your data

pass Data from a List View (generated from Rest Api) to another activity and save that into SQLite Database

I am creating an android app (still the basic structure, without any design) from an Job site through XML feed using REST api.
Till now, I could managed to parse the XML data, displaying the List View with an POP UP menu item on each row. I am passing Data from PostBaseAdapter to MarkAsFav class. Could You please tell me if I am doing right or not? coz, I am getting no any data saved in database
Now, I have a problems:
I have 3 pop up menu item:
1. Set as Favourite
2. Share on Fb
3. email to Your friend
I am working on point number-1.
For now,I would be saving the data in SQLite Database itself. so, I am passing all the data (all the details about the job with all rows) to another activity, more over I am accepting a user given name to save the details through insertDB() in my Database.
But, unfortunately , nothing is getting saved in the database .
Can you tell me, if the data is getting passed or not and if the datas are being saved in database or not?
Please help me out. Please tell me where and how to modify the code?
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MarkAsFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
Intent extras = getIntent();
if (extras != null) {
int Value = extras.getIntExtra("id",0);
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.JOBS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText((CharSequence) nam);
header.setFocusable(false);
header.setClickable(false);
}
}
}
public void run(View view) {
Intent extras = getIntent();
if (extras != null) {
int val = extras.getIntExtra("id",0);
String value1 = extras.getStringExtra("title");
String value2= extras.getStringExtra("company");
String value3= extras.getStringExtra("city");
String value4= extras.getStringExtra("state");
String value5= extras.getStringExtra("country");
String value6= extras.getStringExtra("formattedLocation");
String value7= extras.getStringExtra("source");
String value8= extras.getStringExtra("date");
String value9= extras.getStringExtra("snippet");
String value10= extras.getStringExtra("url");
String value11= extras.getStringExtra("onmousedown");
String value12= extras.getStringExtra("lattitude");
String value13= extras.getStringExtra("longitude");
String value14= extras.getStringExtra("jobkey");
String value15= extras.getStringExtra("sponsored");
String value16= extras.getStringExtra("expired");
String value17= extras.getStringExtra("formattedLocationFull");
String value18= extras.getStringExtra("formattedRelativeTime");
String headerValue = header.getText().toString();
Log.e("ERROR", "Inside run and checking Value and val");
if (val > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)) {
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
PostBaseAdapter.java
public class PostBaseAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<Result> resultList;
private MainActivity mActivity;
private Context mContext;
String TAG="";
public PostBaseAdapter(Context context, ArrayList<Result> resultList) {
this.layoutInflater = LayoutInflater.from(context);
this.resultList = resultList;
this.mContext= context;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Result getItem(int i) {
return resultList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int j=i;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_post, null);
//viewHolder = new ViewHolder(convertView);
viewHolder= new ViewHolder();
//View overFlow = convertView.findViewById(R.id.id_overflow);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.imageClick= (ImageView) convertView.findViewById(R.id.id_overflow);
convertView.setTag(viewHolder);
//overFlow.setOnClickListener(new OverflowSelectedListener(mContext, mActivity));
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Result result = resultList.get(i);
viewHolder.tvTitle.setText(result.getJobtitle());
final String jobTitle=resultList.get(i).getJobtitle();
final String company= resultList.get(i).getCompany();
final String city= resultList.get(i).getCity();
final String state= resultList.get(i).getState();
final String country= resultList.get(i).getCountry();
final String formattedLocation= resultList.get(i).getFormattedLocation();
final String source=resultList.get(i).getSource();
final String date= resultList.get(i).getDate();
final String snippet= resultList.get(i).getSnippet();
final String url= resultList.get(i).getUrl();
final String onmousedown= resultList.get(i).getOnmousedown();
final String lattitude= resultList.get(i).getLattitude();
final String longitude= resultList.get(i).getLongitude();
final String jobkey= resultList.get(i).getJobkey();
final String sponsored= resultList.get(i).getSponsored();
final String expired= resultList.get(i).getExpired();
final String formattedLocaionfull= resultList.get(i).getFormattedLocation();
final String formattedRelativeTime= resultList.get(i).getFormattedRelativeTime();
try {
viewHolder.imageClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.id_overflow:
final PopupMenu popup = new PopupMenu(mContext, v);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
// Force icons to show
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id_To_Search = j + 1;
/*Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtras(dataBundle);
mContext.startActivity(intent);*/
switch (item.getItemId()) {
case R.id.email_whatsapp:
doEmailOrWhatsapp(mActivity);
return true;
case R.id.share_on_fb:
shareOnFb(mActivity);
return true;
case R.id.mark_as_fav:
//viewHolder.
//dataBundle.putString("name", result.getJobtitle());
Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtra("id",0);
intent.putExtra("title", jobTitle );
intent.putExtra("company",company );
intent.putExtra("city", city);
intent.putExtra("state",state );
intent.putExtra("country",country );
intent.putExtra("formattedLocation",formattedLocation );
intent.putExtra("source",source );
intent.putExtra("date", date);
intent.putExtra("snippet", snippet);
intent.putExtra("url", url);
intent.putExtra("onmousedown",onmousedown );
intent.putExtra("lattitude", lattitude);
intent.putExtra("longitude",longitude );
intent.putExtra("jobkey", jobkey);
intent.putExtra("sponsored",sponsored );
intent.putExtra("expired", expired);
intent.putExtra("formattedLocationFull",formattedLocaionfull );
intent.putExtra("formattedRelativeTime",formattedRelativeTime );
//intent.putExtras(dataBundle);
mContext.startActivity(intent);
return true;
default:
break;
}
return true;
}
});
//popup.show();
break;
default:
break;
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
TextView tvTitle;//, tvPublishDate;
ImageView imageClick;
/* public ViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);*/
// imageClick=(ImageView)item.findViewById(R.id.id_overflow);
// tvPublishDate = (TextView) item.findViewById(R.id.tvPublishDate);
}
}
mark-fav-layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<EditText
android:id="#+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="text" >
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="#string/save" />
</LinearLayout>
Result.java
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I have just updated my code and its working fine for me. I am posting it here ,so that anyone can use if needed.
MarkFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
mydb.getWritableDatabase();
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
if (value > 0) {
//means this is the view part not the add contact part.
/* Cursor rs = mydb.getData(value);
id_To_Update = value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText( nam);
header.setFocusable(false);
header.setClickable(false);*/
}
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
String headerValue = header.getText().toString();
String value1 = extras.getString("title");
String value2 = extras.getString("company");
String value3 = extras.getString("city");
String value4 = extras.getString("state");
String value5 = extras.getString("country");
String value6 = extras.getString("formattedLocation");
String value7 = extras.getString("source");
String value8 = extras.getString("date");
String value9 = extras.getString("snippet");
String value10= extras.getString("url");
String value11= extras.getString("onmousedown");
String value12= extras.getString("lattitude");
String value13= extras.getString("longitude");
String value14= extras.getString("jobkey");
String value15= extras.getString("sponsored");
String value16= extras.getString("expired");
String value17= extras.getString("formattedLocationFull");
String value18= extras.getString("formattedRelativeTime");
Log.e("ERROR", "Inside run and checking Value and val");
if (value > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
/* public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);*/
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" Text, "+JOBS_COLUMN_NAME+" Text,"+JOBS_COLUMN_COMPANY+" Text, "+JOBS_COLUMN_CITY+" Text, "+JOBS_COLUMN_STATE+" Text, "+JOBS_COLUMN_COUNTRY+" Text,"+JOBS_COLUMN_FORMATEDLOCATION+" Text,"+JOBS_COLUMN_SOURCE+" Text,"+JOBS_COLUMN_DATE+" Text,"+JOBS_COLUMN_SNIPPET+" Text,"+JOBS_COLUMN_COMPANY+" Text,"+JOBS_COLUMN_URL+"Text,"+JOBS_COLUMN_ONMOUSEDOWN+" Text,"+JOBS_COLUMN_LATTITUDE+" Text,"+JOBS_COLUMN_LONGITUDE+"Text,"+JOBS_COLUMN_JOBKEY+" Text,"+JOBS_COLUMN_SPONSORED+" Text,"+JOBS_COLUMN_EXPIRED+" Text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" Text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" Text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
/* public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}*/
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}

How to use AsyncTask for copy Database in Android

I want use AsyncTask for copy database in my application. The application has 4 fragments, and any fragment shows one table from the database (database has 4 tables). But when I run the application, it show me this error:
03-07 12:49:18.775 11190-11190/com.tellfa.dastanak E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tellfa.dastanak, PID: 11190
android.database.sqlite.SQLiteException: no such table: tbl_Book (code 1): , while compiling: SELECT * FROM tbl_Book WHERE Cat_ID = ?
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:897)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:508)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:726)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1426)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1365)
at com.tellfa.dastanak.Database.DataBase.getCat1_Datas(DataBase.java:157)
at com.tellfa.dastanak.Fragments.Home_Frag.onCreateView(Home_Frag.java:49)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:610)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:677)
at android.view.View.measure(View.java:17496)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:940)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17496)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
at android.view.View.measure(View.java:17496)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
at android.view.Vi
AsyncTask code :
public class LoadDB_AsyncTask extends AsyncTask<Void, Void, Boolean> {
Context mContext;
boolean loadedDB = false;
private DataBase dataBase;
private ProgressDialog progressDialog;
private static final String LOG_TAG = "log : ";
public LoadDB_AsyncTask(Context context) {
this.mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(LOG_TAG, "onPreExecute in loadDB");
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Data loading ...");
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
Log.i(LOG_TAG, "onProgressUpdate in loadDB");
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
Log.i(LOG_TAG, "doInBackground in loadDB");
dataBase = new DataBase(mContext);
boolean dbExist = dataBase.checkDataBase();
if (dbExist) {
loadedDB = true;
} else {
publishProgress(null);
}
try {
dataBase.createDataBase();
} catch (IOException e) {
throw new Error("Error on create DataBase");
}
dataBase.close();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.i(LOG_TAG, "onPostExecute in loadDB");
if (!loadedDB) {
progressDialog.dismiss();
Log.i(LOG_TAG, "Loaded DataBase");
Toast.makeText(mContext, "Data Loaded", Toast.LENGTH_SHORT).show();
} else {
Log.i(LOG_TAG, "The database was already loaded");
}
try {
finalize();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
DataBase code:
public class DataBase extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static String DB_NAME = "Dastansara";
private static int DB_VERSION = 1;
private SQLiteDatabase sqLiteDatabase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
*
* #param context
*/
public DataBase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (android.os.Build.VERSION.SDK_INT >= 17) {
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* Creates a empty database on the system and rewrites it with your own database.
*/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database alerdy exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
*
* #return true if it exists, false if it doesn't
*/
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPATH = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPATH, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
/// database does't exist yet
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Open DataBase
*
* #throws SQLException
*/
public void openDataBase() throws SQLException {
String myPATH = DB_PATH + DB_NAME;
sqLiteDatabase = SQLiteDatabase.openDatabase(myPATH, null, SQLiteDatabase.OPEN_READONLY);
}
/**
* Close DataBase
*/
public void closeDataBase() {
sqLiteDatabase.close();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
*/
public void copyDataBase() throws IOException {
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String myPath = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(myPath);
byte[] buffer = new byte[1024];
int length;
//transfer bytes from the inputfile to the outputfile
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
#Override
public synchronized void close() {
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
super.close();
}
public Cursor getCat1_Datas(SQLiteDatabase sqLiteDatabase) {
try {
String query = "SELECT * FROM tbl_Book WHERE Cat_ID = ?";
Cursor cursor = sqLiteDatabase.rawQuery(query, new String[] {"1"});
if (cursor != null) {
cursor.moveToNext();
}
return cursor;
} catch (SQLException e) {
Log.e("Data Adapter", "getTestData >>" + e.toString());
throw e;
}
}
}
Fragment code:
public class Home_Frag extends Fragment {
DataProvider dataProvider;
DataBase dataBase;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
ListView listView;
Cat1_frag_adapter cat1FragAdapter;
private LoadDB_AsyncTask task;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_home,
container, false);
task = new LoadDB_AsyncTask(getContext());
task.execute();
dataBase = new DataBase(getActivity());
sqLiteDatabase = dataBase.getReadableDatabase();
cursor = dataBase.getCat1_Datas(sqLiteDatabase);
listView = (ListView) rootView.findViewById(R.id.list);
cat1FragAdapter = new Cat1_frag_adapter(getActivity(), R.layout.list_card_layout);
listView.setAdapter(cat1FragAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
listView.setNestedScrollingEnabled(true);
}
if (cursor.moveToFirst()) {
do {
String id;
String title;
//id = cursor.getString(0);
title = cursor.getString(2);
dataProvider = new DataProvider(title);
cat1FragAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
return rootView;
}
How to fix this error and use Asynctask in my application? tnx <3
Create your database tables in the onCreate of your DBHandler class.(Replace table name and columns)
Helper class
DBHandler Class:
public class DBHandler {
private static String TAG = "DBHandler";
static File dir = new File(Environment.getExternalStorageDirectory() + "");
private static String MYDATABASE_NAME = dir + "/test/tablename.db";// dir+"/
public static final String MYDATABASE_TABLE = "tablename";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_TDATE = "TDATE" ;
public static final String KEY_TARIFFFCBASIS = "TARIFFFCBASIS" ;
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, "
+KEY_TDATE + " text , "
+KEY_TARIFFFCBASIS + " text );"
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public DBHandler(Context c) {
context = c;
if(logger == null){
logger = MasterLibraryFunction.getlogger(context, TAG);
logger.info("In Side DBHandler(Context c)");
}
}
public DBHandler openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public DBHandler openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
/**
* Check if the database exist
*
* #return true if it exists, false if it doesn't
*/
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(MYDATABASE_NAME, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
}
return checkDB != null ? true : false;
}
public int deleteAll() {
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
}
}
AsyncTask code :
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
#Override
protected String doInBackground(String... params) {
// Open DB file to write/read
db_helper = new DBHandler(getApplicationContext());
db_helper.openToWrite();
// Complete your operation and close db_helper
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
}
}
}

concurrency in database opener

I have no idea how to do proper concurrent operations, so I just tried to adjust my code.
And totally lost in concurrency in constructor and concurrency with static, final fields...
public static class Connection {
private final CustomerDatabaseOpenHelper mHelper;
private SQLiteDatabase mDatabase;
private String mUserId;
private AtomicInteger mOpenCounter;
public Connection(Context context, String userId) {
mHelper = CustomerDatabaseOpenHelper.getInstance(context, DB_NAME, null, DB_VERSION);
mOpenCounter = mHelper.mOpenCounter;
mUserId = userId;
}
public void open() throws SQLException {
// open database in reading/writing mode
int value = mOpenCounter.incrementAndGet();
if(value == 1 || mDatabase==null || mUserId ==null) {
// Opening new database
Log.v("tugce","open new customer db");
mDatabase = mHelper.getWritableDatabase();
}
};
public void close() {
int value = mOpenCounter.decrementAndGet();
if(value == 0) {
// Closing database
if (mDatabase != null) {
try {
Log.v("tugce","close customer db");
mDatabase.close();
mDatabase = null;
mUserId = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//my openhelper class
public class CustomerDatabaseOpenHelper extends SQLiteOpenHelper{
public AtomicInteger mOpenCounter = new AtomicInteger();
public static CustomerDatabaseOpenHelper mInstance;
public static synchronized CustomerDatabaseOpenHelper getInstance(Context context, String name,
CursorFactory factory, int version) {
if (mInstance == null) {
mInstance = new CustomerDatabaseOpenHelper(context, name, factory, version);
}
return mInstance;
}
private CustomerDatabaseOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
This is how I am using in threads:
class MyGetPlanedCallList extends
AsyncTask<Object, Object, List<MyPlannedCallListItem>> {
CustomerDatabase.Connection mDbCon = new CustomerDatabase.Connection(InstanceActivity.this, mUserId);
#Override
protected void onPreExecute() {
mDbCon.open();
}
#Override
protected List<MyPlannedCallListItem> doInBackground(Object... params) {
mDbCon.doSomeStuff();
}
#Override
protected void onPostExecute(List<MyPlannedCallListItem> result) {
mDbCon.close();
}
#Override
protected void onCancelled() {
if (mDbCon != null)
mDbCon.close();
}
}
What I want is, exactly same db shouldn't be closed if some other instance is working on it.
Any help would be appreciated.

Categories