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.!
Related
I am storing the data that I parsed from the JSON that is returned by my API request into the Firebase database.
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String APIURL = "https://api.github.com/users/" + idInput.getText().toString();
String repoURL = "https://api.github.com/users/" + idInput.getText().toString() + "/repos";
new JSONTask().execute(APIURL);
//new JSONTask().execute(repoURL);
String parsedUserID = idInput.getText().toString();
SM.sendDataToProfile(parsedUserID);
viewPager.setCurrentItem(1);
//addUser(parsedUserID);
}
});
When the button is clicked, it calls a new JSONTask (asynctask) on the APIURL.
JSONTask
public class JSONTask extends AsyncTask<String, String, String> {
#Override
// Any non-UI thread process is running in this method. After completion, it sends the result to OnPostExecute
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
// Pass in a String and convert to URL
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
// Reads the data line by line
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer strBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
strBuffer.append(line);
}
// If we are able to get the data do below :
String retreivedJson = strBuffer.toString();
return retreivedJson;
// When we are not able to retreive the Data
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
// close both connection and the reader
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
And it does parsing in another function.
My question is, as you can see on my setOnClickListener, I tried to make two JSONTask on two different URLs because the first URL gives me the information of the user and the second URL (repoURL) gives me the information of the user's repositories. I tried to fetch the repo info of the user and store it into the DB, but it seems like this is a wrong approach.
What is a right way to call two separate AsyncTasks on two different URLs?
EDIT
private void addUserRepo(final String githubID, final String[] repoList) {
DatabaseReference users = databaseReference.child("users");
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List list = new ArrayList<String>(Arrays.asList(repoList));
databaseReference.child("users").child(githubID).child("Repos").setValue(list);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Using data parsed from
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
RepoInfo[] repoList = new RepoInfo[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
repoList[i].setRepoName(jsonObject.getString("name"));
//repoNameList.add(jsonObject.getString("name"));
}
if(jsonObject.optString("description") != null) {
repoList[i].setDescription(jsonObject.getString("description"));
//descriptionList.add(jsonObject.getString("description"));
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
repoList[i].setOwner(ownerObject.getString("login"));
//userNameList.add(ownerObject.getString("login"));
}
}
}
} catch (JSONException jsonException){
}
}
The response of two different URLs will surely not be similar. So you need different parse methods for them.
One lazy way would be to use two different AsyncTasks subclasses for two different urls.
Another way would be to store a flag inside the asynctask indicating whether it is dealing with user or repo.
public class JSONTask extends AsyncTask <String , String , String> {
boolean fetchingRepo;
#Override
protected String doInBackground (String... params) {
fetchingRepo = params[0].endsWith("/repos");
//other statements
}
Now inside onPostExecute:
if(fetchingRepo){
//parse one way
} else {
//parse another way
}
I was tried to get data from MySQL PHP to Android with JSON Object but not work with me. I was searching about my problem but the examples I found didn't help me.
I have an array list of strings, then I set the strings MySQL DB.
After that, I want to get the cities strings from the DB with JSON, but I was unsuccessful.
My questions are:
How can I make sure that if I have city, it won't appear again?
How can I set the cities in an array list in Android?
My PHP code:
<?php
include 'connection/connection.php';
$noResult = "no results";
// to set the names at the list view
$sql = "SELECT workrCity FROM workersTable ";
$result = $connect->query($sql);
if ($result->num_rows > 0){
while($row[] = $result->fetch_assoc()) {
$json = json_encode($row,JSON_UNESCAPED_UNICODE);
}
} else {
echo $noResult;
}
echo $json;
$connect->close();
?>
the array list function in my Fragment working good :
private ArrayList<City> initCities() {
Log.d(TAG, "ArrayList_CitiesFragment_initCities");
String[] cityName = {"","","",""}; // the cities names
ArrayList<City> theCities = new ArrayList<>();
for (String aCityName : cityName) {
City city = new City(aCityName, false);
theCities.add(city);
}
return theCities;
}
Now I want to get the cities names from MySQL in a JSON-like output:
handler = new Handler(Looper.getMainLooper());
Thread runner = new Thread(new Runnable() {
#Override
public void run() {
Log.d(TAG, " runner");
GetCitiesJson getCitiesJson = new GetCitiesJson();
try{
String[] res = getCitiesJson.getCitiesDataFromDB();
JSONObject jsonObject = new JSONObject(String.valueOf(res));
JSONObject workrCity = jsonObject.getJSONObject("workrCity");
Activity activity = getActivity();
Toast.makeText(activity,"its :" + workrCity, Toast.LENGTH_SHORT).show();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
runner.start();
I know that my code is not correct, but I don't know what's missing...
Hi: Im using Volley library to get a Json file from my server and works fine and fast.
In app/build.gradle under dependencies:
compile 'com.android.volley:volley:1.0.0'
Then, in the activity you want to get the json data:
String from = "http://www.yourserver.com/file.json";
StringRequest request = new StringRequest(from, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
try {
parseJson(URLDecoder.decode(URLEncoder.encode(string, "iso8859-1"),"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Error
Log.d("ERROR:", String.valueOf(volleyError));
}
});
Volley.newRequestQueue(this).add(request);
Then you can parse the Json:
public static void parseJson(String jsonString) {
try {
JSONObject object = new JSONObject(jsonString);
getMessage(this, object);
} catch (JSONException e) {
e.printStackTrace();
}
}
And finally you can get the strings inside your Json:
public static void getMessage(JSONObject object){
if(object.length() != 0) {
try {
message = String.valueOf(object.get("message"));
} catch (JSONException e) {
e.printStackTrace();
}
} }
Okay i was copy the code. but have one problem.that the message = String.valueOf(object.get("message")); where is the var named message? it's on red colo
message is a String:String message; Then in your Json, you need a node called message to get it.
I'm new to Android and using web APIs, and I'm writing an Android App that scans a barcode from a book and then search its ISBN in Google Books API.
I have this url after the barcode scan: https://www.googleapis.com/books/v1/volumes?q=isbn:9788432250651&AIzaSyCpYez5556X4UzPV6rF4kkspj9DsCs_Q_c
And the next code:
private class GetBookInfo extends AsyncTask <View, Void, Integer> {
#Override
protected Integer doInBackground(View... urls) {
// make Call to the url
makeCall("https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + ean_content + "&AIzaSyCpYez5556X4UzPV6rF4kkspj9DsCs_Q_c");
//print the call in the console
System.out.println("https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + ean_content + "&AIzaSyCpYez5556X4UzPV6rF4kkspj9DsCs_Q_c");
return null;
}
#Override
protected void onPreExecute() {
// we can start a progress bar here
}
#Override
protected void onPostExecute(Integer result) {
String ruta = save_cover(getApplicationContext(), title, book_cover);
Intent intent = new Intent(MainActivity.this, Spreadsheets.class);
// intent.putExtra(title,title);
// intent.putExtra(author,authors);
// intent.putExtra(date,date);
// intent.putExtra(category,categories);
// intent.putExtra(description,description);
//finish();
startActivity(intent);
finish();
}
}
public void makeCall(String stringURL) {
URL url = null;
BufferedInputStream is = null;
JsonReader jsonReader;
try {
url = new URL(stringURL);
} catch (Exception ex) {
System.out.println("Malformed URL");
}
try {
if (url != null) {
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException ioe) {
System.out.println("IOException");
}
if (is != null) {
try {
jsonReader = new JsonReader(new InputStreamReader(is, "UTF-8"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("title")) {
title = jsonReader.nextString();
}
else if (name.equals("authors")) {
authors = jsonReader.nextString();
}
else if (name.equals("publishedDate")) {
date = jsonReader.nextString();
}
else if (name.equals("categories")) {
categories = jsonReader.nextString();
}
else if (name.equals("description")) {
description = jsonReader.nextString();
}
// else if (name.equals("averageRating")) {
// rating = jsonReader.nextString();
// }
else if (name.equals("thumbnail")) {
image = jsonReader.nextString();
book_cover = download_cover(image);
}
else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
}
catch (Exception e) {
System.out.println("Exception");
}
}
}
This isn't retrieving anything from the API. I would appreciate your help, thank you!
I think what you need to do next is request a connection from the API, open the connection, using JSON retrieve data from the API and use the inputStream to get the data stored in an array.
something like :Implement these methods in a class:
private static String makeHttpRequest(URL url) throws IOException
private static String readFromStream(InputStream inputStream) throws IOException
private static List extractFeatureFromJson(String booksJson)
public static List featchBookData(String requestUrl)
Here is a full code example of how to use Google Books API in Android with Feign or Retrofit. These libraries provide a higher level abstraction on top of HTTP so that you can use simple method calls and objects in your code, instead of messing with requests, responses and JSON deserialization.
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
I am retrieving JSON from my website and trying to parse it in my android app.
This is an automatic JSON generated by the back-end.
Whenever there is only single image uploaded, I am getting the link of the image without an array. That is as a single string.
However, in case there were images more than one uploaded I am getting them inside an array.(see JSON below) (JSON is invalid, as I removed some stuff that I do not use)
{
"Reports": [
{
"News": {
"Title": "Big Explosion",
"Info": "Lorem ipsum news etc here get here etc",
"field_image": "http://mysite.com/1.jpg"
}
},
{
"News": {
"Title": "2nd explosion",
"Info": "<p>Us a delimited list ws etc here get her</p>\n",
"field_image": [
"http://mysite.com/2.jpg",
"http://mysite.com/3.jpg",
"http://mysite.com/4.jpg"
]
}
]
}
I am using the below code in order to retrieve the JSON.
However, I am not able to get each String alone when there is more than a single image.
JSONObject json = jParser.getJSONFromUrl(url);
if (json != null)
{
JSONArray ReportsJsonArray = json.getJSONArray("Reports");
for (int i = 0; i < ReportsJsonArray.length(); i++)
{
JSONObject c = ReportsJsonArray .getJSONObject(i);
JSONObject news= node.getJSONObject("News");
String title = node.getString("Title");
String info = node.getString("Info");
String fieldImage = node.getString("fieldimage");
if (fieldImage.charAt(0) == '[')
{
Log.i("tag", "more than 1 image");
// HOW TO GET THEM
} else
{
Log.i("tag", "single image");
//already have them
}
}
My code works but gets the whole array as a single string.
(I have omitted the try-catch blocks to make the code simpler).
I think you should use google gson jsonreader or android jsonreader that avaible from android API-11 the JSONreader read per token and you can use the function peek() to see the JSONToken type without consuming it in your case it'll be like this
main function
//response from the server
response = myClient.execute(myConnection);
Reader streamReader = new InputStreamReader(response
.getEntity().getContent());
JsonReader reader = new JsonReader(streamReader);
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("reports")) {
readReports(reader);
} else {
reader.skipValue(); // avoid some unhandle events
}
}
reader.endObject();
reader.close();
readReports function
private void readReports(JsonReader reader) throws IOException {
reader.beginArray();
while(reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String objectNewsName = reader.nextName();
if (objectNewsName .equals("News")) {
readNews(reader);
} else {
reader.skipValue();
}
reader.endObject();
}
reader.endObject();
}
readNews function
private void readNews(JsonReader reader) throws IOException {
reader.beginObject();
while(reader.hasNext()) {
String objectNewsDataName = reader.nextName();
if (objectNewsDataName .equals("Title")) {
Log.d("NEWS",reader.nextString());
} else if (objectNewsDataName .equals("Info")) {
Log.d("NEWS",reader.nextString());
} else if (objectNewsDataName .equals("field_image")) {
if(reader.peek() == JsonToken.BEGIN_ARRAY) {
readFieldImage(reader);
} else {
Log.d("NEWS",reader.nextString());
}
}else {
reader.skipValue();
}
}
reader.endObject();
}
readFieldImage function
private void readFieldImage (JsonReader reader) throws IOException {
reader.beginArray();
while(reader.hasNext()) {
Log.d("NEWS",reader.nextString()); //you will get the field image array content here
}
}
I hope my answer is clear enough but if you have some question about my answer feel free to ask in the comment :)
have you tried this:
....
String title = node.getString("Title");
String info = node.getString("Info");
JSONArray fieldImageArray = node.getJSONArray("fieldimage");
//iterate fieldImageArray here
....
try like this
List<String> url= new ArrayList<String>();
JSONArray field_image= news.getJSONArray("field_image");
for (int i = 0; i < field_image.length(); i++) {
url.add(field_image.get(i).toString());//adding to List
}