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
Related
I'm trying to get the value for the key 'GBP' in the following link: https://api.fixer.io/latest
I've managed to connect to the API successfully and I'm able to cycle through the keys until I get "rates". Inside rates though, I don't know how I cycle through all the currencies until I find 'GBP'.
Note: I'm paring the Json - I'm struggling to parse a Json object that has a Json within it. It's different to the duplicates you've referenced.
My code so far looks like this:
String urlStr = "https://api.fixer.io/latest";
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// Create URL
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Create connection
try {
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("rates")) { // Check if desired key
// Fetch the value as a String
String value = jsonReader.nextString();
//currentCurrency = value;
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
Try this
JSONObject jsonObject = new JSONObject(" your json response ");
Iterator iteratorObj = jsonObject.keys();
while (iteratorObj.hasNext())
{
String JsonObjRates = (String)iteratorObj.next();
if (JsonObjRates.equals("rates")) {
JSONObject jo_rates = jsonObject.getJSONObject(JsonObjRates);
Iterator<String> keys = jo_rates.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jo_rates.getString(key);
Log.i("RATES key", key);
Log.i("RATES value", value);
if(key.equals("GBP"))
{
Log.i("GBP RATES key", key);
Log.i("GBP RATES value", value);
}
}
}
}
Output
Instead of Using manual parsing used below things.
Please Use RoboPojo Generator into Android Studio it will helps you to create model class for you and directly setData to your model class.
if you are using Gson to setData.
Below ilink is helping to you :
https://github.com/robohorse/RoboPOJOGenerator
hope this helps you.
You can use Volleylibrary to make request that url and you will take response.
after take response via related url, you can parse it on Android Studio.
dependencies {
...
compile 'com.android.volley:volley:1.1.0'
}
above will be added in dependencies.
below will be added in your Activity(like MainActivity).
String url ="https://api.fixer.io/latest";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject resultJSON=new JSONObject(response);
JSONObject rates=resultJSON.getJSONObject("rates");
string GPB=rates.getString("GPB");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
I guess it will work. make feedback whether it works or not.
Try this.
You have to loop through jsonobject so first create class for rates.
public Rates readRates(JsonReader reader) throws IOException {
String country_rate = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("GBP")) {
country_rate = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
return new Rates(country_rate);
}
Decalre your class at start of this http method
Rates rate = null;
Replace this Code
if (key.equals("rates")) { // Check if desired key
// Fetch the value as a String
String value = jsonReader.nextString();
//currentCurrency = value;
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
With this
if (key.equals("rates"))
{
rate = readRates(jsonReader);
String rate_value = rate.country_rate;
}
else
{
jsonReader.skipValue(); // Skip values of other keys
}
For more details https://developer.android.com/reference/android/util/JsonReader.html
Hope it helps.!
Task
Create a one-time login feature using Android's authentication manager.
Current Process
I am currently using the Volley to read email and password from a form and send a request to a server
Required Change
To be able to create a one-time login for the use with credentials, using Android authentication manager following this post.
Question
1. My question lies in the implementation of the fetchTokenFromCredentials method under the getAuthToken of the authenticator class.
Here is the Java code snippet:
#Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options)
throws NetworkErrorException {
// We can add rejection of a request for a token type we
// don't support here
// Get the instance of the AccountManager that's making the
// request
final AccountManager am = AccountManager.get(mContext);
// See if there is already an authentication token stored
String authToken = am.peekAuthToken(account, authTokenType);
// If we have no token, use the account credentials to fetch
// a new one, effectively another logon
if (TextUtils.isEmpty(authToken)) {
final String password = am.getPassword(account);
if (password != null) {
authToken = fetchTokenFromCredentials(account.name, password, authTokenType)
}
}
// If we either got a cached token, or fetched a new one, hand
// it back to the client that called us.
if (!TextUtils.isEmpty(authToken)) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
return result;
}
// If we get here, then we don't have a token, and we don't have
// a password that will let us get a new one (or we weren't able
// to use the password we do have). We need to fetch
// information from the user, we do that by creating an Intent
// to an Activity child class.
final Intent intent = new Intent(mContext, LoginActivity.class);
// We want to give the Activity the information we want it to
// return to the AccountManager. We'll cover that with the
// KEY_ACCOUNT_AUTHENTICATOR_RESPONSE parameter.
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
// We'll also give it the parameters we've already looked up, or
// were given.
intent.putExtra(LoginActivity.ARG_IS_ADDING_NEW_ACCOUNT, false);
intent.putExtra(LoginActivity.ARG_ACCOUNT_NAME, account.name);
intent.putExtra(LoginActivity.ARG_ACCOUNT_TYPE, account.type);
intent.putExtra(LoginActivity.ARG_AUTH_TYPE, authTokenType);
// Remember that we have to return a Bundle, not an Intent, but
// we can tell the caller to run our intent to get its
// information with the KEY_INTENT parameter in the returned
// Bundle
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
Previously I was using Volley , so my implementation of fetchTokenfromCredentials was something like shown below. However, I cannot use the same implementation now because I need to 'return' an authentication string. Volley does the login asynchronously so even if i add a return type to the function below it will always return null. Question: How do i wrap around THIS situation. What alternatives can I use?
public void fetchTokenfromCredentials(String name, String password) {
JSONObject loginObject = new JSONObject();
try {
loginObject.put("email", email);
loginObject.put("password", password);
} catch(JSONException e) {
e.printStackTrace();
}
// assume predefined url and params
JsonObjectRequest loginRequest = new HeaderRequest(Request.Method.POST, url + params, loginObject, new Response.Listener < JSONObject > () {#Override
public void onResponse(JSONObject response) {
try {
JSONObject headers = response.getJSONObject("headers");
// A simple use class that stores the id, username etc.
user = new User(response.getInt("id"), response.getString("name"), response.getString("authentication_token"), response.getString("email"));
// Previous code started a new main activity intent here
} catch(JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Failed response");
}
});
RequestQueueSingleton.getInstance(this.getApplicationContext()).addToRequestQueue(loginRequest);
}
You can make a synchronous, blocking request with Volley. That request will perform the network request, while blocking the thread and allow you to set a return type.
I am not fluent with Volley (Retrofit, FTW!) but I am pretty sure it's doable.
Take a look at this answer for a Synchronous request - https://stackoverflow.com/a/23808857
This is how I wrote the fetchTokensFromCredentials(email,password) function using the android Http Client Library:
URL was created using a uri builder
Uri builtUri = Uri.parse(AccountGeneral.LOGIN_QUERY).buildUpon()
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Stores result of the post response
String result = null;
// Create a JSON object for the email and password
JSONObject loginObject = new JSONObject();
try{
loginObject.put("email", email);
loginObject.put("password", password);
} catch(JSONException e) {
e.printStackTrace();
}
// Convert JSON to String
String data = loginObject.toString();
// Connection parameters
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
try {
//Start POST request - Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
//Read response
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();
return result;
} finally {
urlConnection.disconnect();
}
I want to pass the Spinner value to php and get some result and display into my TextView. when i use Toast to display the Selected value its working perfect.but while pass the value to the php file i am struck. I tried some ways. can some to fix my problem.
java file:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); //<< this for hide title bar
setContentView(R.layout.sales_order);
fg.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
if(goods_name1.getSelectedItem() !=null && goods_name1.getSelectedItem() !=""){
// WebServer Request URL
String serverURL = "http://IP/fs/getProductOneStock.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Spinner1: unselected");
}
});
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Sales_Order.this);
String data ="";
int sizeData = 0;
TextView pro_stock1 = (TextView)findViewById(R.id.tv_stock1);
Spinner fgStock = (Spinner)findViewById(R.id.spinner1);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8") + "="+fgStock.getSelectedItem();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
pro_stock1.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
pro_stock1.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Finish_goods_mas");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String Stock1 = jsonChildNode.optString("Finish_goods_mas").toString();
OutputData += Stock1;
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
my php file
<?php
require "db_config.php";
$Goods_name=$_POST['Goods_name'];
$sql = "select goods_min_level from Finish_goods_mas where Goods_name='".$Goods_name."'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
//echo $row['cus_id']."<br />";
$json['Finish_goods_mas'][]=$row;
}
sqlsrv_free_stmt( $stmt);
echo json_encode($json);
?>
after make changes of doInBackground and onPreExecute() the Spinner value not pass to php file also i cannot get back result from php
When an asynchronous task is executed, the task goes through 4 steps:
1.onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
so textView.setText(strOrderNo); do it in onPostExecute(Result) override method
I am performing login task and getting data from PHP server in json format. In response, I am getting a 'success' tag that containing User-ID
like this {"message":"You have been successfully login","success":"75"}
I get that value as "uid" in the same activity and move to next page. Now in next page, I want to check user profile. For that, I have to pass that "uid" as 'params' with url and get value from server. But don't understand how to do that.
In next activity page I am creating asyncTask to perform action.
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "GET",params);
// Check your log cat for JSON reponse
Log.d("Profile JSON: ", json.toString());
try {
// profile json object
profile = json.getJSONObject(TAG_PROFILE);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Now I have to set the 'uid' in the place of params.
Use intent to pass data,
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("UID", uId);
startActivity(intent)
Use intent, but if you want to keep your uid for a long time , you can use SharedPrefferences
Method 1:
Class A {
String UID = "3";
public static void main(String[] args){
ClassB.setUid(3);
}
}
Class B {
public static String uid;
public static setUid(String id){
uid = id;
}
}
Method 2:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("U_ID", uId);
startActivity(intent)
Beware about static variables, programmers dont usually like them and call them evil.
If what you're trying to do is transfer data from one activity to another, try adding an extra to your intent. After you've created the intent to launch the next page, add something like
intent.putExtra("uid", uid);
to add the uid as an extra. And on the next page, you can retrieve this data by
Intent intent = getIntent();
int uid = intent.getIntExtra("uid", defaultvalue);
In case you need to pass parameters along with GET method, you can simply add the respective values to the url:
public void getData(String uid) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.yoursite.com/script.php?uid=" + uid);
HttpResponse response = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
If you want to pass parameters with POST method the code is a bit more complex:
public void postData(String uid) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
nameValuePairs.add(new BasicNameValuePair("uid", uid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
In both cases you can get server response as stream:
InputStream s = response.getEntity().getContent();
The easiest way to get response body as a String is to call:
String body = EntityUtils.toString(response.getEntity());
Of course, there are numerous other ways to achive what you desire.
There are two ways to pass parameters with Get request.
http://myurl.com?variable1=value&variable2=value2
Passing arguments as headers in request.
As HttpClient is now deprecated in the API 22, so you should use the Google Volley https://developer.android.com/training/volley/simple.html
Adding parameters using volley library as
/**
* This method is used to add the new JSON request to queue.
* #param method - Type of request
* #param url - url of request
* #param params - parameters
* #param headerParams - header parameters
* #param successListener - success listener
* #param errorListener - error listener
*/
public void executeJSONRequest(int method, String url, final JSONObject params, final HashMap<String, String> headerParams,
Response.Listener successListener,
Response.ErrorListener errorListener) {
JsonObjectRequest request = new JsonObjectRequest(method, url, params,
successListener, errorListener) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
if (headerParams != null)
return headerParams;
else
return super.getHeaders();
}
};
// Add request to queue.
addRequestToQueue(request);
}
I'm building an Android app that uses the Instagram API to retrieve Instagram images and then display them in my app.
I've been trying to make it work using the only tutorial I found on this,
which is same as this.
I've been able to the first part by loading the Instagram authentication in a Webview, but I'm having trouble with the second part which is actually getting images from my Instagram account by getting the Instagram imageUrl.
Specifically I'm having trouble with this part:
class LongOperation extends AsyncTask<String, Void, String> {
static String accessTokenString, id, username, urlString, imageUrlString;
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(tokenURLString);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("POST");
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpsURLConnection.getOutputStream());
outputStreamWriter.write("client_id="+client_id+
"client_secret="+ client_secret +
"grant_type=authorization_code" +
"redirect_uri="+CALLBACKURL+
"code=" + token);
outputStreamWriter.flush();
Log.i(TAG, "before streamToString");
String response = streamToString(httpsURLConnection.getInputStream());
Log.i(TAG, "after streamToString");
JSONObject jsonObject = (JSONObject) new JSONTokener(response).nextValue();
accessTokenString = jsonObject.getString("access_token"); //Here is your ACCESS TOKEN
id = jsonObject.getJSONObject("user").getString("id");
username = jsonObject.getJSONObject("user").getString("username");
//This is how you can get the user info.
//You can explore the JSON sent by Instagram as well to know what info you got in a response
}
catch (Exception e)
{
Log.e(TAG, "ERROR AsyncTask");
}
return null;
}
//converts Stream to String
public String streamToString(InputStream p_is)
{
try
{
BufferedReader m_br;
StringBuffer m_outString = new StringBuffer();
m_br = new BufferedReader(new InputStreamReader(p_is));
String m_read = m_br.readLine();
while(m_read != null)
{
m_outString.append(m_read);
m_read =m_br.readLine();
}
Log.d(TAG, "m_outString: " + m_outString.toString());
return m_outString.toString();
}
catch (Exception e)
{
Log.e(TAG, "ERROR streamToString");
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d(TAG, "Executed AsyncTask");
}
#Override
protected void onPreExecute() {
Log.d(TAG, "About to execute AsyncTask");
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
I'm wondering what the token variable is? (doInBackground method, in the outStreamWriter arguments)
I'm currently putting the request_token from the AuthWebViewClient.
The AuthWebViewClient is getting a request_token from Instagram successfully after I press Authorize in my WebView.
But I get an error when trying to turn the InputStream to a String!
06-16 14:14:42.302: D/tellmeaboutit(31244): About to execute AsyncTask
06-16 14:14:42.642: I/tellmeaboutit(31244): request_token: 235958nvzdj243u9o974jd1490139238
06-16 14:14:42.642: I/tellmeaboutit(31244): before streamToString
06-16 14:14:42.792: D/tellmeaboutit(31244): ERROR AsyncTask
Prints "before streamToString" then "ERROR AsyncTask" and never reaches "after streamToString".
I'm starting the LongOperation with a button click:
doSomethingIunno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LongOperation().execute("");
}
});
What's wrong here? Why do I get an error when I try and convert the InputStream to a String?
Well, instead of building your own code, why don't you try to use this library instead ? Look at the custom-ui example on "instagram get feeds" part.