create json data in android for call logs - android

I want to create a json format for my call logs details like the below and send it to the server in android :
{"Calllogs":{
"logdata":[
{
"id":"9791",
"number":"+919122185954",
"duration":"0",
"types":"3",
"date":"1425887846182",
"name":"ww"}
,
{
"id":"9790",
"number":"+91712222777",
"duration":"32",
"types":"1",
"date":"1425880324221",
"name":"Dpika"}
:
:
:
:
]}}
but when i use the below code to fetch all the call logs details in json format and send it to the server , i am getting a very unusual error like when i send 30 contacts it is working fine but when i fetch more than that i am getting an error ????
CODE:
public void GetCallLogs()
{
JSONObject main= new JSONObject();
JSONObject calllogs = new JSONObject();
JSONArray logs = new JSONArray();
Cursor cur = getContentResolver().query(Uri.parse("content://call_log/calls"),null, null, null, "_ID DESC");
cur.moveToFirst();
int nameColumn = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
int numberColumn = cur.getColumnIndex(CallLog.Calls.NUMBER);
int dateColumn = cur.getColumnIndex(CallLog.Calls.DATE);
int duretion = cur.getColumnIndex(CallLog.Calls.DURATION);
int type = cur.getColumnIndex(CallLog.Calls.TYPE);
int id = cur.getColumnIndex(CallLog.Calls._ID);
int i=0;
JSONObject studenti = new JSONObject();
while (!cur.isAfterLast() && i < 50) {
String name = cur.getString(nameColumn);
String number = cur.getString(numberColumn);
String date = cur.getString(dateColumn);
String duration = cur.getString(duretion);
String types = cur.getString(type);
String ids = cur.getString(id);
try {
studenti.put("id", ids);
studenti.put("name",name);
studenti.put("date", date);
studenti.put("duration", duration);
studenti.put("types", types);
studenti.put("number", number);
Log.d("HERE IN FETCHCALL", "name"+name);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logs.put(studenti);
studenti = new JSONObject();
cur.moveToNext();
i++;
}
try {
calllogs.put("logdata", logs);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
main.put("Calllogs", calllogs);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Since you are not giving enough info, I must have to assume that you are wanting to create a JSON file with your following code:
name
number
date
duration
types
ids
I have used this link to create JSON files for my ListView.

Related

Android SQL Lite query very slow

I have developed a this function for search all element in a 20 km range respect position of single element into
ArrayList<GeoJsonResponse> result = new ArrayList<GeoJsonResponse>();
Cursor cursor = mDb.query(database_event_schema.TABLE_NAME, null, null, null, null, null, null);
String[] colums = new String[]{database_event_schema._EVENT_ID,database_event_schema._AUTHOR, database_event_schema._LAT,database_event_schema._LON,database_event_schema._PLACE,database_event_schema._MAG,database_event_schema._DEPTH,database_event_schema._TIME};
Double lat,lon,magnitude = null,distance = null;
if (cursor != null) {
while (cursor.moveToNext()) {
try{lat = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._LAT)));}catch(Exception e){continue;}
try{lon = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._LON)));}catch(Exception e){continue;}
String place = cursor.getString(cursor.getColumnIndex(database_event_schema._PLACE));
double dist_km = Utills.distance(curPos.latitude,curPos.longitude,lat,lon,'K');
if(dist_km>=0 && dist_km<=10) {
String id = cursor.getString(cursor.getColumnIndex(database_event_schema._EVENT_ID));
String author = cursor.getString(cursor.getColumnIndex(database_event_schema._AUTHOR));
try{magnitude = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._MAG)));}catch(Exception e){}
try{distance = Double.valueOf(cursor.getString(cursor.getColumnIndex(database_event_schema._DEPTH)));}catch(Exception e){}
String date = cursor.getString(cursor.getColumnIndex(database_event_schema._TIME));
Date dateNew = null;
if(!date.equals(""))
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
dateNew = format.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("test", e.getLocalizedMessage());
}
}
result.add(new GeoJsonResponse(id,author,place,magnitude,distance,date,dateNew,lat,lon));
}
}
}
return result;
but the query is very slow. How can I increase the speed query?
By this table the query select all element with a location with 20km respect the event selected. The table have 500.000 record whitout index.
The result are show into a list
I have write a wrong code?
Thanks
You should create a SQLite distance function in C (so the distance calculation will be faster) and use it as a filter in your query to limit the results.
See an example (for iOS): http://www.thismuchiknow.co.uk/?p=71

how to show data that get from selected listview in another activity

i have an app where in a form show the list view. the user can click one of the list view and when clicking the app will move to another activity and it's activity will show some data based on "code" that sent from the list view form. my app is success to move in another activity but doesn't show the data. please help me.
Thank you.
This is my code in list view form :
final ListView lv = (ListView)findViewById(R.id.lv);
String url = "http://192.168.43.244/wewash/listview.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("nama", c.getString("nama"));
map.put("tanggal_keluar", c.getString("tanggal_keluar"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(halaman_utama.this, MyArrList, R.layout.listview,
new String[] {"nama", "tanggal_keluar","id", ""}, new int[] {R.id.tsnama, R.id.tstglk, R.id.kode, R.id.tsspasi});
lv.setAdapter(sAdap);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String kode = ((TextView) findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(halaman_utama.this, p_daftar_pakaian.class);
//menampilkan value dari item yg diklik
in.putExtra("id", kode);
startActivity(in);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and it's my code in new activity :
Intent intent = getIntent();
String kode = intent.getStringExtra("id");
String url = "http://192.168.43.244/wewash/listview_detail.php?id="+kode;
try {
JSONArray data = new JSONArray(getJSONUrl(url));
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String idpk = c.getString("id");
String namapk = c.getString("nama");
String paketpk = c.getString("paket");
String cbiasapk = c.getString("cbiasa");
String ckhususpk = c.getString("ckhusus");
String tglantarpk = c.getString("tanggal_keluar");
String totalpk = c.getString("total");
// String nomorpk = c.getString("no_hp");
atasnama.setText(namapk);
ereview.setText("Id Pelanggan : " +idpk+
"\nNama Pelanggan : "+namapk+
"\nPaket : "+paketpk+
"\nCucian Biasa : "+cbiasapk+" kg"+
"\nCucian Khusus : "+ckhususpk+" item"+
"\nTotal : "+totalpk+" rupiah"+
"\nTanggal Antar : "+tglantarpk);
// enomer.setText(nomorpk);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
and it's the php file
<?php
mysql_connect("localhost","root","");
mysql_select_db("wewash");
$kode=$_GET["id"];
$sql=mysql_query("select * from pakaian where id='$kode'");
$arrayId=array();
if($sql === FALSE) {
die(mysql_error());
}
while($row=mysql_fetch_array($sql)){
$arrayId["id"]=$row["id"];
$arrayId["nama"]=$row["nama"];
$arrayId["tanggal_keluar"]=$row["tanggal_keluar"];
$arrayId["paket"]=$row["paket"];
$arrayId["cbiasa"]=$row["cbiasa"];
$arrayId["ckhusus"]=$row["ckhusus"];
$arrayId["total"]=$row["total"];
}
echo json_encode($arrayId);
?>

what is the value of AUTHORITY to delete messages

Good day to all!!!
We can delete call history using CallLog.AUTHORITY. Here is an utility method to delete calls...
public static void deleteCallLogsFromNative(Context context, long[] rowIds) {
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
rowIds.length);
for (int i = 0, N = rowIds.length; i < N; i++) {
operations.add(ContentProviderOperation
.newDelete(CallLog.Calls.CONTENT_URI)
.withSelection(CallLog.Calls._ID + " = ?",
new String[] { String.valueOf(rowIds[i]) }).build());
}
try {
context.getContentResolver().applyBatch(CallLog.AUTHORITY,
operations);
} catch (Exception e) {
Log.e(TAG,
"Error while deleting calls from native: " + e.toString());
}
}
You can observe that for applying batch operation, we need an AUTHORITY and here is CallLog.AUTHORITY is required to delete call logs.
Similarly I have another utility method for deleting messages...
public static void deleteMessagesFromNative(Context context, long[] rowIds) {
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
rowIds.length);
for (int i = 0, N = rowIds.length; i < N; i++) {
long rowId = rowIds[i];
operations.add(ContentProviderOperation
.newDelete(Uri.parse("content://sms/"))
.withSelection(BaseColumns._ID + " = ?",
new String[] { String.valueOf(rowId) }).build());
}
try {
// here I need AUTHORITY value for deleting messages
} catch (Exception e) {
// TODO: handle exception
}
}
Now my question is, What is the value of AUTHORITY to delete messages?

How do the retrieve the date of the mms from content://mms.

I did get the information on how to retrieve the text and the image for the mms sent from this link: How to Read MMS Data in Android?.
But I am not sure how to retrieve the date for the mms that was sent.
I know I have to look into content://mms and not in content://mms/part.
This is the Mothod to retrieve the mms text:
private String getMmsText(String id) {
Uri partURI = Uri.parse("content://mms/part/" + id);
InputStream is = null;
StringBuilder sb = new StringBuilder();
try {
is = getContentResolver().openInputStream(partURI);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String temp = reader.readLine();
while (temp != null) {
sb.append(temp);
temp = reader.readLine();
}
}
} catch (IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
and then, in the onCreate method, I use this code to get the info:
Cursor cursor = getContentResolver().query(uri, null, selectionPart,
null, null);
if (cursor.moveToFirst()) {
do {
String partId = cursor.getString(cursor.getColumnIndex("_id"));
String type = cursor.getString(cursor.getColumnIndex("ct"));
if ("text/plain".equals(type)) {
String data = cursor.getString(cursor
.getColumnIndex("_data"));
if (data != null) {
// implementation of this method above
body = getMmsText(partId);
} else {
body = cursor.getString(cursor.getColumnIndex("text"));
}
}
} while (cursor.moveToNext());
}
try {
main.setText(body);
img.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
I just want to know where can I make changes to get the date value.
Some info will be really helpful.
I'm not overly familiar with MMS's, but I'd imagine something like this would at least get you started
Cursor cursor = activity.getContentResolver().query(Uri.parse("content://mms"),null,null,null,date DESC);
count = cursor.getCount();
if (count > 0)
{
cursor.moveToFirst();
long timestamp = cursor.getLong(2);
Date date = new Date(timestamp);
String subject = cursor.getString(3);
}
It's completely untested of course, but should point you in the right direction. Hope this helps!
Edit
After doing a bit of reading, there used to be (possibly still is) a "bug" with the timestamp in MMS messages, when retrieving the data. If you end up with a silly value (like the epoch), you'll have to * 1000 before using it. Just an aside :) I.e.:
long timestamp = (cursor.getLong(2) * 1000);

Android update sqlite table

I have written Update table using dbAdapter.
public void loadDownloadData() {
SoapPrimitive responsePrimitiveData;
//Loop Table list
for (int i = 0; i < tablesName.size(); i++) {
try {
responsePrimitiveData = soapPrimitiveData(tablesName.get(i));
if (responsePrimitiveData != null) {
try {
String result = responsePrimitiveData.toString();
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("Table1");
int max = array.length();
// Loop each table data
for (int j = 0; j < max; j++) {
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
StringBuilder strFields = new StringBuilder();
StringBuilder strValues = new StringBuilder();
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
//getting the Json name, values in separate string array
for (int k = 0; k < names.length(); k++) {
String name = names.getString(k);
strToFields[k] = names.getString(k);
String strVal;
if(obj.getString(name)== null){
strVal="";
strToFieldsVal[k]="";
}else{
if(obj.getString(name).equals(" ")){
strVal="";
strToFieldsVal[k]="";
}else{
String tmp1 = obj.getString(name).replaceAll("\\s+", " ");
String tmp = tmp1.replaceAll("\\s+", " ");
strVal =tmp.replaceAll("\\s+", " ");
strToFieldsVal[k]=strVal;
}
}
strFields.append(name + ",");
strValues.append(strVal+",");
} //end of json for loop
strFields.deleteCharAt(strFields.length() - 1);
strValues.deleteCharAt(strValues.length() - 1);
if(getTableUpdateType(tablesName.get(i)).equals("1")){
String actualtable = getAndroidTablename(tablesName.get(i));
if(isTableRecords(tablesName.get(i))){
String[] strWhereField = getTablePrimaryKey(tablesName.get(i),strBusinessUnit);
String[] strWhereFieldVal = new String[strWhereField.length];
StringBuilder whereFields = new StringBuilder();
for (int a = 0; a < strWhereField.length; a++) {
strWhereFieldVal[a] = obj.getString(strWhereField[a]);
whereFields.append(strWhereField[a] + "= ? and ");
}
whereFields.delete(whereFields.length() - 4, whereFields.length());
updateTableRecords(actualtable, strToFields, strToFieldsVal,whereFields.toString() ,strWhereFieldVal);
}else{
insertTableRecords(actualtable, strToFields, strToFieldsVal);
}
}else if(getTableUpdateType(tablesName.get(i)).equals("2")){
}else if(getTableUpdateType(tablesName.get(i)).equals("3")){
}else{
}
}//end of each table data
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
and I called like update method:
public void updateTableRecords(String strTableName, String[] strToFields, String[] strValues,String strWhereField ,String[] strWhereFieldVal){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.updateRecordsInDB(strTableName, initialValues, strWhereField, strWhereFieldVal);
System.out.println( " -- n--- " + n);
Toast.makeText(DownlaodTableActivity.this, n+" rows updated", Toast.LENGTH_SHORT).show();
}
I want to generate update statement dynamic way. From These code I put Where part also.But I did not generate where clause.
see :
UPDATE strTableName SET ExecutiveCode=?, FreeIssuePrefix=?, DisPaySchedulePrefix=?, NextFreeIssueNo=?, NextReturnNo=?, UploadedType=?, DisNextFOCNo=?, DisNextFreeIssueNo=?
Please help me How to give the Where clase(Here I gave String & arguments as string array)
Thanks in advance...
try like this
dbAdapter.updateRecordsInDB(strTableName, initialValues,""+whereField+"='"+whereFieldValue+"'",null);
if your whereField field's type is number then don't use ''
If you have to compare with multiple values use
String where="";
for(int i=0;i<strWhereField.length();i++)
{
where=where+whereField[i]+"='"+strWhereFieldValue[i]+"'"
if(i<(strWhereField.length()-1)) where=where+" and"
}
dbAdapter.updateRecordsInDB(strTableName, initialValues,where,null);

Categories

Resources