Asyntask not executing onPostExecute() - android

This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.

Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.

Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.

Related

Android JSON Parsing View Gujarati Character Using Web Service

View Gujarati Character Using Web Service in Android JSON Parsing
I Got Gujarati Word Like the one in the images I've included. If Gujarati Word is presented like અપૂર્વ, then it appears like the 1st rounded circle in the image.
Please help me to find a solution to this question
Image For Getting Gujarati Word Like this can be seen below:
And here is my code :
public class GetProductData extends AsyncTask<String, String, JSONObject> {
//private ProgressDialog p_dialog;
JSONArray jArray;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*p_dialog = new ProgressDialog(con);
p_dialog.setMessage("Please Wait ...");
p_dialog.setIndeterminate(false);
p_dialog.setCancelable(false);
p_dialog.show();*/
}
#Override
protected JSONObject doInBackground(String... params) {
jArray = JSONParser.GetProductData();
Log.d("TAG", "JSON ARRAY FOR DEVICE ID : " + jArray);
String msg = "Nothing Happened...";
try {
if (jArray != null) {
Key = jArray.getJSONObject(0).getString("Key").toString();
if (Key.equals("1")) {
db.deleteAllProductDetails();
for (int i = 1; i < jArray.length(); i++) {
Log.d("ADADADADTAG","CategoryName ::: "+jArray.getJSONObject(i).getString("CategoryName"));
Log.d("ADADADADTAG","SubCategoryName ::: "+jArray.getJSONObject(i).getString("SubCategoryName").trim());
Log.d("ADADADADTAG","ProductName ::: "+jArray.getJSONObject(i).getString("ProductName"));
db.insertProductDetails(
jArray.getJSONObject(i).getString("ProductId").trim(),
jArray.getJSONObject(i).getString("CategoryId").trim(),
jArray.getJSONObject(i).getString("CategoryName").trim(),
jArray.getJSONObject(i).getString("CategoryImageUrl").trim(),
jArray.getJSONObject(i).getString("SubCategoryId").trim(),
jArray.getJSONObject(i).getString("SubCategoryName").trim(),
jArray.getJSONObject(i).getString("SubCategoryImageUrl").trim(),
jArray.getJSONObject(i).getString("ProductName").trim(),
jArray.getJSONObject(i).getString("ProductImageUrl").trim(),
jArray.getJSONObject(i).getString("ProductCode").trim(),
jArray.getJSONObject(i).getString("ProductPrice").trim(),
jArray.getJSONObject(i).getString("ProductUnit").trim(),
jArray.getJSONObject(i).getString("ProductSmallDesc").trim(),
jArray.getJSONObject(i).getString("CategoryStatus").trim(),
jArray.getJSONObject(i).getString("SubCategoryStatus").trim(),
jArray.getJSONObject(i).getString("ProductStatus").trim()
);
}
}
} else {
}
} catch (Exception e) {
// TODO: handle exception
Log.e("TAG", "Warn :" + e.getLocalizedMessage());
Log.e("TAG", "Warn :" + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
super.onPostExecute(json);
// p_dialog.dismiss();
if (jArray != null) {
if (Key.equals("1")) {
Cursor cGetAllProductDetails = db.getAllProductDetails();
//Toast.makeText(con,"Count ::: "+cGetAllProductDetails.getCount(),Toast.LENGTH_LONG).show();
preferences = con.getSharedPreferences(IsLogin,Context.MODE_PRIVATE);
if(preferences.getBoolean(IsLogin,false))
{
Intent i = new Intent(con, DashboardActivityEnglishWithLogin.class);
startActivity(i);
overridePendingTransition(R.anim.left_in, R.anim.left_out);
finish();
}
else
{
Intent i = new Intent(con, DashboardActivityEnglishWithoutLogin.class);
startActivity(i);
overridePendingTransition(R.anim.left_in, R.anim.left_out);
finish();
}
} else if (Key.equals("0")) {
} else {
}
}
}
}
public static JSONArray GetProductData() {
// TODO Auto-generated method stub
try
{
init();
url = SITE_URL + "GetProductData";
Log.d("TAG", url);
httpPost = new HttpPost(url.toString());
Log.d("TAG", "HTTP POST"+httpPost);
pairs = new ArrayList<NameValuePair>();
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
Log.d("TAG", "HTTP POST"+httpPost);
httpResponse = httpClient.execute(httpPost);
Log.d("TAG", "HTTP RESPONSE"+httpResponse);
httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
/* Convert response to string */
result = getResult(inputStream);
Log.d("TAG","RESULT : "+ result);
jsonArray = new JSONArray(result);
Log.d("TAG", "JSON ARRAY : "+ jsonArray);
} catch (ClientProtocolException e) {
Log.e("TAG", "Error in Client Protocol : " + e.toString());
} catch (JSONException e) {
Log.e("TAG", "Error Parsing data " + e.toString());
} catch (Exception e) {
Log.e("TAG", "Error in HTTP Connection : " + e.toString());
}
return jsonArray;
}
Parse Json data using URLDecoder,
URLDecoder.decode(jArray.getJSONObject(i).getString("CategoryName"), "utf-8");
Try this
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://floming.com/shayri/guj_romanse.json", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String str = "";
try {
str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();

Paytm Sdk Version 2 - Paytm integration in Android App throwing OOPS error in doInBackground

I am integrating Paytm SDK in my Android Application. I have to POST ORDER ID and callbackurl along with other paytm credentials. All values are passing correctly. But OOPS error is displaying.
Code
public class Paytmgateway extends Activity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
String myorder = "ORDER7999883";
String mycallback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+myorder;
PostAsync postAsync= new PostAsync();
postAsync.execute(myorder,mycallback);
}
class PostAsync extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String LOGIN_URL = "http://192.168.1.4/paytmtest/generateChecksum.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> para = new HashMap<>();
para.put("myorder", args[0]);
para.put("mycallback", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", para);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
PaytmPGService Service = PaytmPGService.getProductionService();
if (json != null) {
Toast.makeText(Paytmgateway.this,"Server Response"+json.toString(), Toast.LENGTH_LONG).show();
String finalresult=json.toString();
try {
JSONObject mJsonObject=new JSONObject(finalresult);
Map paramMap = new HashMap();
System.out.println("Hi");
paramMap.put("MID", mJsonObject.getString("MID"));
System.out.println(mJsonObject.getString("MID"));
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", mJsonObject.getString("ORDER_ID"));
System.out.println(mJsonObject.getString("ORDER_ID"));
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",mJsonObject.getString("CUST_ID"));
System.out.println(mJsonObject.getString("CUST_ID"));
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",mJsonObject.getString("INDUSTRY_TYPE_ID"));
System.out.println(mJsonObject.getString("INDUSTRY_TYPE_ID"));
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", mJsonObject.getString("CHANNEL_ID"));
System.out.println(mJsonObject.getString("CHANNEL_ID"));
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", "1");
System.out.println(mJsonObject.getString("TXN_AMOUNT"));
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , mJsonObject.getString("WEBSITE"));
System.out.println(mJsonObject.getString("WEBSITE"));
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , mJsonObject.getString("CALLBACK_URL"));
System.out.println(mJsonObject.getString("CALLBACK_URL"));
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",mJsonObject.getString("CHECKSUMHASH"));
System.out.println("MYCHECK"+mJsonObject.getString("CHECKSUMHASH"));
PaytmOrder Order = new PaytmOrder(paramMap);
System.out.println("sumithra"+paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(Paytmgateway.this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"UI Error" , Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
Toast.makeText(getApplicationContext(),"No Network Available" , Toast.LENGTH_LONG).show();
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"Client Authentication Failed" , Toast.LENGTH_LONG).show();
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
Toast.makeText(getApplicationContext(),"Error Loading Webpage" , Toast.LENGTH_LONG).show();
}
// 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();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
My Android Studio Monitor output of
System.out.println(paramMap);
is
05-22 15:43:33.801 15328-15328/com.example.merchantapp I/System.out: {MID=Bigfix12826731009600, CALLBACK_URL=https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=ORDER7999883, TXN_AMOUNT=1.00, ORDER_ID=ORDER7999883, WEBSITE=BigfixGadgetWAP, INDUSTRY_TYPE_ID=Retail109, CHECKSUMHASH=HxSimAQAYRsDhJ7XX6JXT+cilxFNdSc4Pb3jr5AE5dddSavv6UD3DJffBHtcHVwQbBMYYHc850/OdZretSWIeo3m/uC0/FUA9wpO1Hgs/jY=, CHANNEL_ID=WAP, CUST_ID=25654}
Which means the two parameter values are posting successfully and i can be able to GET them also. But the following error is displaying
enter image description here
But if if i use the below code , It is working successfully
public class Paytm extends Activity {
String callback,website;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
PaytmPGService Service = PaytmPGService.getProductionService();
Map paramMap = new HashMap();
String mid="",order_id="",cust_id="",industry_type="",txn_amount="",checksum="";
Log.d("before request", "some");
JSONObject mJsonObject = null;
// String url="http://paytmtest.azurewebsites.net/APP/generateChecksum.php";
String url="http://192.168.1.4/paytmtest/generateChecksum.php";
MyAsyncTask myAsyncTask=new MyAsyncTask();
// String json = myAsyncTask.execute(url).get();
String json = (String) myAsyncTask.execute(url).get();
try {
mJsonObject=new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
try {
//mid = mJsonObject.getString("MID");
mid="Bigfix12826731009600";
// order_id=mJsonObject.getString(“ORDER_ID”);
order_id=mJsonObject.getString("ORDER_ID");
// cust_id = mJsonObject.getString(“CUST_ID”);
cust_id=mJsonObject.getString("CUST_ID");
//callback = mJsonObject.getString("CALLBACK_URL");
callback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+order_id;
//website = mJsonObject.getString("WEBSITE");
website="BigfixGadgetWAP";
//industry_type = mJsonObject.getString("INDUSTRY_TYPE_ID");
industry_type="Retail109";
txn_amount = mJsonObject .getString("TXN_AMOUNT");
// checksum = mJsonObject.getString(“CHECKSUMHASH”);
checksum = mJsonObject.getString("CHECKSUMHASH");
} catch (JSONException e) {
e.printStackTrace();
}
// Log.d(“after request”, “some”);
Log.d("after request", "some");
// paramMap.put(“MID”, mid);
paramMap.put("MID", mid);
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", order_id);
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",cust_id);
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",industry_type);
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", "WAP");
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", txn_amount);
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , website);
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , callback);
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",checksum);
System.out.println("sumithra"+paramMap);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
}
#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();
}
});
}
class MyAsyncTask extends AsyncTask {
#Override
protected String doInBackground(Object[] params) {
URL url = null;
try {
url = new URL((String) params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection httpConn = null;
try {
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = httpConn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
} catch (Exception e) {
}
Log.d("Response", result);
}
}
}
[enter image description here][2]
I just used the second code to test the trasaction. But i have to use the first posted code because i have to post the ORDERID and CALLBACKURL from android application to server . Any help would be appreciable.
**Here is the solution for all :**
Be sure to send equal number of parameters to your server (For checksum generator) And then to paytm server for payment.
**For example:**
If you are sending 6 params for checksum generator, then send these 6 same parameters including Checksum to Paytm...
It will resolve your problem.
**CODE EXAMPLE :**
**Generate checksum.php**
$paramList = array();
$paramList["MID"] = 'Provided by Paytm'; //Provided by Paytm
$paramList["ORDER_ID"] = 'hIquwhzvzTG7gvT'; //unique OrderId for every request
$paramList["CUST_ID"] = 'CUST0001453'; // unique customer identifier
$paramList["INDUSTRY_TYPE_ID"] = 'Retail'; //Provided by Paytm
$paramList["CHANNEL_ID"] = 'WAP'; //Provided by Paytm
$paramList["TXN_AMOUNT"] = '10.00'; // transaction amount
$paramList["WEBSITE"] = 'APP_STAGING';//Provided by Paytm
$paramList["CALLBACK_URL"] = 'https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp';
**Android Activity.java**
paramMap.put("MID" , "#########");
paramMap.put( "ORDER_ID" , "hIquwhzvzTG7gvT");
paramMap.put( "CUST_ID" , "CUST0001453");
paramMap.put( "CHANNEL_ID" , "WAP");
paramMap.put( "TXN_AMOUNT" , "10.00");
paramMap.put( "WEBSITE" , "APP_STAGING");
paramMap.put( "CALLBACK_URL" , "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp");
paramMap.put( "CHECKSUMHASH" , "dR5OtEkuNkgamHTZDCHmF+CF3j9RdG1520mlHEb85oSZP1CaxVUsRY2sYric90HLm/vElaPZKoQ7b5/SyFpi3oBWXf2BQNy+r6iiBwg4AH4=");
paramMap.put("INDUSTRY_TYPE_ID" , "Retail");
**NOTE : Please keep in mind to send paytm server exact parameters plus one checksum.....**

App signup button not working

here is my java file and i used onclick function in my xml file as same method working for login button but not for signup please help me to solve this issue.
public class signup extends ActionBarActivity {
EditText username, pass, cpass, mail, phn;
String uname, password, confirmpass, email, phone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
username = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
cpass = (EditText) findViewById(R.id.comfirmpass);
mail = (EditText) findViewById(R.id.email);
phn = (EditText) findViewById(R.id.phone);
Button signupbutton = (Button) findViewById(R.id.signupbutton);
}
//When the send button is clicked
public void sign(View v) {
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
//Method to get list value pair and form the query
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
//Data intialization and Validation
public void validate() {
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
if (password.equals(confirmpass)) {
post();
} else {
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
public void error(boolean flag, String etext) {
if (flag == true) {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
//Code to handle failure
} else {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
setContentView(R.layout.login);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Method to post data to webservice
public void post() {
try
{
// Calling async task to get json
new DownloadOperation().execute();
}
catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadOperation extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
String uname = "";
String email = "";
String password = "";
String confirmpass = "";
String phone = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
//Initiate ProgressBar
dialog = ProgressDialog.show(signup.this, "Please Wait", "Registering ...");
}
#Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
dialog.dismiss();
Log.d("tag", "Result:\n" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String message = jsonObj.getString("message");
boolean error = jsonObj.getBoolean("error");
error(error,message);
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
}
Have you mention android:onClick="sign" in your signup.xml under layout directory? Please make sure it.
I think your code is corect.
add Log to sign function:
public void sign(View v) {
Log.e("tag","sign function called");
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
if corect, you can show log is: "sign function called"
simply add this on your onCreate() method
signupbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"Button is clicked", 3000).show();
///what ever you want to do on signupbtn comes here
//add this try block if you need same functionality as `sign() method`
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
});
and every time you cliecked signupbutton this method(Listener) will called.
Or
add this line in you xml file where you define the signupbutton
android:onClick="sign"
But the best way for me is to add clickListener as it makes it very clear from java class side that what is beaing called on clicking the button.

Rest with Android 4.0

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like thishttp://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
WSTaxiShare ws = new WSTaxiShare();
response = ws.login(login, password);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
}
and here is the call button
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});
}

Android animation only starts after AsyncTask completes

I am trying to create a native login screen, where the username and password boxes slide off the screen while the request is being processed (and slide back up if the login is unsuccessful).
In order to achieve that, I have defined my animation (DropDownAnimation) and I assign it to my LinearLayout (footer). When the user clicks the Login button, I start the animation, and then call a function (tryLogin()) which starts an AsyncTask. The AsyncTask handles all the work of creating and sending the login request, and getting the JSONObject response.
However, my problem is that the slideDown animation doesn't start until after the AsyncTask has completed. This doesn't look so bad on a successful login, but on a failed login it means that the LinearLayout never slides down - it jumps to the bottom of the screen, to begin the slideUp animation back to its original position.
This seems like a similar problem to this question, but I'm not doing using bindService() and all my non-UI code seems (to me) to be contained in the AsyncTask already. LogCat tells me:
06-24 04:37:35.141: I/Choreographer(5347): Skipped 137 frames! The application may be doing too much work on its main thread.
I assume those are the frames where the footer would be sliding down - but I can't figure out where it is that I'm executing things on the main thread. Here's my code for LoginPage and LoginTask.
LoginPage.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
login = (Button) findViewById(R.id.login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
footer = (LinearLayout) findViewById(R.id.footer);
// We must wait for the layout to be finalised before trying to find heights.
ViewTreeObserver vto = footer.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
initAnimations();
}
});
loading = (TextView) findViewById(R.id.loading);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
// Neither of these two things happen until after LoginTask is done.
footer.startAnimation(slideDown);
loading.setVisibility(TextView.VISIBLE);
tryLogin(mUsername, mPassword);
}
});
}
protected void tryLogin(String mUsername, String mPassword) {
Exception e;
String loginUrl = getString(R.string.login_url);
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
LoginTask loginTask = (LoginTask) new LoginTask().execute(mUsername, mPassword, loginUrl, clientId, clientSecret);
if ((e = loginTask.getException()) != null) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
JSONObject response;
try {
response = loginTask.get();
Log.d("login", response.toString());
if (!response.has("access_token")) {
loading.setVisibility(TextView.INVISIBLE);
footer.startAnimation(slideUp);
Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(this, FullscreenWebView.class);
i.putExtra("accessToken", response.get("access_token").toString());
startActivity(i);
overridePendingTransition(0, 0);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
Thread.currentThread().interrupt();
} catch (ExecutionException e1) {
e1.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
throw new RuntimeException(e);
}
}
}
LoginTask.java
class LoginTask extends AsyncTask<String, Void, JSONObject> {
private Exception exception;
#Override
protected JSONObject doInBackground(String... params) {
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
JSONObject response = null;
String parameters = "grant_type=password&username="+params[0]+"&password="+params[1]+"&client_id="+params[3]+"&client_secret="+params[4];
try {
url = new URL(params[2]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
// username or password is probably wrong
Log.d("login", ""+connection.getResponseCode());
if (connection.getResponseCode() != 200) {
return new JSONObject();
}
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("login", sb.toString());
response = new JSONObject(sb.toString());
isr.close();
reader.close();
} catch (Exception e) {
this.exception = e;
}
return response;
}
}
I've also tried making LoginTask be a member class of LoginPage, and starting the animation in the onPreExecute() method, but that didn't change anything.
Any help is much appreciated!
When you use AsyncTask.get(), you are blocking the UI thread. As the animation runs on the UI thread, it appears as if it is not running (while in fact it is blocked by your long running tryLogin method).
Instead, you should move the code that relies on the result from the LoginTask to its onPostExecute method:
protected void tryLogin(String mUsername, String mPassword) {
String loginUrl = getString(R.string.login_url);
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
new LoginTask().execute(mUsername, mPassword,
loginUrl, clientId, clientSecret);
}
LoginTask.java
class LoginTask extends AsyncTask<String, Void, JSONObject> {
private Exception exception;
#Override
protected JSONObject doInBackground(String... params) {
// Unchanged
}
public void onPostExecute(JSONObject response) {
if (exception != null) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
Log.d("login", response.toString());
if (!response.has("access_token")) {
loading.setVisibility(TextView.INVISIBLE);
footer.startAnimation(slideUp);
Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(this, FullscreenWebView.class);
i.putExtra("accessToken", response.get("access_token").toString());
startActivity(i);
overridePendingTransition(0, 0);
}
}
}
}

Categories

Resources