I want to wait for the completion of a sub-thread to determine the login status. But I'm not familiar with how to write internal classes, so I'd like to ask how to write code to wait for a child thread to finish execution in the login function.
public class LoginDataSource {
static LoggedInUser loggedUser = new LoggedInUser();
public Result<LoggedInUser> login(String username, String password) {
try {
// TODO: handle loggedInUser authentication
loginMyBlog(username, password, loggedUser);
if (loggedUser.isLogStatue()) {
return new Result.Success<>(loggedUser);
} else {
return new Result.Failed("pass incorrect");
}
} catch (Exception e) {
return new Result.Error(new IOException("Error logging in", e));
}
}
public void logout() {
// TODO: revoke authentication
}
private void loginMyBlog(String usernames, String passwords, LoggedInUser userAuth) {
new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
// Code for sending network requests
//...
//Code to determine if the login is successful
try {
Response response = client.newCall(request).execute();
final String responseData = response.body().string();
JSONObject jsonObject = JSONObject
.parseObject(responseData);
String code = jsonObject.getString("code");
if (code.equals("20000")){
// login success
JSONObject dataObject = JSONObject.parseObject(jsonObject.getString("data"));
userAuth.setId(dataObject.getInteger("id"));
userAuth.setIntro(dataObject.getString("intro"));
userAuth.setLogStatue(true);
Log.d("test", "登录成功"+userAuth);
}else if (code.equals("51000")){
// login failed
userAuth.setLogStatue(false);
}
} catch (IOException e) {
e.printStackTrace();
// network err
}
}
}).start();
}
}
Thanks.
Related
I am very new in android developing. In my app I have a login page, where I want to implement authentication functionality by POST method. I have a root address through which I have to login. I am giving a sample url, because it is confidential. "test.sample.com". my Protol address is https. then I need to combine "/login" at first. Just after authenticating with this login. I have more apis like "/api/users", "api/image". I can only access to this api if I authenticate with the login functinality. How can I do that. So far I have created a login page, but at this moment I have not implemented any POST method here.
public class LoginPage extends AppCompatActivity{
private UserLoginTask mAuthTask = null;
private static final String TAG = "LoginActivity";
private AutoCompleteTextView userEmail;
private EditText userPassword;
private TextView forgotPassword;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Set up the login form
userEmail=(AutoCompleteTextView) findViewById(R.id.email);
userPassword=(EditText)findViewById(R.id.password);
forgotPassword=(TextView)findViewById(R.id.forgot_password);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getBaseContext(),"Redirect to forgot password link", Toast.LENGTH_SHORT).show();
}
});
userPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.password || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
login=(Button)findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
userEmail.setError(null);
userPassword.setError(null);
String email = userEmail.getText().toString();
String password = userPassword.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
userPassword.setError(getString(R.string.error_invalid_password));
focusView = userPassword;
cancel = true;
}
else if(TextUtils.isEmpty(password)){
userPassword.setError(getString(R.string.error_field_required));
focusView = userPassword;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
userEmail.setError(getString(R.string.error_field_required));
focusView = userEmail;
cancel = true;
} else if (!isEmailValid(email)) {
userEmail.setError(getString(R.string.error_invalid_email));
focusView = userEmail;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mAuthTask = new UserLoginTask(email,password,this);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with other logic
/*attern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();*/
return true;
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public boolean isReachable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs); // this will block no more than timeoutMs
sock.close();
return true;
} catch (IOException e) { return false; }
}
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
boolean result = false;
Activity instance ;
UserLoginTask(String email, String password , Activity instance) {
mEmail = email;
mPassword = password;
this.instance = instance ;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
authenticateUsingServer(mEmail,mPassword);
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
if (success) {
finish();
Intent loginIntent = new Intent(LoginActivity.this, DummyActivity.class);
startActivity(loginIntent);
} else {
userEmail.setError(getString(R.string.error_incorrect_password));
userPassword.requestFocus();
}
}
}
public boolean authenticateUsingServer(final String mEmail, final String mPassword){
boolean result=false ;
try {
if(isReachable("8.8.8.8", 53, 1000)){
Log.e(TAG,"Authenticate using remote server");
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
StringRequest strReq = new StringRequest(Request.Method.POST,
"https://app.com/login", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "Login Response: " + response);
//parse your response here
result = true;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Log.e(TAG,"Inside getParams");
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", mEmail);
params.put("password", mPassword);
return params;
}
};
// Adding request to request queue
queue.add(strReq);
Thread.sleep(2000);
}
else{
Log.e(TAG,"Internet connection is required.");
/*Toast.makeText(LoginActivity.this,"Internet connectivity is required",
Toast.LENGTH_LONG).show();*/
result = false;
// TODO: exit the application
}
} catch (InterruptedException e) {
return false;
}
return result;
}
}
Here use this:
First to check whether internet is available or not.
public boolean isReachable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs); // this will block no more than timeoutMs
sock.close();
return true;
} catch (IOException e) { return false; }
}
then use volley library to hit the request:
public boolean authenticateUsingServer(final String mEmail, final String mPassword){
try {
if(isReachable("8.8.8.8", 53, 1000)){
Log.e(TAG,"Authenticate using remote server");
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "Login Response: " + response);
//parse your response here
result = true;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Log.e(TAG,"Inside getParams");
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", mEmail);
params.put("password", mPassword);
return params;
}
};
// Adding request to request queue
queue.add(strReq);
Thread.sleep(2000);
}
else{
Log.e(TAG,"Internet connection is required.");
/*Toast.makeText(LoginActivity.this,"Internet connectivity is required",
Toast.LENGTH_LONG).show();*/
result = false;
// TODO: exit the application
}
} catch (InterruptedException e) {
return false;
}
return result;
}
then call it like this from Async task:
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
authenticateUsingServer(mEmail,mPassword);
// TODO: register the new account here.
return true;
}
Replace your LoginTask with following Code :
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
Activity instance ;
UserLoginTask(String email, String password , Activity instance) {
mEmail = email;
mPassword = password;
this.instance = instance ;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
JSONObject request = new JSONObject();
request.put("email",mEmail );
request.put("pass",mPassword );
String result = connectWithServer(instance , request);
if(!TextUtils.isEmpty(result)){
return true;
}else{
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(true);
if (success) {
finish();
Intent loginIntent = new Intent(LoginPage.this, MainActivity.class);
startActivity(loginIntent);
} else {
userEmail.setError(getString(R.string.error_incorrect_password));
userPassword.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
Add connectWithServer() method in your Actvity class :
public static String connectWithServer(Activity ctx , JSONObject request) {
String result ="";
try {
//Connect
HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(YOUR_SERVICE_URL)).openConnection());
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
urlConnection.setConnectTimeout(100000);
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(request.toString());
writer.close();
outputStream.close();
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}
return result;
}
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.....**
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.
I am trying to register a new user using my XMPP client using asmack library in Android on ejabberd server. The problem is that I am getting following error & the user is not being created on the server:
bad-request(400)
at org.jivesoftware.smack.AccountManager.createAccount(AccountManager.java:243)
at in.ui.MainActivity$1$1$1.run(MainActivity.java:316)
at java.lang.Thread.run(Thread.java:841)
Following is the code:
_xmppUsername = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_ID);
_xmppPassword = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_PASSWORD);
_xmppHost = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_HOST);
try {
_xmppPortNo = Integer.parseInt (XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_PORT));
} catch (Exception e) {
e.printStackTrace ();
Log.e (TAG, e.getMessage ());
}
_xmppServiceName = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_SERVICE_NAME);
ConnectionConfiguration conConfig = new ConnectionConfiguration (_xmppHost, _xmppPortNo, _xmppServiceName);
_xmppConnection = new XMPPConnection (conConfig);
if (!_xmppConnection.isAuthenticated ()) {
login ();
}
/*
* If connection has not been established or had been established &
* broken again then login
*/
#Override
public void onShow (final DialogInterface dialog) {
Button positiveButton = _dlgRegistration.getButton (DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
// Creating registration thread
new Thread (new Runnable () {
#Override
public void run () {
String clientID = null;
String password = null;
clientID = "user" + XMPP_SERVICE_NAME;
try {
// Getting hash password from UUID
password = "password";
Log.i (TAG, clientID + password);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace ();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace ();
}
}
AccountManager manager = _xmppConnection.getAccountManager ();
try {
// Creating account on the server
manager.createAccount (clientID, password, attr);
}
} catch (XMPPException e) {
e.printStackTrace ();
}
}
}).start ();
}
});
The problem was this line clientID = "user" + XMPP_SERVICE_NAME; where I shouldn't have been appending Domain or Service Name after "user".
When I try to use my restTemplate.postForEntity I get a 404 bad request
What is my fault?
Code:
Servercaller:
public ServerError login(String username, String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
try {
String URL = "http://"+ipAddress+"/ProjectTeamF-1.0/service/login.json";
Object[] params = new Object[]{URL,user};
new login().execute(params);
} catch (ResourceAccessException rae) {
receivedUser = null;
return ServerError.ServerNotFound;
} catch (HttpServerErrorException hsee) {
receivedUser = null;
return ServerError.WrongData;
} catch(RestClientException rce){
receivedUser = null;
return ServerError.WrongData;
} catch (Exception e) {
System.out.println("error " + e);
receivedUser = null;
return ServerError.OtherError;
}
return ServerError.NoError;
}
AsyncTask:
public class login extends AsyncTask<Object[], Void, Void> {
public ServerCaller sc = ServerCaller.getInstance();
public User body;
#Override
protected Void doInBackground(Object[]... params) {
String message = "";
try {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> _entity = new HttpEntity<User>((User)params[0][1], requestHeaders);
RestTemplate templ = new RestTemplate();
templ.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
templ.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
ResponseEntity<User> _response = templ.postForEntity(params[0][0].toString(), _entity, User.class); //null here in order there wasn't http converter errors because response type String and [text/html] for JSON are not compatible;
body = _response.getBody();
return null;
} catch (Exception e) {
message = e.getMessage();
return null;
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
sc.setReceivedUser(body);
}
}
When I debug the program crashes at templ.postForEntity(). The error tells me that this is a 400 - bad request.
Thanks!