okhttp in Background service from Broadcast receiver - android

i have app in which i am sending data to server every time when new messages receives.
Problem:
Only once data is uploaded successfully but for next times data is not uploaded. i have also used volley for this problem but it also have same problem.
What i've tried
BackgroundService.class
public class BackgroundService extends Service {
private static final String TAG = BackgroundService.class.getSimpleName();
Context context;
Uri mSmsQueryUri = Uri.parse("content://sms");
private boolean isRunning;
private Thread backgroundThread;
String phoneNumber;
SessionManager sessionManager;
ArrayList<String> smss;
String callllogs;
public BackgroundService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
this.context = this;
sessionManager = new SessionManager(this);
this.isRunning = false;
Log.i(TAG, "onCreate called");
this.backgroundThread = new Thread(myTask);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!this.isRunning) {
Log.i(TAG, "onStartCommand called");
this.backgroundThread.start();
this.isRunning = true;
stopSelf();
}
return START_STICKY;
}
private Runnable myTask = new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void run() {
if (BaseUrl.isConnectedtoInternet(context)) {
//addToServerOkhttp(context);
addtoServer(context);
} else {
Log.i(TAG, "No internt Connection");
}
}
};
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void addtoServer(final Context context) {
Log.i(TAG, "addToServer called");
String url = BaseUrl.baseUrl + context.getResources().getString(R.string.store_new_details);
Log.i(TAG, url);
smss = getMessages();
callllogs = getCallDetail();
Toast.makeText(context, "inMethod", Toast.LENGTH_SHORT).show();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response);
if (response.equals("Message Received!")) {
Toast.makeText(context, "ok rocky", Toast.LENGTH_SHORT).show();
AppController.getInstance().cancelPendingRequests(BaseUrl.tag_string_req);
}
// Toast.makeText(context, "Messages Uploaded Successfully.! (BackgroundService)", Toast.LENGTH_SHORT).show();
//Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(context, error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
if (error == null || error.networkResponse == null) {
return;
}
String body;
//get status code here
final String statusCode = String.valueOf(error.networkResponse.statusCode);
Log.i(TAG, statusCode);
//get response body and parse with appropriate encoding
try {
body = new String(error.networkResponse.data, "UTF-8");
Log.i(TAG, body);
} catch (UnsupportedEncodingException e) {
// exception
Log.i(TAG, e.getMessage());
}
Log.i(TAG, error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
Log.i(TAG, SessionManager.getPhoneNumber());
params.put("imei_no", "");
params.put("calllog", callllogs);
params.put("record", smss.toString());
params.put("phone", SessionManager.getPhoneNumber());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request, BaseUrl.tag_string_req);
// try{
// RequestQueue requestQueue= Volley.newRequestQueue(this);
// requestQueue.add(request);
// }catch (Exception e){
// Log.i(TAG,e.getMessage());
// }
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public ArrayList<String> getMessages() {
ArrayList<String> messages = new ArrayList<String>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = null;
try {
cursor = contentResolver.query(mSmsQueryUri, new String[]{"_id", "address", "date", "body",
"type", "read"}, null, null, "date desc");
if (cursor == null) {
Log.i("curson null", "cursor is null. uri: " + mSmsQueryUri);
Toast.makeText(this, "curor null", Toast.LENGTH_SHORT).show();
}
//assert cursor != null;
for (boolean hasData = cursor.moveToFirst(); hasData; hasData = cursor.moveToNext()) {
String body = cursor.getString(cursor.getColumnIndex("body"));
String address = cursor.getString(cursor.getColumnIndex("address"));
messages.add("\n" + "Number: " + address + "\n" + "Content: " + body + "\n");
}
} catch (Exception e) {
Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.e("Error", e.getMessage());
} finally {
//assert cursor != null;
cursor.close();
}
//Toast.makeText(context, "all okaay", Toast.LENGTH_SHORT).show();
return messages;
}
private String getCallDetail() {
Toast.makeText(context, "calldetails", Toast.LENGTH_SHORT).show();
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
//Toast.makeText(context, "also all ok", Toast.LENGTH_SHORT).show();
return stringBuffer.toString();
}
}
Service is called from Broadcast receiver every time when new message
receives.

Related

Android: Unable to start service because of NULL POINTER EXCEPTION

I am creating a service in onCreate of my main activity, but i am getting java.lang.RuntimeException: Unable to instantiate service com.ram.courier.service.CheckTimeService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Here is my main activity where I start my service:
if(isServiceRunning(getApplicationContext() ,CheckTimeService.class)){
Log.d("APP","RUNNING SERVICE");
}
else{
Intent myServiceIntent = new Intent(SplashScreen.this, CheckTimeService.class);
startService(myServiceIntent);
}
}
Below is my service class:
public class CheckTimeService extends Service {
final Handler handler = new Handler();
Runnable run;
DatabaseAccess databaseAccess;
ApiCall apiCall;
final String startTime = "15:00:00";
final String endTime = "18:30:00";
// Context context = this.getApplicationContext();
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY); //24 hour format
int minute = now.get(Calendar.MINUTE);
Date date = parseDate(hour + ":" + minute); //current time
//function for parsing the time
private Date parseDate(String date) {
final String inputFormat = "HH:mm";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
try{
return inputParser.parse(date);
}catch (java.text.ParseException e){
return new Date(0);
}
}
Context context = this.getApplicationContext();
DatabaseOpenHelper myDB = new DatabaseOpenHelper(getApplicationContext());
SQLiteDatabase db = myDB.getReadableDatabase();
Cursor sessID = db.rawQuery(" SELECT * FROM " + DataConstants.TABLE_SESSION + " ORDER BY SessionID DESC LIMIT 1", null);
String sessionID = sessID.toString();//convert cursor result to string
Cursor DelVehDepID = db.rawQuery(" SELECT * FROM " + DataConstants.TABLE_DEL_VEH_DEP + " ORDER BY " + DataConstants.COLUMN_VEH_DEP_ID + "DESC LIMIT 1", null);
// JSONObject jsonObjectDelVehDepID = new JSONObject(String.valueOf(DelVehDepID));//convert string to json object
// String delvehdepid = jsonObjectDelVehDepID.toString();//convert cursor to string
String delvehdepid = DelVehDepID.toString();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
run = new Runnable() {
#Override
public void run() {
Date compareTimeOne = parseDate(startTime);
Date compareTimeTwo = parseDate(endTime);
if (compareTimeOne.before(date) && compareTimeTwo.after(date)) {
Log.d("test", " Time is between " + startTime + " and " + endTime);
//call to API
apiCall = new ApiCall(getApplicationContext(), AppConstants.TASK_API_CHECK_IS_CLOSED_SESSION, delvehdepid,
AppConstants.API_CHECK_IS_CLOSED_SESSION + sessionID, new SyncServiceListener() {
#Override
public void onSuccess(int taskID, String Response) {
try {
JSONObject json = new JSONObject(Response);
Log.d("onSuccess",json.toString());
CommonCalls.getInstance().trackSyncRequestService(getApplicationContext(), AppConstants.TASK_API_CHECK_IS_CLOSED_SESSION+sessionID,json.toString());
JSONObject result = json.getJSONObject("Result");
if(result!=null && result.getString("Result")!=null){
if(result.getString("Result")=="true"){
//clear session data and logout drivers and crew members
PreferenceHandler.writeBoolean(CheckTimeService.this, "missing_pod", false);
PreferenceHandler.writeBoolean(CheckTimeService.this, "new_session", true);
PreferenceHandler.writeString(CheckTimeService.this, "activity", "");
PreferenceHandler.writeString(CheckTimeService.this, "session_id", "");
PreferenceHandler.writeString(CheckTimeService.this, "POD_bag", "");
DatabaseAccess.getInstance(CheckTimeService.this).open();
DatabaseAccess.getInstance(CheckTimeService.this).clearSheetsData();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(int taskID, String Response) {
Log.d("ERROR","ERROR...NO RESPONSE" + Response);
}
});
}
else
{
Log.d("test", "Time is not in between" + startTime + "and" + endTime);
}
handler.postDelayed(this,1000);
}
};
handler.post(run);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(run);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

call broadcast receiver being triggered three times

public class callLogs extends BroadcastReceiver {
String phNumber, callType, callDate, callDuration, dir;
Date callDayTime;
List<calls> data = new ArrayList<>();
SharedPreferences pref;
SharedPreferences.Editor edit;
ConnectionDetector cd;
private callsData callsData;
private callsDb callsDb;
private static final String DATABASE_NAME = "callsData";
#Override
public void onReceive(final Context context, Intent intent) {
pref = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
edit = pref.edit();
callsData = Room.databaseBuilder(context.getApplicationContext(),
callsData.class, DATABASE_NAME).fallbackToDestructiveMigration().build();
// cd = new ConnectionDetector(context.getApplicationContext());
CountDownTimer countDownTimer = new CountDownTimer(500 , 1000) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
StringBuffer sb = new StringBuffer();
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Cursor managedCursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, strOrder);
int name = managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
managedCursor.moveToFirst();
// while (managedCursor.moveToNext()) {
String pName = managedCursor.getString(name);
phNumber = managedCursor.getString(number); // mobile number
callType = managedCursor.getString(type); // call type
callDate = managedCursor.getString(date); // call date
callDayTime = new Date(Long.valueOf(callDate));
callDuration = managedCursor.getString(duration);
dir = null;
// Log.d("Name",pName);
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
case CallLog.Calls.REJECTED_TYPE:
dir = "REJECTED";
break;
}
new Thread(new Runnable() {
#Override
public void run() {
callsDb = new callsDb();
callsDb.setPhone(phNumber);
callsDb.setType(dir);
callsDb.setDate(String.valueOf(callDayTime));
callsDb.setDuration(callDuration);
callsData.callsDao().insertAll(callsDb);
}
}).start();
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
sb.append("\n----------------------------------");
// }
managedCursor.close();
// textView.setText(sb);
Log.d("Agile", sb.toString());
Log.d("data",callsDb.getPhone());
Log.d("type kya hai",callsDb.getType());
calls person = new calls();
person.setMobile(callsDb.getPhone());
person.setType(callsDb.getType());
person.setDate(callsDb.getDate());
person.setDuration(callsDb.getDuration());
data.add(person);
Bean b = (Bean) context.getApplicationContext();
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(b.baseURL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Allapi cr = retrofit.create(Allapi.class);
callsBean body = new callsBean();
body.setCallLogs(data);
Gson gsonObj = new Gson();
String jsonStr = gsonObj.toJson(body);
String id = pref.getString("id", "");
Log.d("id", id);
Log.d("id", pref.getString("id", ""));
Log.d("id", jsonStr);
Call<callsBean> call = cr.calls(id, jsonStr);
call.enqueue(new Callback<callsBean>() {
#Override
public void onResponse(Call<callsBean> call, Response<callsBean> response) {
Log.d("response", response.body().getCallLogs().toString());
/*new Thread(new Runnable() {
#Override
public void run() {
callsData.callsDao().delete(callsDb);
}
}).start();*/
}
#Override
public void onFailure(Call<callsBean> call, Throwable t) {
}
});
}
};
countDownTimer.start();
}
I have created a BroadcastReceiver for call code is working fine and storing data in Room Database, latest call is being stored but there i am calling an Api to store data on server as well getting from Room Databse
but the problem is Api being hit three times i think because of broadcast
receiver.
When call is incoming first api will hit on incoming the second on receiving time and third it will hit on end call time, this happening as well in missed call and outgoing call time.
please help me to find the solution for this.
i want Api should hit only one time

Android AsyncTask class Hanged my Application why?

i call MyTask().execute(); in onCreate() of MainAcivity Class in my application. it Busy or Hang my application for long time. please help me why? i want my work in background so that it can't disturb my app. Why my app become busy and unresponsive?
Class code is below:
private class MyTask extends AsyncTask<String, Integer, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
super.onPreExecute();
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
checkUser();
return "";
}
// This is called from background thread but runs in UI
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Do things like update the progress bar
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Do things like hide the progress bar or change a TextView
}
}
checkUser() method code is below
private void checkUser(){
// now here we convert this list array into json string
final String server_url="http://www.xxxx.com/TruCaller/check_user.php"; // url of server check this 100 times it must be working
// volley
StringRequest stringRequest=new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
final String result=response.toString().trim();
if(result.equals("not found")){
//Toast.makeText(MainActivity.this,"Wait...",Toast.LENGTH_LONG).show();
// Log.d("responsedd", "result not found fffffffff: "+result);
getContacts2();
}else{
}
// Log.d("responsedd", "result : "+result); //when response come i will log it
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
error.getMessage(); // when error come i will log it
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("identifier", UIDD);
Log.d("responsedd", "result not found ggggggggggg: "+ UIDD);
return params;
}
};
Vconnection.getnInstance(this).addRequestQue(stringRequest); // vConnection i claas which used to connect volley
}
getContacts2() method code is below:
public void getContacts2() {
if (!mayRequestContacts()) {
return;
}
// contactList = new ArrayList<String>();
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
String phoneC = "", adressC = "", emailC = "",country_code="";
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
Bitmap bitmap = null;
String image = "";
if (hasPhoneNumber > 0) {
////////////////////Phone numbers with this name..... 2 Testing ....////////////////
String phoneNumber2 = "";
final String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE,};
final Cursor phone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contact_id)}, null);
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
phoneC = "";
while (!phone.isAfterLast()) {
////////////////////////////////////////////
String x = phone.getString(contactNumberColumnIndex);
bitmap = retrieveContactPhoto(MainActivity.this, x);
String countryCode = countryCode(phone.getString(contactNumberColumnIndex));
country_code = countryCode;
// String swissNumberStr = "03348633664";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.createInstance(getApplicationContext());
Phonenumber.PhoneNumber pNumberProto;
String phoneVerfid="";
try {
pNumberProto = phoneUtil.parse(phone.getString(contactNumberColumnIndex), countryCode);
// System.err.println("NumberParseException was thrown:>>>>>>>>>>>> " + pNumberProto);
boolean isValid = phoneUtil.isValidNumber(pNumberProto);
if(isValid){
System.out.println(phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
phoneVerfid = phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
}
} catch (NumberParseException e) {
// System.err.println("NumberParseException was thrown: " + e.toString() +" ???" +phone.getString(contactNumberColumnIndex) + countryCode);
}
///////////////////////////////
phoneNumber2 = phoneVerfid + "_";
// output.append("\n Phone number:" + phoneNumber2);
phoneC = phoneC + phoneNumber2;
// System.out.println("Country = "+countryCode(phoneNumber2) + " p= " +phoneNumber2);
phone.moveToNext();
}
}
phone.close();
/////////////////////////////////////////////////////////////
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
emailC = "";
email = "";
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA)) + "%";
if (!emailC.contains(email)) {
emailC = emailC + email;
// output.append("\n Email:" + email);
}
}
emailCursor.close();
//////////// Adresss//////
String postalData = "";
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{String.valueOf(contact_id), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);
if (addrCur.moveToFirst()) {
postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
//output.append("\n Address:" + postalData);
adressC = adressC + " " + postalData;
}
addrCur.close();
}
if (phoneC != "") {
if (bitmap != null) {
Bitmap bitmap1 = getResizedBitmap(bitmap,210);
image = getStringImage(bitmap1);
if(bitmap1!=null) {
bitmap1.recycle();
}
// System.out.println("KKKKKKKKKKKKKKKKKKK >>>>>>>>> "+image);
}
Contact_Details dt = new Contact_Details(name, phoneC, UIDD, country_code, image, emailC, adressC);
dataArray.add(dt);
if(bitmap!=null){ bitmap.recycle();}
image = "";
}
}
submit1User2Contacs();
}
}
MainAcivity onCreate Method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new MyTask().execute();}
Looks like you haven't called close method for cursor object.
Calling cursor.close() will solve your problem
i try below code instead of new MyTask().execute() class. and the below code work for me. i also try below code with xxx.run(); method instead of start();. run() method also not work. only thread with xxx.start(); worked. so the correct code is below one. Thanks every one.
new Thread(new Runnable(){
#Override
public void run() {
//my method
checkUser();
}
}).start();

Object cannot be accessed, is it deleted by another thread?

I have this function which is called when there is any change in Contacts in Phone, Now the problem here is that this code works fine on HTC Desire 620 (KitKat) but crashes on Moto G (Lollipop) and other devices.
Error : java.lang.IllegalStateException: Illegal State: object is no longer valid to operate on. Was it deleted?
Also: It works fine with Moto G2 if contacts are less like < 500 but if more it crashes!
Logcat details:
E/AndroidRuntime: Process: com.advisualinc.echo:SwitchService, PID: 16972
E/AndroidRuntime: java.lang.IllegalStateException: Illegal State: Object is no longer valid to operate on. Was it deleted by another thread?
E/AndroidRuntime: at io.realm.internal.UncheckedRow.nativeGetString(Native Method)
E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
My service class:
public class ContactsSyncService extends Service {
public static int count = 0;
int k = 0;
Realm realmFresh;
public static boolean contactUpdated = false;
ContentObserver mObserver;
public Context contextService = ContactsSyncService.this;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
k++;
// Toast.makeText(ApplicationController.getInstance(), "Starting Change: " , Toast.LENGTH_SHORT).show();
if (!contactUpdated) {
contactUpdated = true;
Logger.debug("Contact Update to start -->");
// Toast.makeText(ApplicationController.getInstance(), "Changing: " , Toast.LENGTH_SHORT).show();
FetchLocalContacts.refreshingContactsDB(contextService);
// Toast.makeText(ApplicationController.getInstance(), "Changed: " , Toast.LENGTH_SHORT).show();
}
}
};
getContentResolver().registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, mObserver);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
getContentResolver().unregisterContentObserver(mObserver);
}
}
The Function called by Service is refreshingContactsDB():
public static void parseContactstoContactsDB()
{
Thread background = new Thread(new Runnable()
{
public void run()
{
Realm realmFetchFirstTime = Realm.getInstance(ApplicationController.getInstance());
ContentResolver cr = ApplicationController.getInstance()
.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION,null,null, null);
String duplicateName = "";
String duplicatePhone = "";
if( phones.getCount() >0)
{
final int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
String name = phones.getString(nameIndex);
String phoneNo = phones.getString(numberIndex);
if(phoneNo!=null&&!phoneNo.isEmpty())
{
phoneNo = phoneNo.replace(" ", "");
phoneNo = phoneNo.replace("(", "");
phoneNo = phoneNo.replace(")", "");
phoneNo = phoneNo.replace("-", "");
phoneNo = phoneNo.replace("\u00a0", "");
phoneNo = phoneNo.replace("\u202c", "");
phoneNo = phoneNo.replace("\u2011", "");
phoneNo = phoneNo.replace("\u202a", "");
phoneNo = phoneNo.replace("*", "");
phoneNo = phoneNo.replace("#", "");
if (phoneNo.length() >= 5)
{
if(name.equalsIgnoreCase(duplicateName)&&phoneNo.equalsIgnoreCase(duplicatePhone))
{
continue;
}
duplicateName = name;
duplicatePhone = phoneNo;
String formattedPhoneNumber;
formattedPhoneNumber = parseNumber(phoneNo);
realmFetchFirstTime.beginTransaction();
R_LocalContactDB rContacts = realmFetchFirstTime.createObject(R_LocalContactDB.class);
rContacts.setName(name);
rContacts.setPhone(formattedPhoneNumber);
realmFetchFirstTime.commitTransaction();
Logger.debug("Formatted Contacts --> Name: "
+ name
+ " -- Phone No: "
+ formattedPhoneNumber);
}
}
}
phones.close();
}
realmFetchFirstTime.close();
// getNumbersFromDBAndUpdate();
}
});
background.start();
}
public static void getNumbersFromDBAndUpdate()
{
Realm realmServer = Realm.getInstance(ApplicationController.getInstance());
RealmResults<R_LocalContactDB> query = realmServer.where(R_LocalContactDB.class).findAll();
Logger.debug("Contact Update updating to server -->");
for (int i = 0; i < query.size(); i++)
{
phoneNumberJsonArray.put(query.get(i).getPhone());
}
try
{
uploadContactJsonBody.put("phone_numbers", phoneNumberJsonArray);
Logger.debug("LocalContacts RequestJson ---> "
+ uploadContactJsonBody.toString());
AppPreferenceManager.getInstance().setContactPref(1);
UploadLocalContactsToServerAsynTask test = new UploadLocalContactsToServerAsynTask(
uploadContactJsonBody.toString(),
new LocalContactsSyncCallBack()
{
#Override
public void didFinishProfileSync(boolean bool,
String result) {
Logger.debug("Is ContactUpdated FetchContacts --> "
+ bool);
setMatchedStatusToFalse();
AppPreferenceManager.getInstance().setContactUpdate(bool);
Intent roomIntent = new Intent();
roomIntent
.setAction("com.advisualinc.echo.fetch.local_contacts");
ApplicationController.getInstance().sendBroadcast(roomIntent);
}
});
test.execute();
}
catch (JSONException e)
{
e.printStackTrace();
}
realmServer.close();
}
public static void refreshingContactsDB()
{
Thread background = new Thread(new Runnable()
{
public void run()
{
realmFresh = Realm.getInstance(ApplicationController.getInstance());
createCountryDetailsArrayModel();
R_LocalContactDB rCont;
TelephonyManager tm = (TelephonyManager) ApplicationController.getInstance()
.getSystemService(Context.TELEPHONY_SERVICE);
String simCountryISO = tm.getSimCountryIso();
for (int i = 0; i < countryDetailsList.size(); i++)
{
if (simCountryISO.equalsIgnoreCase(countryDetailsList.get(i)
.getCode()))
{
dialCodePrefix = countryDetailsList.get(i).getDial_code();
}
}
AppPreferenceManager.getInstance().setContactUpdate(false);
Logger.debug("Contact Update Refreshing Contact Started -->");
ContentResolver cr = ApplicationController.getInstance()
.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
String duplicateName = "";
String duplicatePhone = "";
if (phones.getCount() > 0)
{
final int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
String name = phones.getString(nameIndex);
String phoneNo = phones.getString(numberIndex);
if (phoneNo != null && !phoneNo.isEmpty())
{
phoneNo = phoneNo.replace(" ", "");
phoneNo = phoneNo.replace("(", "");
phoneNo = phoneNo.replace(")", "");
phoneNo = phoneNo.replace("-", "");
phoneNo = phoneNo.replace("\u00a0", "");
phoneNo = phoneNo.replace("\u202c", "");
phoneNo = phoneNo.replace("\u2011", "");
phoneNo = phoneNo.replace("\u202a", "");
phoneNo = phoneNo.replace("*", "");
phoneNo = phoneNo.replace("#", "");
if (phoneNo.length() >= 5)
{
if (name.equalsIgnoreCase(duplicateName) && phoneNo.equalsIgnoreCase(duplicatePhone)) {
continue;
}
duplicateName = name;
duplicatePhone = phoneNo;
String formattedPhoneNumber;
formattedPhoneNumber = parseNumber(phoneNo);
R_LocalContactDB realmResults = realmFresh.where(R_LocalContactDB.class).equalTo("phone", formattedPhoneNumber).findFirst();
Logger.debug("Size: " + realmResults);
R_LocalContactDB rContacts = new R_LocalContactDB(null, null, false, 0);
if (realmResults == null)
{
i++;
realmFresh.beginTransaction();
rCont = realmFresh.copyToRealm(rContacts);
rCont.setName(name);
rCont.setPhone(formattedPhoneNumber);
rCont.setStatus(0);
rCont.setMatchedWithRecent(true);
// Logger.debug("New Size: " + query.size());
realmFresh.commitTransaction();
}
else if( realmResults.isValid())
{
realmFresh.beginTransaction();
if (!name.equalsIgnoreCase(realmResults.getName()))
{
realmResults.setName(name);
}
realmResults.setMatchedWithRecent(true);
// Logger.debug("New Size Else Condition: " + query.size());
realmFresh.commitTransaction();
}
}
}
}
ContactsSyncService.contactUpdated = false;
}
realmFresh.close();
deleteExtraContacts();
getNumbersFromDBAndUpdate();
}
});
background.start();
}

SQLite in Android: do I have to download any SQLite Administration (like MySQL) or it is already in device memory?

I need to work with SQLite in Android.
So, do I have to download any SQLite Administration (like MySql) or it is already in device memory?
All you need is already installed. To inspect the database during development you can use the sqlite3 tool. It is installed in the emulator.
You Don't need to download anything.its already there.
You don't have to do anything besides using the built-in tools in the Android SDK. For more information please have a look at the sqlite documentation
Basically you can use Java code to create databases, insert records into them, modify them etc.
If you want a graphical way to work on the databases, simply use Eclipse's DDMS View to navigate into your app's databases folder. From there, download the database on your computer and open it with one of the many sqlite applications available.
------------------------------------------------------------------------
Sqlite
----------------------------------------------------------------------
// instance varieable
Button btn_insert,btn_update,btn_show,btn_delete,btn_search;
EditText edit_no,edit_name,edit_mark;
Cursor c;
Context context=this;
SQLiteDatabase db;
StringBuffer sb;
init
edit_no= (EditText) findViewById(R.id.edit_no);
edit_name= (EditText) findViewById(R.id.edit_name);
edit_mark= (EditText) findViewById(R.id.edit_mark);
btn_insert= (Button) findViewById(R.id.btn_insert);
btn_update= (Button) findViewById(R.id.btn_update);
btn_show= (Button) findViewById(R.id.btn_show);
btn_delete= (Button) findViewById(R.id.btn_delete);
btn_search= (Button) findViewById(R.id.btn_search);
db=openOrCreateDatabase("topstech",context.MODE_PRIVATE,null);
db.execSQL("create table if not exists register(no varchar2(20),name varchar2(20),mark varchar2(20))");
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (edit_no.getText().toString().trim().length() == 0) {
edit_no.setError("Enter Your No");
return;
} else if (edit_name.getText().toString().trim().length() == 0) {
edit_name.setError("Enter Your Name");
return;
} else if (edit_mark.getText().toString().trim().length() == 0) {
edit_mark.setError("Enter Your Mark");
return;
} else {
db.execSQL("insert into register values('" + edit_no.getText().toString() + "','" + edit_name.getText().toString() + "','" + edit_mark.getText().toString() + "')");
Toast.makeText(context, "Record Successfully Inserted...", Toast.LENGTH_SHORT).show();
Clear();
}
}
});
btn_show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
c=db.rawQuery("select * from register",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
sb.append(c.getString(c.getColumnIndex("no"))+"\t");
sb.append(c.getString(c.getColumnIndex("name"))+"\t");
sb.append(c.getString(c.getColumnIndex("mark"))+"\n");
}while (c.moveToNext());
Toast.makeText(MainActivity.this, ""+sb, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Empty Record...", Toast.LENGTH_SHORT).show();
}
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
db.execSQL("delete from register where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Deleted...", Toast.LENGTH_SHORT).show();
Clear();
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_search.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
edit_name.setText(c.getString(c.getColumnIndex("name")));
edit_mark.setText(c.getString(c.getColumnIndex("mark")));
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
if (edit_name.getText().toString().trim().length() == 0)
{
edit_name.setError("Enter Your Name");
return;
}
else if (edit_mark.getText().toString().trim().length() == 0)
{
edit_mark.setError("Enter Your Mark");
return;
}
else
{
//Syntex:-
// db.execSQL("update tablename set col_name='" +edit_name+"' where no='" + no+ "'");
db.execSQL("update register set name='"+edit_name.getText().toString()+"',mark='"+edit_mark.getText().toString()+"' where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Updated...", Toast.LENGTH_SHORT).show();
Clear();
}
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
}
-----------------------------------------
Upload Image ANd Fetch Device Contact JSON ARRAY
------------------------------------------
Upload Image Using Retrofit
#Multipart
#POST("addDocument")
Call<AddDocumentsResponse> doAddDocuments(#Header("Authorization") String token, #Part List<MultipartBody.Part> files, #PartMap Map<String, RequestBody> map);
private void uploadDocuments() {
if (Utility.checkInternetConnection(InsurenceActivity.this)) {
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("document_type", RequestBody.create(MediaType.parse("text/plain"), "insurance"));
map.put("expiry_date", RequestBody.create(MediaType.parse("text/plain"), str_select_date));
map.put("photo_id_type", RequestBody.create(MediaType.parse("text/plain"), ""));
multipart.add(Utility.prepareFilePart(InsurenceActivity.this, "document_file", picturePath));
messageUtil.showProgressDialog(InsurenceActivity.this);
Call<AddDocumentsResponse> registerResponseCall = ApiClient.getApiInterface().doAddDocuments(fastSave.getString(Constant.ACCESS_TOKEN), multipart, map);
Log.d("request","---- Request -----"+map.toString());
registerResponseCall.enqueue(new Callback<AddDocumentsResponse>() {
#Override
public void onResponse(Call<AddDocumentsResponse> call, Response<AddDocumentsResponse> response) {
if (response.code() == 200) {
if (response.body().getStatus().equalsIgnoreCase("fail"))
{
messageUtil.hideProgressDialog();
messageUtil.showErrorToast(response.body().getMessage());
return;
}
if (response.body().getStatus().equalsIgnoreCase("success"))
{
Log.d("response","---- Respons -----"+new Gson().toJson(response));
messageUtil.hideProgressDialog();
messageUtil.showSuccessToast(response.body().getMessage());
str_select_date = str_select_date;
picturePath = null;
Log.d("TAG", "success:............... " + new Gson().toJson(response));
finish();
}
}
}
#Override
public void onFailure(Call<AddDocumentsResponse> call, Throwable t) {
messageUtil.hideProgressDialog();
messageUtil.showErrorToast("Something went wrong");
}
});
} else {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
}
}
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
ll_profile_file.setVisibility(View.GONE);
img_photo_file.setVisibility(VISIBLE);
img_photo_file.setImageURI(resultUri);
picturePath = resultUri.getPath();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
}
}
}
Fetch Device Contact Fast
ArrayList<Contact> listContacts;
listContacts = new ContactFetcher(this).fetchAll();
public class ContactPhone {
public String number;
public String type;
public ContactPhone(String number, String type) {
this.number = number;
this.type = type;
}
}
public class ContactFetcher {
private final Context context;
public ContactFetcher(Context c) {
this.context = c;
}
public ArrayList<Contact> fetchAll() {
String[] projectionFields = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
ArrayList<Contact> listContacts = new ArrayList<>();
CursorLoader cursorLoader = new CursorLoader(context,
ContactsContract.Contacts.CONTENT_URI,
projectionFields, // the columns to retrieve
null, // the selection criteria (none)
null, // the selection args (none)
null // the sort order (default)
);
Cursor c = cursorLoader.loadInBackground();
final Map<String, Contact> contactsMap = new HashMap<>(c.getCount());
if (c.moveToFirst()) {
int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
int nameIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
String contactId = c.getString(idIndex);
String contactDisplayName = c.getString(nameIndex);
Contact contact = new Contact(contactId, contactDisplayName);
contactsMap.put(contactId, contact);
listContacts.add(contact);
} while (c.moveToNext());
}
c.close();
matchContactNumbers(contactsMap);
matchContactEmails(contactsMap);
return listContacts;
}
public void matchContactNumbers(Map<String, Contact> contactsMap) {
// Get numbers
final String[] numberProjection = new String[]{
Phone.NUMBER,
Phone.TYPE,
Phone.CONTACT_ID,
};
Cursor phone = new CursorLoader(context,
Phone.CONTENT_URI,
numberProjection,
null,
null,
null).loadInBackground();
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
final int contactIdColumnIndex = phone.getColumnIndex(Phone.CONTACT_ID);
while (!phone.isAfterLast()) {
final String number = phone.getString(contactNumberColumnIndex);
final String contactId = phone.getString(contactIdColumnIndex);
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
final int type = phone.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
CharSequence phoneType = Phone.getTypeLabel(context.getResources(), type, customLabel);
contact.addNumber(number, phoneType.toString());
phone.moveToNext();
}
}
phone.close();
}
public void matchContactEmails(Map<String, Contact> contactsMap) {
// Get email
final String[] emailProjection = new String[]{
Email.DATA,
Email.TYPE,
Email.CONTACT_ID,
};
Cursor email = new CursorLoader(context,
Email.CONTENT_URI,
emailProjection,
null,
null,
null).loadInBackground();
if (email.moveToFirst()) {
final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);
final int contactIdColumnsIndex = email.getColumnIndex(Email.CONTACT_ID);
while (!email.isAfterLast()) {
final String address = email.getString(contactEmailColumnIndex);
final String contactId = email.getString(contactIdColumnsIndex);
final int type = email.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
CharSequence emailType = Email.getTypeLabel(context.getResources(), type, customLabel);
contact.addEmail(address, emailType.toString());
email.moveToNext();
}
}
email.close();
}
public class ContactEmail {
public String address;
public String type;
public ContactEmail(String address, String type) {
this.address = address;
this.type = type;
}
}
public class Contact {
public String id;
public String name;
public ArrayList<ContactEmail> emails;
public ArrayList<ContactPhone> numbers;
public Contact(String id, String name) {
this.id = id;
this.name = name;
this.emails = new ArrayList<ContactEmail>();
this.numbers = new ArrayList<ContactPhone>();
}
#Override
public String toString() {
String result = name;
if (numbers.size() > 0) {
ContactPhone number = numbers.get(0);
result += " (" + number.number + " - " + number.type + ")";
}
if (emails.size() > 0) {
ContactEmail email = emails.get(0);
result += " [" + email.address + " - " + email.type + "]";
}
return result;
}
public void addEmail(String address, String type) {
emails.add(new ContactEmail(address, type));
}
public void addNumber(String number, String type) {
numbers.add(new ContactPhone(number, type));
}
JSON ARRAY
Model model = new Model();
ArrayList<Model> contacts_arraylist=new ArrayList<>();
for (int i = 0; i < 50; i++)
{
model.setName("sanjay"+i);
model.setEmails("sanjay#gmail.com"+i);
model.setNumbers("89689527"+i);
contacts_arraylist.add(model);
}
JSONArray personarray=new JSONArray();
for (int j = 0; j < contacts_arraylist.size(); j++)
{
JSONObject person1 = new JSONObject();
try {
if(contacts_arraylist.get(j).getName()!=null)
{
person1.put("name", contacts_arraylist.get(j).getName());
}
else {
person1.put("name","");
}
if(contacts_arraylist.get(j).getEmails().length()>0)
{
person1.put("email", contacts_arraylist.get(j).getEmails());
}
else {
person1.put("email", "");
}
if(contacts_arraylist.get(j).getNumbers().length()>0)
{
person1.put("mobile_number", contacts_arraylist.get(j).getNumbers());
}
else {
person1.put("mobile_number", "");
}
personarray.put(person1);
} catch (JSONException e)
{
e.printStackTrace();
}
}
txt_array.setText(personarray.toString());
System.out.println("jsonString:---- " + personarray.toString());
}

Categories

Resources