In my Android application I have passed the sqlite data into remote mysql database using JSON over AsyncHttp protocol.
Now I want the data from Mysql database to SQLite database so that from server I am fetching the data and converting it to JSON.
Since server has many rows of data I need to fetch only my mobiles sqlite data so that I need to pass the variables and check if the data is mine or not rather than fetching all the users data.
How to pass the variables in the url so that while fetching only I want to search my users data and insert them to SQLITE database.
Here is my code
public void syncMySQLDBSQLite(){
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
// Make Http call to getusers.php
client.post("http://10.0.2.2/tafapps/getuser.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Hide ProgressBar
prgDialog.hide();
// Update SQLite DB with response sent by getusers.php
updateSQLite(response);
}
// When error occured
#Override
public void onFailure(int statusCode, Throwable error, String content) {
// TODO Auto-generated method stub
// Hide ProgressBar
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
public void updateSQLite(String response){
ArrayList<HashMap<String, String>> usersynclist;
usersynclist = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
Toast.makeText(getApplicationContext(), response, 5000).show();
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("userId"));
System.out.println(obj.get("userName"));
db = this.openOrCreateDatabase("Hangman", MODE_PRIVATE, null);
// String id = obj.get("userId").toString();
name = obj.get("userName").toString();
email = obj.get("userEmail").toString();
phn = obj.get("userPhnum").toString();
plyd = obj.get("userPlayed").toString();
crct = obj.get("userCorrect").toString();
//Toast.makeText(getApplicationContext(), email, 5000).show();
db.execSQL("insert into scores(userName,userEmail,userPhnum,userPlayed,userCorrect)values('"+name+"','"+email+"','"+phn+"','"+plyd+"','"+crct+"')");
}
//Toast.makeText(getApplicationContext(), ""+queryValues, 5000).show();
// Inform Remote MySQL DB about the completion of Sync activity by passing Sync status of Users
updateMySQLSyncSts(gson.toJson(usersynclist));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use HTTP GET or POST requests.
GET example with parametrs:
http://example.com/tafapps/getuser.php?user=user1&user_age=21
In POST request this parametrs will be not visible inside URL and encoded instead inside request body.
You can use the parse_url() and parse_str() for parsing:
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['user'];
Or even better as I knew:
$user = $_GET['user']
PHP Manual: Predefined _GET variable
Related
I am writing an Android application that pulls JSON data from an SQL db.
In my Async Task class, I receive a JSON string from an HTTP request and I assign it to a JSONObject. This string contains various data, including an array of coordinates which I need. After that, I do obj.getJSONArray("coordinates"); As soon as I do that, my application throws an exception:
org.json.JSONObject cannot be converted to JSONArray in android
I am following this post's approach to solve my issues but with no luck:
org.json.JSONObject cannot be converted to JSONArray in android
I feel like I need to iterate over my JSON string until I see that array. I will post the string data below.
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(address);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
JSONArray deviceJsonArray = obj.getJSONArray("coordinates"); //ERROR OCCURS HERE!
// looping through All Devices
for (int i = 0; i < deviceJsonArray.length(); i++) {
JSONObject json = deviceJsonArray.getJSONObject(i);
//String DeviceID = c.getString("id");
// longitude = json.getDouble("longitude");
// latitude = json.getDouble("latitude");
Device device = new Device();
device.setName(receivedDeviceName);
//Adding the information to the array.
coordinatesArray.add(device);
}
//Log.e(TAG, "arraylist: " + coordinatesArray);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
JSON string value:
{"data":{"type":"gps","total_distance":18,"coordinates":[{"latitude":49.169209,"longitude":-122.990952,"time":"12:02:38 AM"},{"latitude":49.16922,"longitude":-122.990959,"time":"2:42:33 PM"},{"latitude":49.1693,"longitude":-122.988098,"time":"5:16:33 PM"},{"latitude":49.170979,"longitude":-122.968239,"time":"5:18:33 PM"},{"latitude":49.174992,"longitude":-122.962502,"time":"5:20:33 PM"},{"latitude":49.17688,"longitude":-122.95768,"time":"5:22:33 PM"},{"latitude":49.182232,"longitude":-122.960297,"time":"5:24:33 PM"},{"latitude":49.18581,"longitude":-122.950813,"time":"5:26:33 PM"},{"latitude":49.188869,"longitude":-122.945969,"time":"5:28:33 PM"},{"latitude":49.197689,"longitude":-122.948502,"time":"5:30:33 PM"},{"latitude":49.20216,"longitude":-122.947418,"time":"5:32:33 PM"},{"latitude":49.2071,"longitude":-122.949593,"time":"5:34:33 PM"},{"latitude":49.213051,"longitude":-122.938522,"time":"5:36:33 PM"},{"latitude":49.215462,"longitude":-122.93399,"time":"5:38:33 PM"},{"latitude":49.216381,"longitude":-122.932297,"time":"5:40:33 PM"},{"latitude":49.218769,"longitude":-122.92791,"time":"5:42:33 PM"},{"latitude":49.221062,"longitude":-122.923653,"time":"5:44:33 PM"},{"latitude":49.227119,"longitude":-122.912392,"time":"5:46:33 PM"},{"latitude":49.234489,"longitude":-122.89872,"time":"5:48:33 PM"},{"latitude":49.235699,"longitude":-122.894608,"time":"5:50:33 PM"},{"latitude":49.241928,"longitude":-122.89257,"time":"5:52:33 PM"},{"latitude":49.241871,"longitude":-122.89016,"time":"6:02:33 PM"}]}}
Could someone see what I am doing wrong or recommend a fix please?
Try this instead:
JSONObject obj = new JSONObject(jsonStr);
JSONObject objData = obj.getJSONObject("data");
JSONArray deviceJsonArray = objData.getJSONArray("coordinates");
The "coordinates" JSONArray is one element deeper in your JSON structure
Why am I getting this error and how can I fix it? I have 43 items in my ListView, where is index 4338 coming from?
I looked at the solution here : JSONArray Exception : Index 50 out of range [0..50). Is there any limit on JsonArray and modified my code accordingly but still getting the errors.
These errors come up in logcat - my ListView loads eventually, after about 20 seconds which seems way too long - but only after this error displays in Logcat after repeating hundreds of times - index 3829 all the way up to 4338 (skipping a few along the way).
Here's my code :
public class PopulistoListView extends AppCompatActivity {
// this is the php file name where to select from.
// we will post the user's phone number into Php and get the matching user_id
private static final String SelectUserReviews_URL = "http://www.example.com/SelectUserReviews.php";
//we are posting phoneNoofUser, the key is phonenumberofuser, which we see in php
public static final String KEY_PHONENUMBER_USER = "phonenumberofuser";
private ProgressDialog pDialog;
private List<Review> reviewList = new ArrayList<Review>();
private ListView listView;
private CustomPopulistoListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_contacts);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomPopulistoListAdapter(this, reviewList);
listView.setAdapter(adapter);
//get the phone number value from shared preferences file instead
//of from the VerifiedUserPhoneNumber class because we might not
//be coming from that class, for example on Edit, New etc. The phone
//number needs to be posted for this listview to load properly.
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
final String phoneNoofUser = sharedPreferences.getString("phonenumberofuser", "");
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
//post the phone number of the logged in user to SelectUserReviews.php and from that
//get the logged in user's reviews
StringRequest stringRequest = new StringRequest(Request.Method.POST, SelectUserReviews_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hide the 'loading' box when the page loads
hidePDialog();
//toast the response of SelectUserReviews.php, which has been converted to a
//JSON array in the Php file with JSON encode
Toast.makeText(PopulistoListView.this, response, Toast.LENGTH_LONG).show();
//break up the JSON Array into parts
//we need to sort out this error we keep getting in logcat
final int numberOfItemsInResp = response.length();
for (int i = 0; i < numberOfItemsInResp; i++) {
try {
JSONArray responseObject = new JSONArray(response);
JSONObject obj = responseObject.getJSONObject(i);
Review review = new Review();
review.setCategory(obj.getString("category"));
review.setName(obj.getString("name"));
review.setPhone(obj.getString("phone"));
review.setComment(obj.getString("comment"));
//we are getting the review id so we can pull extra needed info, like Address etc
review.setReviewid(obj.getString("reviewid"));
// Toast.makeText(PopulistoListView.this, responseObject.toString(), Toast.LENGTH_LONG).show();
reviewList.add(review);
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PopulistoListView.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
//post info to php
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//phoneNoofUser is the value we get from Android, the user's phonenumber.
//the key is "phonenumberofuser". When we see "phonenumberofuser" in our php,
//put in phoneNoofUser
params.put(KEY_PHONENUMBER_USER, phoneNoofUser);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
In logcat I get the error several times :
unexpected JSON exception
org.json.JSONException: Index 4001 out of range [0..43)
at org.json.JSONArray.get(JSONArray.java:282)
at org.json.JSONArray.getJSONObject(JSONArray.java:510)
at PopulistoListView$1.onResponse(PopulistoListView.java:96)
at PopulistoListView$1.onResponse(PopulistoListView.java:81)
Line 96 is :
JSONObject obj = responseObject.getJSONObject(i);
Line 81 is :
new Response.Listener<String>() {
Thanks for any help.
Your for loop is iterating over this range: (int i = 0; i < numberOfItemsInResp; i++), but numberOfItemsInResp is the length of a String object.
Without getting too deep into it (really just based off of the other code you've written), I think you'd be better off with this:
JSONArray responseObject = new JSONArray(response);
for (int i = 0; i < responseObject.length(); i++) {
JSONObject obj = responseObject.getJSONObject(i);
...
}
The cause of error in line 81 is that your phoneNoofuser is incorrect, you have to modify it.
final String phoneNoofUser = sharedPreferences.getString("KEY_PHONENUMBER_USER", "");
I am Integrating Paytm PGSDK_V2.0 in my android app. I have read all documentation on Github. I have understand everything.but the problem is in its earlier SDK where we can simply generate checksum using Paytm Merchant object Like:
PaytmMerchant merchant=new PaytmMerchant("Checksum generation url","Checksum verification url");
and put this in Service Like this
Service.initialize(Order,merchant,null);
But in new SDK it change to
Service.initialize(Order,null);
So please help me how to generate checksum in new SDK
Paytm has change process to increase the security. now in PGSDK_V2.0 first you have to generate through calling the api Checksum Generation on your server side
Like this:
#Override
protected String doInBackground(String... params) {
url ="http://xxx.co.in/generateChecksum.php";
JSONParser jsonParser = new JSONParser(MainActivity.this);
param="ORDER_ID=" + orderId+
"&MID="+YourMID+
"&CUST_ID="+custId+
"&CHANNEL_ID=WAP&INDUSTRY_TYPE_ID=Retail110&WEBSITE=xxxwap&TXN_AMOUNT="+billAmt+"&CALLBACK_URL=http://xxx.co.in/verifyChecksum.php";
JSONObject jsonObject = jsonParser.makeHttpRequest(url,"POST",param);
Log.e("CheckSum result >>",jsonObject.toString());
if(jsonObject != null){
Log.d("CheckSum result >>",jsonObject.toString());
try {
CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
Log.e("CheckSum result >>",CHECKSUMHASH);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
now after getting CHECKSUM string in your onPostExecute initialize paytm Service object and do further process Like This:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.hide();
Service = PaytmPGService.getProductionService();
/*PaytmMerchant constructor takes two parameters
1) Checksum generation url
2) Checksum verification url
Merchant should replace the below values with his values*/
//below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values
Map<String, String> paramMap = new HashMap<String, String>();
//these are mandatory parameters
paramMap.put("ORDER_ID", orderId);
//MID provided by paytm
paramMap.put("MID", yourMID);
paramMap.put("CUST_ID", custId);
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
paramMap.put("WEBSITE", "xxxwap");
paramMap.put("TXN_AMOUNT",billAmt);
//
paramMap.put("CALLBACK_URL" ,"http://xxx.co.in/verifyChecksum.php");
paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order,null);
Service.startPaymentTransaction(ReviewBooking.this, true, true, new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
// Some UI Error Occurred in Payment Gateway Activity.
// // This may be due to initialization of views in
// Payment Gateway Activity or may be due to //
// initialization of webview. // Error Message details
// the error occurred.
}
#Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG", "Payment Transaction : " + inResponse);
String response=inResponse.getString("RESPMSG");
if (response.equals("Txn Successful."))
{
new ConfirmMerchent().execute();
}else
{
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "Payment Transaction response "+inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
// If network is not
// available, then this
// method gets called.
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
// This method gets called if client authentication
// failed. // Failure may be due to following reasons //
// 1. Server error or downtime. // 2. Server unable to
// generate checksum or checksum response is not in
// proper format. // 3. Server failed to authenticate
// that client. That is value of payt_STATUS is 2. //
// Error Message describes the reason for failure.
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed " + inErrorMessage);
Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
}
});
}
JsonParser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpURLConnection urlConnection = null;
// variable to hold context
private Context context;
// constructor
public JSONParser(Context context){
this.context=context;
}
public JSONObject makeHttpRequest(String url,String method,String params) {
// boolean isReachable =Config.isURLReachable(context);
// Making HTTP request
try {
String retSrc="";
char current = '0';
URL url1 = new URL(url);
// check for request method
HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
if (method == "POST") {
// request method is POST
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setFixedLengthStreamingMode(params.getBytes().length);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(params);
out.close();
}
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
byte[] bytes = new byte[10000];
StringBuilder x = new StringBuilder();
int numRead = 0;
while ((numRead = in.read(bytes)) >= 0) {
x.append(new String(bytes, 0, numRead));
}
retSrc=x.toString();
jObj = new JSONObject(retSrc);
} catch (Exception e) {
e.printStackTrace();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Connectivity issue. Please try again later.", Toast.LENGTH_LONG).show();
}
});
return null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return jObj;
}
}
and parameter values should be same both time.
Generating Checksum is quite easy.
Just get the Paytm App Checksum Kit from Github.
Extract the downloaded kit and put it in your server. If you are using a local server using xampp then the path would be c:/xampp/htdocs/paytm. I would recommend renaming the folder name to paytm or a small name.
Inside the kit there is a folder named lib. Inside this folder you will find a file named config_paytm.php, Open this file and put your Paytm Merchant Key here.
Now you can use the file generateChecksum.php to generate checksum.
Remember you need to pass every parameter that you will pass with transaction.
Below you can see a retrofit api code sample to send POST request to generateChecksum.php.
//this is the URL of the paytm folder that we added in the server
//make sure you are using your ip else it will not work
String BASE_URL = "http://192.168.101.1/paytm/";
#FormUrlEncoded
#POST("generateChecksum.php")
Call<Checksum> getChecksum(
#Field("MID") String mId,
#Field("ORDER_ID") String orderId,
#Field("CUST_ID") String custId,
#Field("CHANNEL_ID") String channelId,
#Field("TXN_AMOUNT") String txnAmount,
#Field("WEBSITE") String website,
#Field("CALLBACK_URL") String callbackUrl,
#Field("INDUSTRY_TYPE_ID") String industryTypeId
);
This part is very important you have to send all the parameters. And order_id should be unique everytime.
Source: Paytm Integration in Android Example
You need to pass only 8 param for checksum generation from SDK 2.0 and later. On Earlier version you need to pass email and mobile number too. Now there is no use of these param. First upload PHP file on your server and change the merchant key on config.php file inside lib folder. Now from android use can use retrofit or volley or httpconnection request to get checksum from your server. Here i am using Httpconnection (in this code JSONParse is a separate java class to call httpconnection). You can get reference on this link -http://www.blueappsoftware.in/android/blog/paytm-integration-sdk-2-1-android/
public class sendUserDetailTOServerdd extends AsyncTask<ArrayList<String>, Void, String> {
private ProgressDialog dialog = new ProgressDialog(checksum.this);
private String orderId , mid, custid, amt;
String url ="http://www.blueappsoftware.com/payment/payment_paytm/generateChecksum.php";
String varifyurl = // "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=<ORDER_ID>"; //
"https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp";//
String CHECKSUMHASH ="";
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
// initOrderId();
orderId ="KK100343"; // NOTE : order id must be unique
mid = "blueap01867059473586"; // CREATI42545355156573
custid = "KKCUST0342";
}
protected String doInBackground(ArrayList<String>... alldata) {
// String url ="http://xxx.co.in/generateChecksum.php";
JSONParser jsonParser = new JSONParser(checksum.this);
String param=
"MID="+mid+
"&ORDER_ID=" + orderId+
"&CUST_ID="+custid+
"&CHANNEL_ID=WEB&TXN_AMOUNT=100&WEBSITE=www.blueappsoftware.in"+"&CALLBACK_URL="+ varifyurl+"&INDUSTRY_TYPE_ID=Retail";
Log.e("checksum"," param string "+param );
JSONObject jsonObject = jsonParser.makeHttpRequest(url,"POST",param);
// yaha per checksum ke saht order id or status receive hoga..
Log.e("CheckSum result >>",jsonObject.toString());
if(jsonObject != null){
Log.e("CheckSum result >>",jsonObject.toString());
try {
CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
Log.e("CheckSum result >>",CHECKSUMHASH);
} catch (JSONException e) {
e.printStackTrace();
}
}
return CHECKSUMHASH;
}
#Override
protected void onPostExecute(String result) {
// jab run kroge to yaha checksum dekhega
///ab service ko call krna hai
Log.e(" setup acc "," signup result " + result);
if (dialog.isShowing()) {
dialog.dismiss();
}}
Step 2) now onPostExceute method you have checksum as result. It's time to call paytm staging service and call start transaction. Below is code to call paytm service
PaytmPGService Service =PaytmPGService.getStagingService();
// when app is ready to publish use production service
// PaytmPGService Service = PaytmPGService.getProductionService();
// now call paytm service here
//below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values
Map<String, String> paramMap = new HashMap<String, String>();
//these are mandatory parameters
// ye sari valeu same hon achaiye
//MID provided by paytm
paramMap.put("MID", mid);
paramMap.put("ORDER_ID", orderId);
paramMap.put("CUST_ID", custid);
paramMap.put("CHANNEL_ID", "WEB");
paramMap.put("TXN_AMOUNT", "100");
paramMap.put("WEBSITE", "www.blueappsoftware.in");
paramMap.put("CALLBACK_URL" ,varifyurl);
//paramMap.put( "EMAIL" , "abc#gmail.com"); // no need
// paramMap.put( "MOBILE_NO" , "9144040888"); // no need
paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
//paramMap.put("PAYMENT_TYPE_ID" ,"CC"); // no need
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
PaytmOrder Order = new PaytmOrder(paramMap);
Log.e("checksum ", paramMap.toString());
Service.initialize(Order,null);
// start payment service call here
Service.startPaymentTransaction(checksum.this, true, true, checksum.this );
what is new ConfirmMerchent().execute();
and in docs
after merchent verify check again this uri for payment confirmation
https://secure.paytm.in/oltp/HANDLER_INTERNAL/TXNSTATUS
after i import the project and fix some problem i got the json error like the title i mention, can you help me please. In the IDE nothing with error sign (red sign)
ImageProblemHere
if you need anything else just ask below
Here is my code
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result != null) {
parseJson(Result); // here problem
} else {
// intent_depan();
Toast.makeText(LoginActivity.ctx,
"Login Failed, Connection Error", Toast.LENGTH_SHORT)
.show();
}
}
// Android monitor show the problem maybe here
public void parseJson(String s) {
try {
JSONObject jobj = new JSONObject();
String stat = jobj.getString("stat");
// Log.i("json result", "string result " + s1);
if (stat.equals("failed")) {
String msg = jobj.getString("msg");
Toast.makeText(LoginActivity.ctx, msg, Toast.LENGTH_SHORT)
.show();
} else {
userName = jobj.getString("name");
// Toast.makeText(LoginActivity.ctx, userName,
// Toast.LENGTH_SHORT).show();
saveLoginState();
goToMainActivity();
}
/*
* if (s1 == "success") { intent_depan(); } else {
* intent_depan(); }
*/
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.ctx, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
creat a json object from result like this and before parsing also check the result string is a valid json string or not.
JSONObject jobj = new JSONObject(s);
The server's response cannot cannot be parsed as JSON because the server returns an error message (in HTML) instead of JSON data.
It's a HTTP 404 Not found error, indicating that the URL was probably invalid.
It would also be good practice to check if the HTTP request was successful at all. If it wasn't, don't even try to parse the response as JSON.
I'm having troubles deleting rows in the sqlite database.
What I'm trying to do is getting the Id's I want to delete from the Remote Database, and then use them to delete the rows in the SQLite DataBase.
But so far is not working
Here is where I first delete the items, and then insert items if needed.
// Method to Sync MySQL to SQLite DB
public void syncSQLiteMySQLDB() {
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
//Llamada HTTP a getdeletes.php
client.post("http://restaurantechinaimperial.com/mysqlsqlitesync/getDeletes.php", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
deleteSQLite(response);
}
});
// Make Http call to getplatos.php
client.post("http://restaurantechinaimperial.com/mysqlsqlitesync/getplatos.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Hide ProgressBar
prgDialog.hide();
// Update SQLite DB with response sent by getusers.php
updateSQLite(response);
}
// When error occured
#Override
public void onFailure(int statusCode, Throwable error, String content) {
// TODO Auto-generated method stub
// Hide ProgressBar
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Recurso no encontrado", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Algo ha fallado en el servidor", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Inesperado! [Razon mas probable: El dispositivo no esta conectado a Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
Here is the method which call the method in the sqlitecontroller to delete.
public void deleteSQLite(String response){
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has deleteid
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
String id=obj.getString("Id");
controller.deletePlato(id);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is the delete method on the sqlitehelper
public void deletePlato(String deleteid){
SQLiteDatabase database = this.getWritableDatabase();
database.delete("platos", "platoId = 'deleteid'", null);
database.close();
}
Can anybody help?