empty crash file when using ACRA - android

i am using the code below to generate a crash file, the file is created at parse.com but it is empty.
any idea why?
Another problem is that "ACRA.DEFAULT_REPORT_FIELDS;" has an error, default report fields is not available.
public class LocalSender implements ReportSender {
private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>() ;
private FileOutputStream crashReport = null;
private Context ctx;
public LocalSender(Context ct) {
ctx = ct;
}
public void send(CrashReportData report) throws ReportSenderException {
final Map<String, String> finalReport = remap(report);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
Log.i("hcsh","Report send");
try {
Set set = finalReport.entrySet();
Iterator i = set.iterator();
String tmp;
while (i.hasNext()) {
Map.Entry<String,String> me = (Map.Entry) i.next();
tmp = "[" + me.getKey() + "]=" + me.getValue();
buf.write(tmp.getBytes());
}
ParseFile myFile = new ParseFile("crash.txt", buf.toByteArray());
myFile.save();
ParseObject jobApplication = new ParseObject("AppCrash");
jobApplication.put("MyCrash", "app name");
jobApplication.put("applicantResumeFile", myFile);
try {
jobApplication.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (FileNotFoundException e) {
Log.e("TAG", "IO ERROR",e);
}
catch (IOException e) {
Log.e("TAG", "IO ERROR",e);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Map<String, String> remap(Map<ReportField, String> report) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final Map<String, String> finalReport = new HashMap<String, String>(
report.size());
for (ReportField field : fields) {
if (mMapping == null || mMapping.get(field) == null) {
finalReport.put(field.toString(), report.get(field));
} else {
finalReport.put(mMapping.get(field), report.get(field));
}
}
return finalReport;
}
}

There is no such constant as ACRA.DEFAULT_REPORT_FIELDS. You are looking for ACRAConstants.DEFAULT_REPORT_FIELDS

ACRA.DEFAULT_REPORT_FIELDS constant value is in acra-4.3.0 version ...
if you are using acra-4.5.0 version ACRA you will get this error "DEFAULT_REPORT_FIELDS cannot be resolved or is not a field" .
try to use acra-4.5.0 version and then use following code
// Extract the required data out of the crash report.
String reportBody = createCrashReport(report);
/** Extract the required data out of the crash report. */
private String createCrashReport(CrashReportData report) {
// I've extracted only basic information.
// U can add loads more data using the enum ReportField. See below.
StringBuilder body = new StringBuilder();
body.append(
"Device : " + report.getProperty(ReportField.BRAND) + "-"
+ report.getProperty(ReportField.PHONE_MODEL))
.append("\n")
.append("Android Version :"
+ report.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("App Version : "
+ report.getProperty(ReportField.APP_VERSION_CODE))
.append("\n")
.append("STACK TRACE : \n"
+ report.getProperty(ReportField.STACK_TRACE));
return body.toString();
}
Don't use following code
////////////////////////
final String reportBody = buildBody(arg0);
private String buildBody(CrashReportData errorContent) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
// fields = ACRA.DEFAULT_MAIL_REPORT_FIELDS;
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final StringBuilder builder = new StringBuilder();
for (ReportField field : fields) {
builder.append(field.toString()).append("=");
builder.append(errorContent.get(field));
builder.append('\n');
}
return builder.toString();
}
Happy Coding....

Related

PayUBiz - Android: Transaction failed due to incorrectly calculated hash parameter

I'm trying to integrate PayUBiz in my Android Application. It is working fine in test environment.
What I'm using is like below.
Test Merchant Key / Salt : gtKFFx / eCwWELxi
Our server URL for generating hash: http://xx.xxx.xx.xx/payment/getPaymentData
Success URL - Failure URL: https://payu.herokuapp.com/success - https://payu.herokuapp.com/failure
I'm passing orderId and userId in our server URL for generating hash.
I can go to the screen where I can enter test card details. But after entering card details I'm getting "Error Reason: Transaction failed due to incorrectly calculated hash parameter"
Whole error screen-shots are below.
What I done in code is like below.
ActivityConfirmOrder.java
private String merchantKey = "gtKFFx";
private String merchantSalt = "eCwWELxi";
private String userCredentials = merchantKey + ":" + "maulik#techniche.co";
private PayuConfig payuConfig;
private PaymentParams mPaymentParams;
In onCreate I put
// PayUBiz initialisation
Payu.setInstance(this);
Below methods are not in onCreate method.
private void makePayment() {
int environment = PayuConstants.STAGING_ENV;
sharedPref = new UserSharedPref(this);
mPaymentParams = new PaymentParams();
mPaymentParams.setKey(merchantKey);
mPaymentParams.setAmount(String.valueOf(totalPrice));
mPaymentParams.setProductInfo("product_info");
mPaymentParams.setFirstName("Maulik");
mPaymentParams.setEmail("maulik#techniche.co");
mPaymentParams.setTxnId(OrderNumber);
mPaymentParams.setSurl("https://payu.herokuapp.com/success");
mPaymentParams.setFurl("https://payu.herokuapp.com/failure");
mPaymentParams.setUdf1("");
mPaymentParams.setUdf2("");
mPaymentParams.setUdf3("");
mPaymentParams.setUdf4("");
mPaymentParams.setUdf5("");
mPaymentParams.setUserCredentials(userCredentials);
payuConfig = new PayuConfig();
payuConfig.setEnvironment(environment);
generatePayUHashFromServer(mPaymentParams);
}
private void generatePayUHashFromServer(PaymentParams mPaymentParams) {
StringBuffer postParamsBuffer = new StringBuffer();
postParamsBuffer.append(concatParams(PayuConstants.KEY, mPaymentParams.getKey()));
postParamsBuffer.append(concatParams(PayuConstants.AMOUNT, mPaymentParams.getAmount()));
postParamsBuffer.append(concatParams(PayuConstants.TXNID, mPaymentParams.getTxnId()));
postParamsBuffer.append(concatParams(PayuConstants.EMAIL, null == mPaymentParams.getEmail() ? "" : mPaymentParams.getEmail()));
postParamsBuffer.append(concatParams(PayuConstants.PRODUCT_INFO, mPaymentParams.getProductInfo()));
postParamsBuffer.append(concatParams(PayuConstants.FIRST_NAME, null == mPaymentParams.getFirstName() ? "" : mPaymentParams.getFirstName()));
postParamsBuffer.append(concatParams(PayuConstants.UDF1, mPaymentParams.getUdf1() == null ? "" : mPaymentParams.getUdf1()));
postParamsBuffer.append(concatParams(PayuConstants.UDF2, mPaymentParams.getUdf2() == null ? "" : mPaymentParams.getUdf2()));
postParamsBuffer.append(concatParams(PayuConstants.UDF3, mPaymentParams.getUdf3() == null ? "" : mPaymentParams.getUdf3()));
postParamsBuffer.append(concatParams(PayuConstants.UDF4, mPaymentParams.getUdf4() == null ? "" : mPaymentParams.getUdf4()));
postParamsBuffer.append(concatParams(PayuConstants.UDF5, mPaymentParams.getUdf5() == null ? "" : mPaymentParams.getUdf5()));
postParamsBuffer.append(concatParams(PayuConstants.USER_CREDENTIALS, mPaymentParams.getUserCredentials() == null ? PayuConstants.DEFAULT : mPaymentParams.getUserCredentials()));
if (null != mPaymentParams.getOfferKey())
postParamsBuffer.append(concatParams(PayuConstants.OFFER_KEY, mPaymentParams.getOfferKey()));
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("orderId", orderId);
jsonObject.put("userId", sharedPref.getUserId());
} catch (JSONException e) {
e.printStackTrace();
}
// String postParams = jsonObject.toString();
// String postParams = postParamsBuffer.charAt(postParamsBuffer.length() - 1) == '&' ? postParamsBuffer.substring(0, postParamsBuffer.length() - 1).toString() : postParamsBuffer.toString();
GetHashesFromServerTask getHashesFromServerTask = new GetHashesFromServerTask();
getHashesFromServerTask.execute(jsonObject);
}
protected String concatParams(String key, String value) {
return key + "=" + value + "&";
}
private class GetHashesFromServerTask extends AsyncTask<JSONObject, String, PayuHashes> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(ActivityConfirmOrder.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected PayuHashes doInBackground(JSONObject... postParams) {
PayuHashes payuHashes = new PayuHashes();
try {
URL url = new URL(AppConstant.BASE_URL + "/payment/getPaymentData");
String postParam = postParams[0].toString();
byte[] postParamsByte = postParam.getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", String.valueOf(postParamsByte.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postParamsByte);
InputStream responseInputStream = conn.getInputStream();
StringBuffer responseStringBuffer = new StringBuffer();
byte[] byteContainer = new byte[1024];
for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
responseStringBuffer.append(new String(byteContainer, 0, i));
}
JSONObject response = new JSONObject(responseStringBuffer.toString());
Iterator<String> payuHashIterator = response.keys();
while (payuHashIterator.hasNext()) {
String key = payuHashIterator.next();
switch (key) {
case "payment_hash":
payuHashes.setPaymentHash(response.getString(key));
break;
case "vas_for_mobile_sdk_hash":
payuHashes.setVasForMobileSdkHash(response.getString(key));
break;
case "payment_related_details_for_mobile_sdk_hash":
payuHashes.setPaymentRelatedDetailsForMobileSdkHash(response.getString(key));
break;
case "delete_user_card_hash":
payuHashes.setDeleteCardHash(response.getString(key));
break;
case "get_user_cards_hash":
payuHashes.setStoredCardsHash(response.getString(key));
break;
case "edit_user_card_hash":
payuHashes.setEditCardHash(response.getString(key));
break;
case "save_user_card_hash":
payuHashes.setSaveCardHash(response.getString(key));
break;
case "check_offer_status_hash":
payuHashes.setCheckOfferStatusHash(response.getString(key));
break;
default:
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return payuHashes;
}
#Override
protected void onPostExecute(PayuHashes payuHashes) {
super.onPostExecute(payuHashes);
progressDialog.dismiss();
launchSdkUI(payuHashes);
}
}
public void launchSdkUI(PayuHashes payuHashes) {
Intent intent = new Intent(ActivityConfirmOrder.this, PayUBaseActivity.class);
intent.putExtra(PayuConstants.PAYU_CONFIG, payuConfig);
intent.putExtra(PayuConstants.PAYMENT_PARAMS, mPaymentParams);
intent.putExtra(PayuConstants.PAYU_HASHES, payuHashes);
intent.putExtra(PayuConstants.SALT, merchantSalt);
intent.putExtra("PaymentType", "PAYU");
startActivityForResult(intent, PayuConstants.PAYU_REQUEST_CODE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PayuConstants.PAYU_REQUEST_CODE) {
if (data != null) {
Log.e("PayuResponse", data.getStringExtra("payu_response"));
if (!data.getStringExtra("payu_response").equals("")) {
PayUSuccessRequest request = new PayUSuccessRequest(ActivityConfirmOrder.this);
try {
JSONObject paySuccessRes = new JSONObject(data.getStringExtra("payu_response"));
request.setPayUSuccessResJsonObject(paySuccessRes);
} catch (JSONException e) {
e.printStackTrace();
}
new AsyncTaskExecutor<A2BRequest, Void, A2BResponse>().execute(
new RequestProcessor(ActivityConfirmOrder.this, ActivityConfirmOrder.this, true), request);
}
try {
JSONObject responseObject = new JSONObject(data.getStringExtra("payu_response"));
if (responseObject != null) {
if (responseObject.optString("status").equalsIgnoreCase("failure")) {
Toast.makeText(mContext, "Failure..", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ActivityConfirmOrder.this, ActivityOrderFailure.class);
ActivityConfirmOrder.this.startActivity(intent);
} else {
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} else {
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} else {
//Toast.makeText(getActivity(), getString(R.string.could_not_receive_data), Toast.LENGTH_LONG).show();
}
} else {
Log.e("Log MSg", "No Payu SDK Request Code");
}
}
I found the solution but I haven't applied yet.
I emailed to customer support of PayUBiz and they responded well.
Email IDs: tech#payu.in / mobile-integration#payu.in
As I mentioned in question I was using TEST ENVIRONMENT and TEST CREDENTIALS and OUR SERVER URL for generating hash, this is the place where I was wrong. It won't work if you are using TEST CREDENTIALS and YOUR SERVER URL for hash.
In TEST ENVIRONMENT use all TESTING RELATED stuff and for LIVE ENVIRONMENT use all LIVE RELATED stuff.
I replaced OUR SERVER URL with PayUBiz's TEST URL https://payu.herokuapp.com/get_hash and it's working.

Why were the three error log files created?

I use the following code to catch a global uncaught error, the test code System.out.println(s.equals("any string")); will cause an error.
In my mind, one error log file will be created, but in fact, the three error log files were created with same content, what problem are there in my code?
BTW, I test the code in Android 4.0, only one error log file was generated! but when it run under Android 5.0, three error log files was generated!
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println(s.equals("any string"));
}
}
CrashApplication.java
public class CrashApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
}
}
CrashHandler.java
public class CrashHandler implements UncaughtExceptionHandler {
public static final String TAG = "CrashHandler";
private Thread.UncaughtExceptionHandler mDefaultHandler;
private static CrashHandler INSTANCE = new CrashHandler();
private Context mContext;
private Map<String, String> infos = new HashMap<String, String>();
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
private CrashHandler() {
}
public static synchronized CrashHandler getInstance() {
return INSTANCE;
}
public void init(Context context) {
mContext = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
#Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
#Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "Sorry.", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
collectDeviceInfo(mContext);
saveCrashInfo2File(ex);
return true;
}
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".txt";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory() + "/MyCrash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}
There are different log files in android: Error,Debug,Verbose etc.
And therefore there are different qualifiers for them and they are Log.e,Log.d,Log.v etc. Two of them you are using e and d qualifiers but I don't know about third

how to convert my java object to json and save it in sd card

I don't know how to do after this to convert my Java to JSON with Jackson
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper mapper = new ObjectMapper();
Book b = new Book();
ArrayList<Book> listBook = new ArrayList<Book>();
listBook.add(b);
b = new Book();
b.setName("exam");
b.setFileName("res/raw/exam.txt");
b.setCate(0); //4 categories here
b.setSoundFileName("res/raw/exams.mp3");
b.setTranFileName("res/raw/examt.txt");
listBook.add(b);
b = new Book();
b.setName("test");
b.setCate(0);
b.setFileName("res/raw/test.txt");
b.setSoundFileName("res/raw/tests.mp3")
b.setTranFileName("res/raw/textt.txt");
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(listBook);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ttt", "show ans : "+jsonString);
How do I do next to write this to my SD card?
as user Zain has told, Gson is more convenient to use, However, assuming that you are getting the Json string from this line:
jsonString = mapper.writeValueAsString(listBook);
Then use this method to write the string to a file in sdcard.
public static void writeStringToFile(String p_string, String p_fileName)
{
FileOutputStream m_stream = null;
try
{
m_stream = new FileOutputStream(p_fileName);
m_stream.write(p_string.getBytes());
m_stream.flush();
}
catch (Throwable m_th)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_th);
}
finally
{
if (m_stream != null)
{
try
{
m_stream.close();
}
catch (Throwable m_e)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_e);
}
m_stream = null;
}
}
}

How get call log history using Cordova CallLog plugin for Android

My project is I have to get the calllog history from phone and send to the server.I don't get the calllog history by using calllog plugin, but I am new to cordova I don't know how to get the values in the script file.Can anybody pls help me..I have posted my code here.
My CallLogPlugin.java file
public class CallLogPlugin extends CordovaPlugin {
private static final String ACTION_LIST = "list";
private static final String ACTION_CONTACT = "contact";
private static final String ACTION_SHOW = "show";
private static final String TAG = "CallLogPlugin";
#Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
Log.d(TAG, "Plugin Called");
if (ACTION_CONTACT.equals(action)) {
contact(args, callbackContext);
} else if (ACTION_SHOW.equals(action)) {
show(args, callbackContext);
} else if (ACTION_LIST.equals(action)) {
list(args, callbackContext);
} else {
Log.d(TAG, "Invalid action : " + action + " passed");
callbackContext.sendPluginResult(new PluginResult(Status.INVALID_ACTION));
}
return true;
}
private void show(final JSONArray args, final CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
PluginResult result;
try {
String phoneNumber = args.getString(0);
viewContact(phoneNumber);
result = new PluginResult(Status.OK);
} catch (JSONException e) {
Log.d(TAG, "Got JSON Exception " + e.getMessage());
result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
} catch (Exception e) {
Log.d(TAG, "Got Exception " + e.getMessage());
result = new PluginResult(Status.ERROR, e.getMessage());
}
callbackContext.sendPluginResult(result);
}
});
}
private void contact(final JSONArray args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
PluginResult result;
try {
final String phoneNumber = args.getString(0);
String contactInfo = getContactNameFromNumber(phoneNumber);
Log.d(TAG, "Returning " + contactInfo);
result = new PluginResult(Status.OK, contactInfo);
} catch (JSONException e) {
Log.d(TAG, "Got JSON Exception " + e.getMessage());
result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
}
callbackContext.sendPluginResult(result);
}
});
}
private void list(final JSONArray args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
PluginResult result;
try {
String limiter = null;
if (!args.isNull(0)) {
// make number positive in case caller give negative days
int days = Math.abs(Integer.valueOf(args.getString(0)));
Log.d(TAG, "Days is: " + days);
//turn this into a date
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_YEAR, -days);
Date limitDate = calendar.getTime();
limiter = String.valueOf(limitDate.getTime());
}
//now do required search
JSONObject callLog = getCallLog(limiter);
Log.d(TAG, "Returning " + callLog.toString());
result = new PluginResult(Status.OK, callLog);
} catch (JSONException e) {
Log.d(TAG, "Got JSON Exception " + e.getMessage());
result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
} catch (NumberFormatException e) {
Log.d(TAG, "Got NumberFormatException " + e.getMessage());
result = new PluginResult(Status.ERROR, "Non integer passed to list");
} catch (Exception e) {
Log.d(TAG, "Got Exception " + e.getMessage());
result = new PluginResult(Status.ERROR, e.getMessage());
}
callbackContext.sendPluginResult(result);
}
});
}
private void viewContact(String phoneNumber) {
Intent i = new Intent(Intents.SHOW_OR_CREATE_CONTACT,
Uri.parse(String.format("tel: %s", phoneNumber)));
this.cordova.getActivity().startActivity(i);
}
private JSONObject getCallLog(String limiter) throws JSONException {
JSONObject callLog = new JSONObject();
String[] strFields = {
android.provider.CallLog.Calls.DATE,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.TYPE,
android.provider.CallLog.Calls.DURATION,
android.provider.CallLog.Calls.NEW,
android.provider.CallLog.Calls.CACHED_NAME,
android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
android.provider.CallLog.Calls.CACHED_NUMBER_LABEL };
try {
Cursor callLogCursor = this.cordova.getActivity().getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI,
strFields,
limiter == null ? null : android.provider.CallLog.Calls.DATE + ">?",
limiter == null ? null : new String[] {limiter},
android.provider.CallLog.Calls.DEFAULT_SORT_ORDER);
int callCount = callLogCursor.getCount();
if (callCount > 0) {
JSONObject callLogItem = new JSONObject();
JSONArray callLogItems = new JSONArray();
callLogCursor.moveToFirst();
do {
callLogItem.put("date", callLogCursor.getLong(0));
callLogItem.put("number", callLogCursor.getString(1));
callLogItem.put("type", callLogCursor.getInt(2));
callLogItem.put("duration", callLogCursor.getLong(3));
callLogItem.put("new", callLogCursor.getInt(4));
callLogItem.put("cachedName", callLogCursor.getString(5));
callLogItem.put("cachedNumberType", callLogCursor.getInt(6));
callLogItem.put("cachedNumberLabel", callLogCursor.getInt(7));
//callLogItem.put("name", getContactNameFromNumber(callLogCursor.getString(1))); //grab name too
callLogItems.put(callLogItem);
callLogItem = new JSONObject();
} while (callLogCursor.moveToNext());
callLog.put("rows", callLogItems);
}
callLogCursor.close();
} catch (Exception e) {
Log.d("CallLog_Plugin", " ERROR : SQL to get cursor: ERROR " + e.getMessage());
}
return callLog;
}
private String getContactNameFromNumber(String number) {
// define the columns I want the query to return
String[] projection = new String[]{PhoneLookup.DISPLAY_NAME};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor c = this.cordova.getActivity().getContentResolver().query(contactUri, projection, null, null, null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(PhoneLookup.DISPLAY_NAME));
c.deactivate();
return name;
}
// return the original number if no match was found
return number;
}
}
My CallLog.js file
function CallLog() {
}
CallLog.prototype.list = function (period, successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "CallLog", "list", [period]);
};
CallLog.prototype.contact =
function (phoneNumber, successCallback,errorCallback) {
cordova.exec(successCallback, errorCallback, "CallLog", "contact", [phoneNumber]);
};
CallLog.prototype.show = function (phoneNumber, successCallback, errorCallback) {
cordova.exec(successCallback, errorCallback, "CallLog", "show", [phoneNumber]);
};
CallLog.install = function () {
if (!window.plugins) {
window.plugins = {};
}
window.plugins.calllog = new CallLog();
return window.plugins.calllog;
};
cordova.addConstructor(CallLog.install);
My index.js file
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
var f = window.plugins.calllog.list();
alert(f);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
But i don't get any result. Please help me.
Thanks
I'm not trying to solve all your problem, just want to throw some light.
Your Java seems fine, but check https://wiki.apache.org/cordova/DeprecationPolicy
and see the solution offered for such deprecation code on the next url link. for your Javascript.
deprecation: window.addPlugin and window.plugins will be removed
http://simonmacdonald.blogspot.com.es/2012/08/so-you-wanna-write-phonegap-200-android.html
Your Code:
window.plugins.calllog = new CallLog();
return window.plugins.calllog;
The solution provided is something like:
module.exports = new CallLog();
Here is a plugin I have made
https://www.npmjs.com/package/callsplugin
you basically have to write the command
cordova plugin add callsplugin
and follow the instruction you find in the project site
since retrieving calls is not a quick task I have used Thread Pool to avoid blocking the application. You can find the whole code here https://github.com/asindico/callsplugin

How to Pass SQLite Table values row wise into JSON?

Hi I pass the Data base values into webservices. but it passing only resent entry valules only. I need to pass all rows one by one into JSON.
Can any one help me with sample code.
SQLite in DB
Cursor cursor;
cursor = myDataBase.rawQuery(" SELECT " + VENDORID + " FROM " + VENDORINFO_TABLE
+ " WHERE " + CATEGORYID + " = " + id,null);
while (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndex(VENDORID));
// your JSON put Code
JSONObject jsMain = new JSONObject();
try {
jsMain.put("email", id);
return jsMain.toString();
} catch (JSONException e) {
e.printStackTrace();
return "";
}
}
cursor.close();
check below code try this way. this is just advice for you.
Cursor cus = db.selectAll_delete();
JSONObject jon1 = new JSONObject();
JSONArray jaa = new JSONArray();
int i = 0;
try {
if (cus.moveToFirst()) {
do {
String a = cus.getString(1);
// Toast.makeText(this, ""+ a,
// Toast.LENGTH_LONG).show();
JSONObject job_get = getData_b(a);
jaa.put(i, job_get);
i++;
} while (cus.moveToNext());
}
jon1.accumulate("details", jaa);
} catch (Exception e) {
// TODO: handle exception
}
if (cus != null && !cus.isClosed()) {
cus.close();
}
String js = jon1.toString();
send_to_server(js);
Log.d("test json", "" + js);
method getData_b();
private JSONObject getData_b(String a) {
// TODO Auto-generated method stub
Cursor cus = db.fetchRow(a);
JSONObject job = new JSONObject();
try {
if (cus.moveToFirst()) {
do {
job.put("B", cus.getInt(1));
job.put("I", cus.getString(2));
job.put("O", cus.getString(3));
job.put("D", cus.getString(4));
job.put("D u", cus.getString(5));
job.put("L", cus.getString(6));
job.put("B", cus.getString(7));
job.put("A", cus.getString(8));
job.put("K", cus.getString(9));
job.put("A", cus.getString(10));
job.put("Time", cus.getString(11));
job.put("Upd", cus.getString(12));
job.put("Deleted", cus.getString(13));
} while (cus.moveToNext());
}
} catch (Exception e) {
// TODO: handle exception
}
return job;
}

Categories

Resources