This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a fragment called PopularFragment.java in that i am fetching images from server and then displaying them into recyclerview. Usually it works great but sometimes the app crashes with a NullPointerException.
PopularFragment:
package com.apphics.minimalwallpapers;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.adapter.AdapterImage;
import com.example.item.ItemPhotos;
import com.example.util.Constant;
import com.example.util.DBHelper;
import com.example.util.EndlessRecyclerViewScrollListener;
import com.example.util.JsonUtils;
import com.pnikosis.materialishprogress.ProgressWheel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class PopularFragment extends Fragment {
DBHelper dbHelper;
GridLayoutManager lLayout;
RecyclerView recyclerView;
AdapterImage adapterImage;
ArrayList<ItemPhotos> arrayOfLatestImage;
SwipeRefreshLayout mSwipeRefreshLayout;
ProgressWheel pbar;
TextView txt_no;
int spaceInPixels = 10;
Boolean isOver = false;
public PopularFragment newInstance() {
PopularFragment fragment = new PopularFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
pbar=(ProgressWheel) rootView.findViewById(R.id.progressBar1);
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
dbHelper = new DBHelper(getActivity().getApplicationContext());
arrayOfLatestImage=new ArrayList<ItemPhotos>();
lLayout = new GridLayoutManager(getActivity(), 2);
lLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return adapterImage.isHeader(position) ? lLayout.getSpanCount() : 1;
}
});
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_latest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(lLayout);
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(lLayout) {
#Override
public void onLoadMore(int p, int totalItemsCount) {
arrayOfLatestImage.add(null);
adapterImage.notifyItemInserted(arrayOfLatestImage.size() - 1);
arrayOfLatestImage.remove(arrayOfLatestImage.size() - 1);
adapterImage.notifyItemRemoved(arrayOfLatestImage.size());
if(!isOver) {
// list_url.clear();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new MyTask(getActivity().getApplicationContext()).execute(Constant.POPULAR_URL);
}
}, 2000);
} else {
adapterImage.hideHeader();
//Toast.makeText(getActivity(), "No more data", Toast.LENGTH_SHORT).show();
}
}
});
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshContent();
}
});
if (JsonUtils.isNetworkAvailable(getActivity())) {
new MyTask(getActivity().getApplicationContext()).execute(Constant.POPULAR_URL);
} else {
arrayOfLatestImage = dbHelper.getAllDataPopular("popular");
if(arrayOfLatestImage.size()==0) {
Toast.makeText(getActivity(), "Please connect to internet to load Images ", Toast.LENGTH_SHORT).show();
pbar.setVisibility(View.GONE);
} else {
adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
recyclerView.setAdapter(adapterImage);
pbar.setVisibility(View.GONE);
}
}
return rootView;
}
private class MyTask extends AsyncTask<String, Void, String> {
private final WeakReference<Context> contextReference;
public MyTask(Context context) {
this.contextReference = new WeakReference<Context>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Context context = this.contextReference.get();
if(context != null) {
if (arrayOfLatestImage.size() == 0) {
pbar.setVisibility(View.VISIBLE);
}
}
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Context context = this.contextReference.get();
if(context != null) {
if (arrayOfLatestImage.size() == 0) {
pbar.setVisibility(View.INVISIBLE);
}
if (null == result || result.length() == 0) {
Toast.makeText(getActivity(), "Something Went Wrong! Please check your internet and reload", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
if (jsonArray.length() <= arrayOfLatestImage.size() + 40) {
isOver = true;
}
int a = arrayOfLatestImage.size();
int b;
b = 40;
JSONObject objJson = null;
for (int i = a; i < a + b; i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_WALL_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String img = objJson.getString(Constant.TAG_WALL_IMAGE);
String img_thumb = objJson.getString(Constant.TAG_WALL_IMAGE_THUMB);
String cat_name = objJson.getString(Constant.TAG_CAT_NAME);
String views = objJson.getString(Constant.TAG_WALL_VIEWS);
ItemPhotos objItem = new ItemPhotos(id, cid, img, img_thumb, cat_name, views);
dbHelper.addtoFavorite(objItem, "popular");
arrayOfLatestImage.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
isOver = true;
}
setAdapterToListview();
}
}
}
}
public void setAdapterToListview() {
if(arrayOfLatestImage.size()<41) {
adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
recyclerView.setAdapter(adapterImage);
} else {
adapterImage.notifyDataSetChanged();
}
//setExmptTextView();
}
/*private void setExmptTextView() {
if(adapterImage.getItemCount()==0) {
txt_no.setVisibility(View.VISIBLE);
} else{
txt_no.setVisibility(View.INVISIBLE);
}
}*/
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
//if(adapterImage!=null && adapterImage.getItemCount() > 0) {
// adapterImage.notifyDataSetChanged();
//setExmptTextView();
// }
super.onResume();
}
private void refreshContent() {
// TODO implement a refresh
recyclerView.getRecycledViewPool().clear();
adapterImage.notifyDataSetChanged();
arrayOfLatestImage.clear();
try{
if (JsonUtils.isNetworkAvailable(getActivity())) {
new MyTask(getActivity()).execute(Constant.POPULAR_URL);
} else {
arrayOfLatestImage = dbHelper.getAllDataPopular("popular");
if(arrayOfLatestImage.size()==0) {
Toast.makeText(getActivity(), "First Time Load Application from Internet ", Toast.LENGTH_SHORT).show();
} else {
adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
recyclerView.setAdapter(adapterImage);
}
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false); // Disables the refresh icon
}
}
DBHelper.java:
package com.example.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.item.ItemAbout;
import com.example.item.ItemCategory;
import com.example.item.ItemGIF;
import com.example.item.ItemPhotos;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
private static String DB_NAME = "wallpaper.db";
private SQLiteDatabase db;
private final Context context;
private String DB_PATH;
String outFileName = "";
SharedPreferences.Editor spEdit;
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
//------------------------------------------------------------
PackageInfo pinfo = null;
if (!dbExist) {
getReadableDatabase();
copyDataBase();
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.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);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public Cursor getData(String Query) {
String myPath = DB_PATH + DB_NAME;
Cursor c = null;
try {
File file = new File(myPath);
if (file.exists() && !file.isDirectory())
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
c = db.rawQuery(Query, null);
} catch (Exception e) {
Log.e("Err", e.toString());
}
return c;
}
//UPDATE temp_dquot SET age='20',name1='--',rdt='11/08/2014',basic_sa='100000',plno='814',pterm='20',mterm='20',mat_date='11/08/2034',mode='YLY',dab_sa='100000',tr_sa='0',cir_sa='',bonus_rate='42',prem='5276',basic_prem='5118',dab_prem='100.0',step_rate='for Life',loyal_rate='0',bonus_rate='42',act_mat='1,88,000',mly_b_pr='448',qly_b_pr='1345',hly_b_pr='2664',yly_b_pr='5276' WHERE uniqid=1
public void dml(String Query) {
String myPath = DB_PATH + DB_NAME;
File file = new File(myPath);
if (file.exists() && !file.isDirectory())
if (db == null)
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
try {
db.execSQL(Query);
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public ArrayList<ItemPhotos> getAllData(String table){
ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
arrayList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemPhotos> getAllDataPopular(String table){
ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
arrayList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemPhotos> getAllDataShuffl(String table){
ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
arrayList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemGIF> getAllDataGIF(){
ArrayList<ItemGIF> arrayList = new ArrayList<ItemGIF>();
Cursor cursor = getData("select * from gif");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String gid = cursor.getString(cursor.getColumnIndex("gid"));
String img = cursor.getString(cursor.getColumnIndex("image"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemGIF itemGIF = new ItemGIF(gid,img,views);
arrayList.add(itemGIF);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemCategory> getAllDataCat(String table){
ArrayList<ItemCategory> arrayList = new ArrayList<ItemCategory>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String tot_wall = cursor.getString(cursor.getColumnIndex("tot_wall"));
ItemCategory itemCategory = new ItemCategory(cid,cname,img,img_thumb,tot_wall);
arrayList.add(itemCategory);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemPhotos> getFavRow(String id, String table)
{
ArrayList<ItemPhotos> dataList = new ArrayList<ItemPhotos>();
// Select All Query
String selectQuery = "SELECT * FROM '"+table+"' WHERE pid="+"'"+id+"'";
Cursor cursor = getData(selectQuery);
if (cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
dataList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
// return contact list
return dataList;
}
public ArrayList<ItemGIF> getFavRowGIF(String id)
{
ArrayList<ItemGIF> dataList = new ArrayList<ItemGIF>();
// Select All Query
String selectQuery = "SELECT * FROM gif WHERE gid="+"'"+id+"'";
Cursor cursor = getData(selectQuery);
if (cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String gid = cursor.getString(cursor.getColumnIndex("gid"));
String img = cursor.getString(cursor.getColumnIndex("image"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemGIF itemGIF = new ItemGIF(gid,img,views);
dataList.add(itemGIF);
cursor.moveToNext();
}
cursor.close();
}
// return contact list
return dataList;
}
public ArrayList<ItemPhotos> getCatList(String id, String table)
{
ArrayList<ItemPhotos> dataList = new ArrayList<ItemPhotos>();
// Select All Query
String selectQuery = "SELECT * FROM '"+table+"' WHERE cid="+"'"+id+"'";
Cursor cursor = getData(selectQuery);
if (cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
dataList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
// return contact list
return dataList;
}
public void addtoFavorite(ItemPhotos itemPhotos, String table) {
dml("insert into '"+table+"' (pid,cid,cname,img,img_thumb,views) values ('"+itemPhotos.getId()+"','"+itemPhotos.getCatId()+"','"+itemPhotos.getCName()+"','"+itemPhotos.getImage()+"','"+itemPhotos.getImageThumb()+"','"+itemPhotos.getTotalViews()+"')");
}
public void addtoFavoriteGIF(ItemGIF itemGIF) {
dml("insert into gif (gid,image,views) values ('"+itemGIF.getId()+"','"+itemGIF.getImage()+"','"+itemGIF.getTotalViews()+"')");
}
public void addtoCatList(ItemCategory itemCategory, String table) {
dml("insert into '"+table+"' (cid,cname,img,img_thumb,tot_wall) values ('"+itemCategory.getId()+"','"+itemCategory.getName()+"','"+itemCategory.getImage()+"','"+itemCategory.getImageThumb()+"','"+itemCategory.getTotalWallpaper()+"')");
}
public void removeFav(String id) {
dml("delete from fav where pid = '"+id+"'");
}
public void removeFavGIF(String id) {
dml("delete from gif where gid = '"+id+"'");
}
public void updateView(String id, String totview) {
int views = Integer.parseInt(totview) + 1;
dml("update catlist set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
dml("update fav set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
dml("update latest set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
dml("update shuffl set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
}
public void updateViewGIF(String id, String totview) {
int views = Integer.parseInt(totview) + 1;
dml("update gif set views = '"+String.valueOf(views)+"' where gid = '"+id+"'");
}
public void addtoAbout() {
dml("delete from about");
dml("insert into about (name,logo,version,author,contact,email,website,desc,developed,privacy) values (" +
"'"+ Constant.itemAbout.getAppName()+"','"+ Constant.itemAbout.getAppLogo()+"','"+ Constant.itemAbout.getAppVersion()+"'" +
",'"+ Constant.itemAbout.getAuthor()+"','"+ Constant.itemAbout.getContact()+"','"+ Constant.itemAbout.getEmail()+"'" +
",'"+ Constant.itemAbout.getWebsite()+"','"+ Constant.itemAbout.getAppDesc()+"','"+ Constant.itemAbout.getDevelopedby()+"'" +
",'"+ Constant.itemAbout.getPrivacy()+"')");
}
public Boolean getAbout() {
String selectQuery = "SELECT * FROM about";
Cursor c = getData(selectQuery);
if (c != null && c.getCount()>0) {
c.moveToFirst();
for (int i=0; i<c.getCount(); i++) {
String appname = c.getString(c.getColumnIndex("name"));
String applogo = c.getString(c.getColumnIndex("logo"));
String desc = c.getString(c.getColumnIndex("desc"));
String appversion = c.getString(c.getColumnIndex("version"));
String appauthor = c.getString(c.getColumnIndex("author"));
String appcontact = c.getString(c.getColumnIndex("contact"));
String email = c.getString(c.getColumnIndex("email"));
String website = c.getString(c.getColumnIndex("website"));
String privacy = c.getString(c.getColumnIndex("privacy"));
String developedby = c.getString(c.getColumnIndex("developed"));
Constant.itemAbout = new ItemAbout(appname,applogo,desc,appversion,appauthor,appcontact,email,website,privacy,developedby);
}
c.close();
return true;
} else {
return false;
}
}
}
This is the logcat:
java.lang.NullPointerException:
at com.example.util.DBHelper.<init>(DBHelper.java:35)
at com.example.adapter.AdapterImage.<init>(AdapterImage.java:69)
at com.apphics.minimalwallpapers.PopularFragment.setAdapterToListview(PopularFragment.java:226)
at com.apphics.minimalwallpapers.PopularFragment$MyTask.onPostExecute(PopularFragment.java:217)
at com.apphics.minimalwallpapers.PopularFragment$MyTask.onPostExecute(PopularFragment.java:141)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5438)
at java.lang.reflect.Method.invoke(Native Method:0)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
The exception is thrown when arrayOfLatestImage.size() is greater than or equal to 41. Initialize adapterImage in the else block in the setAdapterToListview() function. Hope it helps.
Related
I need your help. I want to delete data from my Database by actionModeCallbacks inside the RecyclerView.
remove a users from my recyclerview/database.
This is my logcat.
Process: com.andylab.recovermessages, PID: 24576
android.database.sqlite.SQLiteException: near "=": syntax error (code 1 SQLITE_ERROR): , while compiling: DELETE FROM users = com.andylab.recovermessages.models.UserModel#dff4685;
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:939)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:550)
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.executeSql(SQLiteDatabase.java:1770)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
at com.andylab.recovermessages.db.recentNumberDB.deleteItem(recentNumberDB.java:367)
at com.andylab.recovermessages.adapters.UsersAdapter$1.onActionItemClicked(UsersAdapter.java:70)
at androidx.appcompat.app.AppCompatDelegateImpl$ActionModeCallbackWrapperV9.onActionItemClicked(AppCompatDelegateImpl.java:2171)
at androidx.appcompat.view.StandaloneActionMode.onMenuItemSelected(StandaloneActionMode.java:141)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)
at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
2020-05-10 02:55:30.109 24576-24576/com.andylab.recovermessages I/Process: Sending signal. PID: 24576 SIG: 9
This is my datadb.
private class datadb extends SQLiteOpenHelper {
private static final String CREATE_TABLE_ADDED_PACKAGES = "CREATE TABLE table_packages (ID INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT unique);";
static final String CREATE_TABLE_FILES = "CREATE TABLE files (_id INTEGER PRIMARY KEY AUTOINCREMENT, files TEXT, whole_time LONG);";
static final String CREATE_TABLE_MSG = "CREATE TABLE messeges (_id INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT, username TEXT, msg TEXT, small_time TEXT, whole_time LONG);";
private static final String CREATE_TEBLE_COOL = "CREATE TABLE cool_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, cool_text TEXT unique);";
private static final String CREATE_TEBLE_QUICK_REPLY = "CREATE TABLE quick_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, quick_reply TEXT);";
private static final String CREATE_TEBLE_REPEATER = "CREATE TABLE repeater_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, text_repeater TEXT);";
private static final String CREATE_TEBLE_UNSAVED = "CREATE TABLE num_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, nums TEXT unique);";
static final String CREATE_USER_WITH_ID = "CREATE TABLE users (_id INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT, username TEXT UNIQUE, read_unread boolean, whole_time DATETIME DEFAULT CURRENT_TIMESTAMP);";
private static final String ID = "_id";
private static final String NAME = "recover.db";
private static final int version = 1;
public void onUpgrade(SQLiteDatabase sQLiteDatabase, int i, int i2) {
}
public datadb(Context context) {
super(context, NAME, null, version);
}
public void onCreate(SQLiteDatabase sQLiteDatabase) {
sQLiteDatabase.execSQL(CREATE_TEBLE_UNSAVED);
sQLiteDatabase.execSQL(CREATE_TEBLE_QUICK_REPLY);
sQLiteDatabase.execSQL(CREATE_TEBLE_REPEATER);
sQLiteDatabase.execSQL(CREATE_TEBLE_COOL);
sQLiteDatabase.execSQL(CREATE_USER_WITH_ID);
sQLiteDatabase.execSQL(CREATE_TABLE_MSG);
sQLiteDatabase.execSQL(CREATE_TABLE_FILES);
sQLiteDatabase.execSQL(CREATE_TABLE_ADDED_PACKAGES);
}
}
public recentNumberDB(Context context) {
this.context = context;
}
public long addData(String str, String str2, String str3, String str4, String str5) {
Long l = null;
try {
addUser(str2, str, str5);
SQLiteDatabase writableDatabase = new datadb(this.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", str);
contentValues.put("small_time", str4);
contentValues.put("whole_time", str5);
contentValues.put(NotificationCompat.CATEGORY_MESSAGE, str3);
contentValues.put("package", str2);
l = writableDatabase.insert("messeges", null, contentValues);
writableDatabase.close();
} catch (Exception str6) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str6.toString());
Log.d("dblog", stringBuilder.toString());
}
return l;
}
public void addUser(String str, String str2, String str3) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
String str4 = str;
String str5 = str2;
String str6 = str3;
String str7 = "package";
String str8 = "read_unread";
String str9 = "whole_time";
String str10 = "username";
String str11 = "addedusrsnum";
Log.d(str11, "adding started");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("current time ");
stringBuilder.append(str6);
Log.d(str11, stringBuilder.toString());
try {
SQLiteDatabase writableDatabase = new datadb(view_deleted_messages_dbs_recentNumberDB.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(str10, str5);
contentValues.put(str9, str6);
contentValues.put(str8, Boolean.valueOf(false));
contentValues.put(str7, str4);
String str12 = "users";
if (writableDatabase.query("users", new String[]{str10, str7}, "username=? AND package=?", new String[]{str5, str4}, null, null, null).getCount() == 0) {
writableDatabase.insert(str12, null, contentValues);
Log.d(str11, "greater 0");
} else {
contentValues.clear();
contentValues.put(str9, str6);
contentValues.put(str8, Boolean.valueOf(false));
writableDatabase.update(str12, contentValues, "username=? AND package=?", new String[]{str5, str4});
Log.d(str11, "updates");
}
writableDatabase.close();
} catch (Exception e) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("error: ");
stringBuilder2.append(e.toString());
Log.d(str11, stringBuilder2.toString());
}
}
public List<HashMap> getUsers(String str) {
String str2 = "username";
String str3 = "read_unread";
List<HashMap> arrayList = new ArrayList();
try {
SQLiteDatabase readableDatabase = new datadb(this.context).getReadableDatabase();
SQLiteDatabase sQLiteDatabase = readableDatabase;
Cursor query = sQLiteDatabase.query("users", new String[]{str3, str2}, "package=?", new String[]{str}, null, null, "whole_time DESC");
while (query.moveToNext()) {
HashMap hashMap = new HashMap();
Log.d("readunr", query.getString(query.getColumnIndex(str3)));
hashMap.put("boolean", query.getString(query.getColumnIndex(str3)));
hashMap.put("string", query.getString(query.getColumnIndex(str2)));
arrayList.add(hashMap);
}
query.close();
readableDatabase.close();
} catch (Exception str4) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str4.toString());
Log.d("dblog", stringBuilder.toString());
}
return arrayList;
}
public List<DataModel> getMsg(String str, String str2) {
String str3 = "small_time";
String str4 = NotificationCompat.CATEGORY_MESSAGE;
List<DataModel> arrayList = new ArrayList();
try {
SQLiteDatabase writableDatabase = new datadb(this.context).getWritableDatabase();
SQLiteDatabase sQLiteDatabase = writableDatabase;
Cursor query = sQLiteDatabase.query("messeges", new String[]{str4, str3}, "username=? AND package=?", new String[]{str, str2}, null, null, null);
while (query.moveToNext()) {
arrayList.add(new DataModel(query.getString(query.getColumnIndex(str4)), query.getString(query.getColumnIndex(str3))));
}
query.close();
writableDatabase.close();
} catch (Exception str5) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str5.toString());
Log.d("dblog", stringBuilder.toString());
}
return arrayList;
}
public boolean isPresent(String str, String str2, String str3) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
String str4 = str;
String str5 = NotificationCompat.CATEGORY_MESSAGE;
String str6 = "dblog";
boolean z = false;
try {
SQLiteDatabase readableDatabase = new datadb(view_deleted_messages_dbs_recentNumberDB.context).getReadableDatabase();
SQLiteDatabase sQLiteDatabase = readableDatabase;
Cursor query = sQLiteDatabase.query("messeges", new String[]{str5}, "username=? AND package=?", new String[]{str4, str3}, null, null, "_id DESC", "1");
if (query.getCount() > 0) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("isPresentusername=");
stringBuilder.append(str4);
stringBuilder.append("Size=");
stringBuilder.append(String.valueOf(query.getCount()));
Log.d(str6, stringBuilder.toString());
while (query.moveToNext()) {
str4 = query.getString(query.getColumnIndex(str5));
stringBuilder = new StringBuilder();
stringBuilder.append("ispresend greater 0. chat = ");
stringBuilder.append(str4);
Log.d(str6, stringBuilder.toString());
z = str4.equals(str2);
}
} else {
Log.d(str6, "ispresent is 0");
}
query.close();
readableDatabase.close();
} catch (Exception e) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("error: ");
stringBuilder2.append(e.toString());
Log.d(str6, stringBuilder2.toString());
}
return z;
}
public List<UserModel> getHomeList(String s) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
ArrayList<UserModel> list = new ArrayList<UserModel>();
try {
List<HashMap> users = this.getUsers(s);
SQLiteDatabase readableDatabase = new recentNumberDB.datadb(view_deleted_messages_dbs_recentNumberDB.context).getReadableDatabase();
for (int i = 0; i < users.size(); ++i) {
Cursor query = readableDatabase.query("messeges", new String[] { "msg", "small_time" }, "username=? AND package=?", new String[] { users.get(i).get("string").toString(), s }, (String)null, (String)null, "_id DESC", "1");
if (query != null) {
StringBuilder sb = new StringBuilder();
sb.append("users lenght ");
sb.append(users.size());
Log.d("emptylog", sb.toString());
StringBuilder sb2 = new StringBuilder();
sb2.append("cursor lenght ");
sb2.append(String.valueOf(query.getCount()));
Log.d("emptylog", sb2.toString());
if (query.getCount() == 0) {
list.add(new UserModel(users.get(i).get("string").toString(), "no recent msg", "", 1));
}
else {
while (true) {
int moveToNext = query.moveToNext() ? 1 : 0;
if (moveToNext == 0) {
break;
}
list.add(new UserModel(users.get(i).get("string").toString(), query.getString(0), query.getString(moveToNext), Integer.parseInt(users.get(i).get("boolean").toString())));
Log.d("emptylog", query.getString(0));
}
}
query.close();
}
else {
Log.d("emptylog", "cursor null");
}
}
readableDatabase.close();
return list;
}
catch (Exception ex) {
return list;
}
}
public void addPackages(String s) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("package", s);
writableDatabase.insert("table_packages", (String)null, contentValues);
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public ArrayList<String> getAllPackages() {
String[] array = { "com.whatsapp", "com.whatsapp.w4b", "com.gbwhatsapp", "com.facebook.lite", "com.facebook.orca", "com.facebook.mlite", "org.telegram.messenger" };
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
try {
Cursor query = new recentNumberDB.datadb(this.context).getReadableDatabase().query("table_packages", new String[] { "package" }, (String)null, (String[])null, (String)null, (String)null, (String)null);
boolean moveToNext;
while (true) {
moveToNext = query.moveToNext();
if (!moveToNext) {
break;
}
list.add(query.getString(0));
}
query.close();
int n = moveToNext ? 1 : 0;
int i;
while (true) {
i = (moveToNext ? 1 : 0);
if (n >= array.length) {
break;
}
if (list.contains(array[n])) {
list2.add(array[n]);
}
++n;
}
while (i < list.size()) {
if (!list2.contains(list.get(i))) {
list2.add(list.get(i));
}
++i;
}
return list2;
}
catch (Exception ex) {
return list2;
}
}
public void removePackageAndMsg(ArrayList<String> list) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
Iterator<String> iterator = list.iterator();
while (true) {
int hasNext = iterator.hasNext() ? 1 : 0;
if (hasNext == 0) {
break;
}
String s = iterator.next();
String[] array = new String[hasNext];
array[0] = s;
writableDatabase.delete("table_packages", "package=?", array);
String[] array2 = new String[hasNext];
array2[0] = s;
writableDatabase.delete("users", "package=?", array2);
String[] array3 = new String[hasNext];
array3[0] = s;
writableDatabase.delete("messeges", "package=?", array3);
}
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void remove(ArrayList<String> list) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
Iterator<String> iterator = list.iterator();
while (true) {
int hasNext = iterator.hasNext() ? 1 : 0;
if (hasNext == 0) {
break;
}
String s = iterator.next();
String[] array = new String[hasNext];
array[0] = s;
/// writableDatabase.delete("table_packages", "package=?", array);
String[] array2 = new String[hasNext];
array2[0] = s;
writableDatabase.delete("users", "package=?", array2);
String[] array3 = new String[hasNext];
array3[0] = s;
writableDatabase.delete("messeges", "package=?", array3);
}
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void deleteItem(UserModel position){
SQLiteDatabase db = new recentNumberDB.datadb(this.context).getWritableDatabase();
db.execSQL("DELETE FROM " + "users" + "package=?" + "username" + " = " + position + ";");
db.execSQL("DELETE FROM " + "messeges" + "package=?" + "small_time" + " = " + position + ";");
db.close();
}
}
And this is my adapter
`public class UsersAdapter extends RecyclerView.Adapter <UsersAdapter.RecyclerViewHolder> {
private Context context;
private ArrayList <UserModel> list;
private ArrayList<UserModel> selectedItems = new ArrayList<UserModel>();
private String pack;
private SparseBooleanArray mSelectedItemsIds;
LayoutInflater inflater;
private boolean multiSelect = false;
private ActionMode.Callback actionModeCallbacks = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
multiSelect = true;
menu.add("Delete");
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
for (UserModel intItem : selectedItems) {
list.remove(intItem);
notifyDataSetChanged ();
recentNumberDB recentNumberDB = new recentNumberDB(context);
recentNumberDB.deleteItem ( intItem );
}
switch (item.getItemId()) {
case R.id.action_delete:
return true;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
multiSelect = false;
selectedItems.clear();
notifyDataSetChanged();
}
};
public void itemRemoved(int position) {
recentNumberDB recentNumberDB = new recentNumberDB(context);
list.remove(position);
notifyItemRemoved(position);
recentNumberDB.deleteItem(position);
}
public UsersAdapter(Context context, ArrayList <UserModel> list, String str) {
this.context = context;
this.list = (ArrayList <UserModel>) list;
this.pack = str;
mSelectedItemsIds = new SparseBooleanArray();
this.inflater = LayoutInflater.from(context);
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder{
ConstraintLayout listt;
TextView msg;
TextView name;
TextView readunread;
TextView time;
public ImageButton btn_delete;
public CheckBox chkSelected;
public RecyclerViewHolder(#NonNull View itemView) {
super ( itemView );
name = (TextView) itemView.findViewById(R.id.name);
msg = (TextView) itemView.findViewById(R.id.msg);
time = (TextView) itemView.findViewById(R.id.time);
listt = (ConstraintLayout) itemView.findViewById(R.id.list);
readunread = (TextView) itemView.findViewById(R.id.unread);
btn_delete = (ImageButton) itemView.findViewById(R.id.btn_delete_unit);
chkSelected = (CheckBox) itemView.findViewById(R.id.chk_selected);
}
public void selectItem(UserModel list) {
if (multiSelect) {
if (selectedItems.contains(list)) {
selectedItems.remove(list);
itemView.setBackgroundColor(Color.WHITE);
} else {
selectedItems.add(list);
itemView.setBackgroundColor(Color.LTGRAY);
}
}
}
public void update(final UserModel value) {
// textView.setText(value + "");
if (selectedItems.contains(value)) {
itemView.setBackgroundColor(Color.LTGRAY);
} else {
itemView.setBackgroundColor( Color.WHITE);
}
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
((AppCompatActivity)view.getContext()).startSupportActionMode(actionModeCallbacks );
selectItem(value);
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectItem(value);
}
});
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.users_home, parent, false);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
UserModel userModel = (UserModel) list.get(position);
holder.name.setText(userModel.getName());
holder.msg.setText(userModel.getLastmsg());
holder.time.setText(userModel.getTime());
holder.listt.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (adCount%4==0){
/// AdmobHelper.showInterstitialAd(context, AdmobHelper.ADSHOWN);
}
adCount++;
Intent intent = new Intent(context, MessegesActivity.class);
intent.putExtra("name", userModel.getName());
intent.putExtra("pack", pack);
context.startActivity(intent);
}
});
holder.update(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
}`
I have navigation drawer with menu nav items. Now I define for one item, for when clicking on it, open a new activity.Inside this activity, I design layout for start flag game quiz.When clicking on play game Button, the game started so fast without waiting for click user, and finish. Inside "PlayGame" layout, I define one imageView for flags and 4 buttons for answers. Flags name and answers come from the External database. When I debug the app, countDownTimer realise null amount, Everything is correct, Just Timer doesn't wait for use, and playing Quiz is so quickly.
this is my database.
WorldCountryDatabase
public class WorldCountryDatabase extends SQLiteOpenHelper {
private static final String TAG = "databaseHelper";
private static final String DB_NAME = "worldCountries.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "country";
private static String DB_PATH = "";
private Context mContext;
private SQLiteDatabase database;
public WorldCountryDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_PATH = context.getDatabasePath(DB_NAME).getPath();
File file = new File(DB_PATH + "worldCountries.db");
if (file.exists())
openDataBase();
this.mContext = context;
}
public void createDatabase() {
boolean dbExist = checkDatabase();
if (dbExist) {
Log.d("MIN1", "Database already Exist");
} else {
this.getReadableDatabase();
}
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
Log.i("MIN2", e.getMessage());
}
}
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
e.printStackTrace();
Log.d("MIN3", e.getMessage());
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
public synchronized void close() {
if (database != null) {
database.close();
SQLiteDatabase.releaseMemory();
}
super.close();
}
private void copyDataBase() throws IOException {
try {
InputStream in = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream out = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
out.close();
in.close();
Log.d("MIN4", "Database copy");
} catch (SQLiteException e) {
Log.d("MIN5", e.getMessage());
}
}
public Cursor QueryData(String query) {
return database.rawQuery(query, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("MIN6", "onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion +
"Which will destroy all oldest data");
if (newVersion > oldVersion) {
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void openDataBase() {
String myPath = DB_PATH + DB_NAME;
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
Log.d("MIN7", "Opened database");
}
// CRUD Table
public List<Questions> getAllQuestions() {
List<Questions> questionsList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null);
if (c == null) return null;
c.moveToFirst();
do {
int Id = c.getInt(c.getColumnIndex("id"));
String Image = c.getString(c.getColumnIndex("Image"));
String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionsList.add(question);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
database.close();
return questionsList;
}
// Insert Score to Ranking table.
public void insertScore(double score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put("Score", score);
db.insert("Ranking", null, content);
}
// Get score and sort Ranking.
public List<Ranking> getRanking() {
List<Ranking> rankingList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Score DESC;", null);
if (c == null) return null;
c.moveToFirst();
do {
int ID = c.getInt(c.getColumnIndex("id"));
int Score = c.getInt(c.getColumnIndex("Score"));
Ranking ranking = new Ranking(ID, Score);
rankingList.add(ranking);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
db.close();
return rankingList;
}
public int getPlayCount(int level)
{
int result = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c;
try{
c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null);
if(c == null) return 0;
c.moveToNext();
do{
result = c.getInt(c.getColumnIndex("PlayCount"));
}while(c.moveToNext());
c.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
return result;
}
public void updatePlayCount(int level,int playCount)
{
String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level);
database.execSQL(query);
}
this is my ChoicGame class.
ChoiceGame
public class ChoiceGame extends AppCompatActivity {
TextView modeText;
SeekBar seekBarMode;
Button playGame, scoreGame;
WorldCountryDatabase worldCountryDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_flag);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
modeText = (TextView) findViewById(R.id.modeText);
seekBarMode = (SeekBar) findViewById(R.id.seekBarMode);
playGame = (Button) findViewById(R.id.playGame);
scoreGame = (Button) findViewById(R.id.scoreGame);
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//Event
seekBarMode.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0)
modeText.setText(Common.MODE.EASY.toString());
else if (progress == 1)
modeText.setText(Common.MODE.MEDIUM.toString());
else if (progress == 2)
modeText.setText(Common.MODE.HARD.toString());
else if (progress == 3)
modeText.setText(Common.MODE.HARDEST.toString());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayGameCountry.class);
intent.putExtra("Mode", getPlayMode()); // Send Mode to Playing page
startActivity(intent);
finish();
}
});
scoreGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ScoreGame.class);
startActivity(intent);
finish();
}
});
}
private String getPlayMode() {
if (seekBarMode.getProgress() == 0)
return Common.MODE.EASY.toString();
else if (seekBarMode.getProgress() == 1)
return Common.MODE.MEDIUM.toString();
else if (seekBarMode.getProgress() == 2)
return Common.MODE.HARD.toString();
else
return Common.MODE.HARDEST.toString();
}
}
and at last this is my PlayingGame class.
PlayingGmae
public class PlayGameCountry extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1; // 1 second
final static long TIMEOUT = 7; // 1 second
CountDownTimer countDownTimer;
int progressValue = 0;
int score = 0, index = 0, thisQuestion = 0, correctAnswer, totalQuestions;
List<Questions> questionsList = new ArrayList<>();
String mode;
ProgressBar progressBar;
ImageView flagCountry;
TextView scoreText, numberQuestion;
Button answerA, answerB, answerC, answerD;
WorldCountryDatabase worldCountryDatabase;
ChoiceGame choiceGame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game_country);
// Get data from ChoiceGame
Bundle bundle = getIntent().getExtras();
if (bundle != null)
mode = bundle.getString("Mode");
worldCountryDatabase = new WorldCountryDatabase(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
flagCountry = (ImageView) findViewById(R.id.flagQuiz);
scoreText = (TextView) findViewById(R.id.scoreText);
numberQuestion = (TextView) findViewById(R.id.trueAnswer);
answerA = (Button) findViewById(R.id.firstAnswer);
answerB = (Button) findViewById(R.id.secondAnswer);
answerC = (Button) findViewById(R.id.thirthAnswer);
answerD = (Button) findViewById(R.id.forthAnswer);
progressBar = (ProgressBar) findViewById(R.id.progressUser);
answerA.setOnClickListener(this);
answerB.setOnClickListener(this);
answerC.setOnClickListener(this);
answerD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionsList = this.getQuestionMode(mode);
assert questionsList != null;
totalQuestions = questionsList.size();
countDownTimer = new CountDownTimer(INTERVAL, TIMEOUT) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
countDownTimer.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestions) {
thisQuestion++;
numberQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestions));
progressBar.setProgress(0);
progressValue = 0;
int ImageId = this.getResources().getIdentifier(questionsList.get(index).getImage().toLowerCase(), "drawable", getPackageName());
flagCountry.setBackgroundResource(ImageId);
answerA.setText(questionsList.get(index).getAnswerA());
answerB.setText(questionsList.get(index).getAnswerB());
answerC.setText(questionsList.get(index).getAnswerC());
answerD.setText(questionsList.get(index).getAnswerD());
countDownTimer.start();
} else {
Intent scoreIntent = new Intent(getApplicationContext(), Done.class);
Bundle bundle = new Bundle();
bundle.putInt("SCORE", score);
bundle.putInt("TOTAL", totalQuestions);
bundle.putInt("CORRECT", correctAnswer);
scoreIntent.putExtras(bundle);
startActivity(scoreIntent);
finish();
}
}
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (index < totalQuestions) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionsList.get(index).getCorrectAnswer()))
{
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else
showQuestion(++index); // If choose right , just go to next question
scoreText.setText(String.format("%d", score));
}
}
private List<Questions> getQuestionMode(String mode) {
List<Questions> questionList = new ArrayList<>();
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
int limit = 0;
if (mode.equals(Common.MODE.EASY.toString()))
limit = 30;
else if (mode.equals(Common.MODE.MEDIUM.toString()))
limit = 50;
else if (mode.equals(Common.MODE.HARD.toString()))
limit = 100;
else if (mode.equals(Common.MODE.HARDEST.toString()))
limit = 200;
try {
Cursor cursor = worldCountryDatabase.QueryData(String.format("SELECT * FROM country ORDER BY Random() LIMIT %d", limit));
if (cursor == null) return null;
if (cursor.moveToNext()) {
do {
int Id = cursor.getInt(cursor.getColumnIndex("id"));
String Image = cursor.getString(cursor.getColumnIndex("Image"));
String AnswerA = cursor.getString(cursor.getColumnIndex("AnswerA"));
String AnswerB = cursor.getString(cursor.getColumnIndex("AnswerB"));
String AnswerC = cursor.getString(cursor.getColumnIndex("AnswerC"));
String AnswerD = cursor.getString(cursor.getColumnIndex("AnswerD"));
String CorrectAnswer = cursor.getString(cursor.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionList.add(question);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return questionList;
}
}
At the first, I defining "getQuestionMode" method inside WorldCountryDatabase, but the app doesn't go to the PlayingCountryGame layout and open ScoreGame class. After I define "getQuestionMode" method inside PlayingCountryGame class. I hope to tell clear my problem.
Please help me, good friends. Thanks to all of you.
I think that you problem is the constructor and values.
https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)
The constructor need the time on milliseconds and not seconds. Y ou need convert 1 second to 1000 ms.
final static long INTERVAL = 1000; // 1 second -> 1000 milliseconds
final static long TIMEOUT = 7000; // 7 seconds -> 7000 milliseconds
And the order of the params.
If you want wait 7 second the constructor is:
countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL){ ... }
I`m new in android coding...
I created some Activities and Sqlite...
I added a button in to my activity to store some data in to database, but every time we click on the button it added the same data to the database...
How can I check if the data is already exist in the data base??!!!
I created a listView for showing some data and when we click on each item it directed us in to a new activity, in the new activity I created a new button to store data in database, so I want to see how can I find out data is already exist so the button can be off and if not exist the button should be on...
here is my code:
database:
public class PhraseDataBaseAdapter {
private Context context;
private SQLiteOpenHelper sqLiteOpenHelper;
public PhraseDataBaseAdapter(Context context){
this.context = context;
sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, 1) {
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table tb1_phrases (id integer primary key, eng text, per text)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
};
}
public long savePhrase(Phrases phrases){
String eng = phrases.getEng();
String per = phrases.getPer();
long id = -1;
SQLiteDatabase database = null;
try{
ContentValues values = new ContentValues();
values.put("eng", eng);
values.put("per", per);
database = sqLiteOpenHelper.getWritableDatabase();
id = database.insert("tb1_phrases", null, values);
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
}finally {
if (database!=null && database.isOpen()){
database.close();
}
}
return id;
}
public Phrases readPhrase(long id){
Phrases phrases = null;
String[] columns = new String[]{"id", "eng", "per"};
String selection = "id=?";
String[] selectionArgs = new String[]{String.valueOf(id)};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase database = null;
try{
database = sqLiteOpenHelper.getWritableDatabase();
Cursor cursor = database.query("tb1_phrases", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if (cursor !=null && cursor.moveToFirst()){
int idIndex = 0;
int engIndex = 1;
int perIndex = 2;
long phraseId = cursor.getLong(idIndex);
String phraseEng = cursor.getString(engIndex);
String phrasePer = cursor.getString(perIndex);
phrases = new Phrases();
phrases.setId(phraseId);
phrases.setEng(phraseEng);
phrases.setPer(phrasePer);
}
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
}finally {
if (database!=null && database.isOpen()){
database.close();
}
}
return phrases;
}
public int updatePhrase(Phrases phrases){
int noOfDataUpdatedRecords = 0;
String whereClause = "id=?";
String[] whereArgs = new String[]{String.valueOf(phrases.getId())};
SQLiteDatabase database = null;
try{
ContentValues values = new ContentValues();
values.put("eng", phrases.getEng());
values.put("per", phrases.getPer());
database = sqLiteOpenHelper.getWritableDatabase();
noOfDataUpdatedRecords = database.update("tb1_phrases", values, whereClause, whereArgs);
}catch (Exception ex){
Log.d("Database", "Exeption: " + ex.getMessage());
} finally {
if(database!=null && database.isOpen()){
database.close();
}
}
return noOfDataUpdatedRecords;
}
public int deletePhrase(long id){
int noOfDeletedRecords = 0;
String whereClause = "id=&";
String[] whereArgs = new String[]{String.valueOf(id)};
SQLiteDatabase database = null;
try{
database = sqLiteOpenHelper.getWritableDatabase();
noOfDeletedRecords = database.delete("tb1_phrases", whereClause, whereArgs);
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
} finally {
if(database!=null && database.isOpen()){
database.close();
}
}
return noOfDeletedRecords;
}
public ArrayList<Phrases> readAllPhrases(){
ArrayList<Phrases> phrasesArrayList = null;
String[] columns = new String[]{"id", "eng", "per"};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase database = null;
try{
database = sqLiteOpenHelper.getWritableDatabase();
Cursor cursor = database.query("tb1_phrases", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if (cursor !=null && cursor.moveToFirst()){
phrasesArrayList = new ArrayList<>();
int idIndex = 0;
int engIndex = 1;
int perIndex = 2;
do {
long phraseId = cursor.getLong(idIndex);
String phraseEng = cursor.getString(engIndex);
String phrasePer = cursor.getString(perIndex);
Phrases phrases = new Phrases();
phrases.setId(phraseId);
phrases.setEng(phraseEng);
phrases.setPer(phrasePer);
phrasesArrayList.add(phrases);
}while (cursor.moveToNext());
}
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
}finally {
if (database!=null && database.isOpen()){
database.close();
}
}
return phrasesArrayList;
}
the favorite button:
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PhraseDataBaseAdapter dataBaseAdapter = new PhraseDataBaseAdapter(getApplicationContext());
Phrases phrases = new Phrases();
phrases.setEng(mainAdviceEnglish);
phrases.setPer(mainAdvicePersian);
dataBaseAdapter.savePhrase(phrases);
}
});
Thanks...
For your requirement i have a great solution without using SQLite.
You should use this class for storing your words and also it have feature to check those word has stored or not.
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WordListPref {
public static final String PREFS_NAME = "XYZ";
public static final String WORD_LIST = "WordList";
public void storeWords(Context context, List favorites) {
// used for store arrayList in json format
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(WORD_LIST, jsonFavorites);
editor.commit();
}
public ArrayList<String> loadWords(Context context) {
// used for retrieving arraylist from json formatted string
SharedPreferences settings;
List favorites;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (settings.contains(WORD_LIST)) {
String jsonFavorites = settings.getString(WORD_LIST, null);
Gson gson = new Gson();
String[] favoriteItems = gson.fromJson(jsonFavorites, String[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList(favorites);
} else
return new ArrayList<>();
return (ArrayList) favorites;
}
public void addWord(Context context, String beanSampleList) {
List favorites = loadWords(context);
if (favorites == null)
favorites = new ArrayList();
favorites.add(beanSampleList);
storeWords(context, favorites);
}
public void removeUsers(Context context, String beanSampleList) {
ArrayList<String> favorites = loadWords(context);
if (favorites != null) {
for (int i = 0; i < favorites.size(); i++) {
String bean = favorites.get(i);
if (bean == beanSampleList) {
favorites.remove(i);
storeWords(context, favorites);
}
}
}
}
public boolean isWordExist(String bean, Context context) {
ArrayList<String> data = loadWords(context);
if (data != null) {
for (int i = 0; i < data.size(); i++) {
String beanSampleList = data.get(i);
if (bean == beanSampleList) {
return true;
}
}
}
return false;
}
public void flushWordPref(Context context) {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.clear();
editor.commit();
}
}
For storing Word use Method
addWord("")
For Checking word exits
isWordExist()
This class would be solve your problem you will never use sqlite for same kind of stuffs.
Best of luck and dont forgot to VOTE :)
Here i am fetching the name,email,phone number from the mobile and trying to upload to server..Here if the contacts contains name,email and phone number the values will be inserted successfully..but if any of the field is empty it is throwing NULL pointer exception.How to avoid this one..i mean if the contact does not contain email it should atleast send name and phone number.
here is my code.
public class DisplayContact1 extends Activity {
private static String TAG = WorkDetails1.class.getSimpleName();
Button select;
private String vault;
List<AddressBookContact> list;
public static final String kvault = "vault_no";
public static final String kname = "name";
public static final String kphone = "phone";
public static final String kemail = "email";
public static final String kcontacts = "contacts";
public static final String SHARED_PREF_NAME = "myloginapp";
public static final String UPLOAD_URL = "http://oursite.com/contacts_1.php";
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
Cursor cursor;
LongSparseArray<AddressBookContact> array;
long start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.display);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
getAllContacts(this.getContentResolver());
}
public void getAllContacts(ContentResolver cr) {
int result = ContextCompat.checkSelfPermission(DisplayContact1.this, Manifest.permission.READ_CONTACTS);
if (result == PackageManager.PERMISSION_GRANTED){
//fetches contacts from the phone contact list and displays in ascending order
list = new LinkedList<AddressBookContact>();
array = new LongSparseArray<AddressBookContact>();
start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.Data.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
contactsdisplay();
} else {
requestForLocationPermission();
}
}
private void requestForLocationPermission()
{
if (ActivityCompat.shouldShowRequestPermissionRationale(DisplayContact1.this, Manifest.permission.READ_CONTACTS))
{
}
else {
ActivityCompat.requestPermissions(DisplayContact1.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getAllContacts(DisplayContact1.this.getContentResolver());
contactsdisplay();
}
break;
}
}
public void contactsdisplay() {
//Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
ListView lv= (ListView) findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
uploadImage();
}
});
}
public void uploadImage(){
SharedPreferences sharedPreferences = getSharedPreferences(DisplayContact.SHARED_PREF_NAME, MODE_PRIVATE);
final String vault_no = vault;
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DisplayContact1.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("Successfully Saved")){
//Intent intent = new Intent(CollegeDetails.this,Work.class);
Toast.makeText(DisplayContact1.this, s, Toast.LENGTH_SHORT).show();
// startActivity(intent);
}else{
Toast.makeText(DisplayContact1.this,s,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
//RegisterUserClass rh = new RegisterUserClass();
HashMap<String,String> param = new HashMap<String,String>();
JSONArray contacts = new JSONArray();
int i = 1;
for (AddressBookContact addressBookContact : list) {
try {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
JSONObject contact = new JSONObject();
contact.put(kname, addressBookContact.name.toString());
contact.put(kvault, vault_no);
contact.put(kphone, addressBookContact.phone.toString());
if(addressBookContact.email.toString()!=null)
contact.put(kemail, addressBookContact.email.toString());
contacts.put(contact);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
param.put(kcontacts, contacts.toString());
System.out.println("param value.." + i++ +":"+ contacts.toString());
}
return rh.sendPostRequest(UPLOAD_URL, param);
}
}
UploadImage u = new UploadImage();
u.execute();
}
}
here is the AddressBookContact.class
public class AddressBookContact {
private long id;
private Resources res;
String name;
LongSparseArray<String> email;
LongSparseArray<String> phone;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append(name);
} else {
builder.append("name: ").append(name);
}
if (phone != null) {
builder.append("\nphone: ");
for (int i = 0; i < phone.size(); i++) {
int type = (int) phone.keyAt(i);
builder.append(phone.valueAt(i));
if (i + 1 < phone.size()) {
builder.append(", ");
}
}
}
if (email != null) {
builder.append("\nemail: ");
for (int i = 0; i < email.size(); i++) {
int type = (int) email.keyAt(i);
builder.append(email.valueAt(i));
if (i + 1 < email.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (email == null) {
email = new LongSparseArray<String>();
}
email.put(type, address);
}
public void addPhone(int type, String number) {
if (phone == null) {
phone = new LongSparseArray<String>();
}
phone.put(type, number);
}
}
if email field is empty, i am getting null pointer exception at this line..
contact.put(kemail, addressBookContact.email.toString());..so i have added if loop to check the null condition..but then also i am getting exception.
Here
if (addressBookContact.email.toString() != null)
you try to get String from 'email' variable that is null.
Correct comparing is:
if (addressBookContact.email != null)
Add two conditions as below your string might not be null but can be
empty ""
if(addressBookContact.email.toString() != null && !addressBookContact.email.toString().equalsIgnoreCase(""))
contact.put(kemail, addressBookContact.email.toString());
Use TextUtils.
if(!TextUtils.isEmpty(addressBookContact.email.toString())){
contact.put(kemail, addressBookContact.email.toString());
}
And if kemail is compulsory field then in else condition just pass "" empty value.
In my Android application, I have a List of Phone Contacts. I want to add these contacts in private list by selection through CheckBoxe and onButtonClick. What I want here is that if contacts are already present there in database then they should not be added. How can i do so ? Please help.
Here is the code :
private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_contact_name = new ArrayList<String>();
ArrayList<String> filteredList = new ArrayList<String>();
ArrayList<String> item_contact_number = new ArrayList<String>();
Uri queryUri;
boolean flag = false;
boolean[] selection;
static ArrayList<String> selection_val;
private Button btn_select, btn_remove;
DbManager manager;
String[] contactArray;
Cursor Cursor, cursor1;
public static String[] selectedData;
String phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contacts);
manager = new DbManager(this);
try{
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
showEvents(Cursor);
cursor1 = manager.Return_All_Contacts();
contactArray = showEvents2(cursor1);
//final ViewHolder holder = new ViewHolder();
selection = new boolean[item_id.size()];
selection_val = new ArrayList<String>();
selectedData=new String[selection.length];
adapter = new MyListAdapter(this);
setListAdapter(adapter);
btn_select = (Button) findViewById(R.id.button1);
btn_select.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
// selectedData[i]=item_msg_body.get(i);
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
try{
addContacts(selectedData);
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
getApplicationContext(),
"Your have Selected " + cnt + " ids. " + " "+ selectIds, Toast.LENGTH_LONG).show();
}
}
});
}
catch(Exception ex)
{
Log.e("Error in retrieving phone", ex.toString());
}
btn_remove = (Button)findViewById(R.id.remove);
btn_remove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
deleteMultiple(selectedData);
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
}
}
});
}
public class MyListAdapter extends BaseAdapter{
Context con;
private LayoutInflater layoutinf;
ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
ArrayList<String> items_ = new ArrayList<String>();
public MyListAdapter(
privateContacts sample_MultipleSelectionActivity) {
con = sample_MultipleSelectionActivity;
}
public int getCount() {
return item_id.size();
}
public Object getItem(int position) {
return item_id.size();
}
public long getItemId(int position) {
return item_id.get(position).hashCode();
}
public View getView(final int position, View convertView, ViewGroup arg2) {
View v = convertView;
ViewHolder holder = null;
if (v == null) {
layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_add_contacts, null);
holder = new ViewHolder();
holder.chk = (CheckBox) v.findViewById(R.id.checkBox);
holder.tv_contact_name = (TextView) v.findViewById(R.id.tvname);
holder.tv_number = (TextView) v.findViewById(R.id.tvphone);
holder.iv_contact = (ImageView) v.findViewById(R.id.iv_contacts);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.chk.setId(position);
holder.tv_contact_name.setId(position);
holder.chk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
String val = cb.getText().toString();
if (selection[id]) {
cb.setChecked(false);
selection[id] = false;
selection_val.remove("" + item_contact_name.get(id));
} else {
cb.setChecked(true);
selection[id] = true;
selection_val.add("" + item_contact_name.get(id));
}
adapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("error", "" + e.toString());
}
}
});
holder.chk.setChecked(selection[position]);
if(selection[position] == true)
{
//holder.tv_contact_name.setBackgroundColor(Color.GRAY);
}
else
{
holder.tv_contact_name.setBackgroundColor(Color.TRANSPARENT);
}
// for(int i=0;i<contactArray.length;i++){
//
// holder.tv_contact_name.setBackgroundColor(Color.GREEN);
// }
//holder.chk.setText(item_id.get(position));
holder.tv_contact_name.setText("" + item_contact_name.get(position));
holder.tv_number.setText("" + item_contact_number.get(position));
return v;
}
}
public class ViewHolder {
private CheckBox chk;
private TextView tv_contact_name;
private TextView tv_number;
private ImageView iv_contact;
}
private void addContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
moveToLogActivity();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
private void showEvents(Cursor cursor) {
item_id = new ArrayList<String>(cursor.getCount());
item_contact_name = new ArrayList<String>(cursor.getCount());
item_contact_number = new ArrayList<String>(cursor.getCount());
//String ContactNames[] = new String[cursor.getCount()];
String id[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
item_contact_name.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
item_contact_number.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
i++;
}
}
private String[] showEvents2(Cursor cursor) {
String addedContacts[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
addedContacts[i] = cursor.getString(1);
i++;
}
return addedContacts;
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void deleteMultiple(String[]selectedItems) {
manager.deleteContactsMultiselected(selectedItems);
moveToLogActivity();
}
The database code where i am saving data is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
ContactTable code in database is as :
// define table name
public static final String TABLE_CONTACTS = "CONTACTS_TABLE";
//define column of TABLE_CONTACTS
public static final String KEY_CONTACTID = "_id";
public static final String CONTACT_NAME = "Contact_name";