How to Retrieve Live Currency Information from xml file in Server - java

I want to parse an xml file of this form from a url into my android application.
<ArrayOfCurrency xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MobileAssignmentApi.Models">
<Currency>
<Buy>21.19573</Buy>
<CurrencyId>53</CurrencyId>
<Name>USD/MXN</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>21.15679</Sell>
</Currency>
<Currency>
<Buy>1.46806</Buy>
<CurrencyId>22</CurrencyId>
<Name>EUR/NZD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.46395</Sell>
</Currency>
<Currency>
<Buy>1.34658</Buy>
<CurrencyId>15</CurrencyId>
<Name>EUR/CAD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.3445</Sell>
</Currency>
.
.
.
</ArrayOfCurrency>
It is an array of currencies.
After a lot of effort i managed to parse the xml file into a string into my application.
The string have now the following form.
[{"currencyId":53,"buy":21.23042,"sell":21.1921,"name":"USD/MXN","pipMultiplier":10000},{"currencyId":22,"buy":1.50225,"sell":1.49891,"name":"EUR/NZD","pipMultiplier":10000},{"currencyId":15,"buy":1.38201,"sell":1.38083,"name":"EUR/CAD","pipMultiplier":10000},{"currencyId":62,"buy":0.69619,"sell":0.69404,"name":"NZD/CHF","pipMultiplier":10000},{"currencyId":19,"buy":80.085,"sell":79.968,"name":"NZD/JPY","pipMultiplier":100},{"currencyId":13,"buy":1.23727,"sell":1.23613,"name":"GBP/CHF","pipMultiplier":10000},{"currencyId":16,"buy":0.95424,"sell":0.95167,"name":"AUD/CAD","pipMultiplier":10000},{"currencyId":5,"buy":1.00469,"sell":1.00414,"name":"USD/CHF","pipMultiplier":10000},{"currencyId":1,"buy":122.014,"sell":121.839,"name":"EUR/JPY","pipMultiplier":100},{"currencyId":60,"buy":0.9092,"sell":0.90615,"name":"NZD/CAD","pipMultiplier":10000},{"currencyId":97,"buy":30.806,"sell":30.793,"name":"TRY/JPY","pipMultiplier":100},{"currencyId":10,"buy":0.68269,"sell":0.6823,"name":"NZD/USD","pipMultiplier":10000},{"currencyId":23,"buy":1.61316,"sell":1.61245,"name":"GBP/CAD","pipMultiplier":10000},{"currencyId":9,"buy":1.31115,"sell":1.31023,"name":"USD/CAD","pipMultiplier":10000},{"currencyId":3,"buy":1.21594,"sell":1.21552,"name":"GBP/USD","pipMultiplier":10000},{"currencyId":27,"buy":1.75536,"sell":1.7494,"name":"GBP/NZD","pipMultiplier":10000},{"currencyId":63,"buy":3.6378,"sell":3.62206,"name":"USD/TRY","pipMultiplier":10000},{"currencyId":64,"buy":3.83117,"sell":3.81819,"name":"EUR/TRY","pipMultiplier":10000},{"currencyId":28,"buy":0.73074,"sell":0.72814,"name":"AUD/CHF","pipMultiplier":10000},{"currencyId":50,"buy":9.54563,"sell":9.51557,"name":"EUR/SEK","pipMultiplier":10000},{"currencyId":18,"buy":87.091,"sell":86.919,"name":"CAD/JPY","pipMultiplier":100},{"currencyId":14,"buy":1.43031,"sell":1.4289,"name":"EUR/AUD","pipMultiplier":10000},{"currencyId":8,"buy":0.71693,"sell":0.7154,"name":"AUD/USD","pipMultiplier":10000},{"currencyId":17,"buy":83.97,"sell":83.811,"name":"AUD/JPY","pipMultiplier":100},{"currencyId":11,"buy":0.84385,"sell":0.84329,"name":"EUR/GBP","pipMultiplier":10000},{"currencyId":4,"buy":115.641,"sell":115.555,"name":"USD/JPY","pipMultiplier":100},{"currencyId":61,"buy":0.75641,"sell":0.75508,"name":"CAD/CHF","pipMultiplier":10000},{"currencyId":20,"buy":1.67121,"sell":1.66758,"name":"GBP/AUD","pipMultiplier":10000},{"currencyId":76,"buy":1171.7,"sell":1170.674,"name":"XAU/USD","pipMultiplier":100},{"currencyId":6,"buy":142.45,"sell":142.188,"name":"GBP/JPY","pipMultiplier":100},{"currencyId":2,"buy":1.04081,"sell":1.03929,"name":"EUR/USD","pipMultiplier":10000},{"currencyId":54,"buy":13.77633,"sell":13.70746,"name":"USD/ZAR","pipMultiplier":10000},{"currencyId":7,"buy":1.05845,"sell":1.05868,"name":"EUR/CHF","pipMultiplier":10000},{"currencyId":52,"buy":8.53823,"sell":8.51386,"name":"USD/NOK","pipMultiplier":10000},{"currencyId":48,"buy":9.0615,"sell":9.03791,"name":"USD/SEK","pipMultiplier":10000},{"currencyId":12,"buy":113.73,"sell":113.454,"name":"CHF/JPY","pipMultiplier":100},{"currencyId":21,"buy":1.03599,"sell":1.03438,"name":"AUD/NZD","pipMultiplier":10000},{"currencyId":51,"buy":8.99332,"sell":8.96375,"name":"EUR/NOK","pipMultiplier":10000},{"currencyId":150,"buy":6.7165,"sell":6.7144,"name":"USD/CNH","pipMultiplier":1000},{"currencyId":77,"buy":15.142,"sell":15.112,"name":"XAG/USD","pipMultiplier":100},{"currencyId":93,"buy":7.182,"sell":7.129,"name":"ZAR/JPY","pipMultiplier":100}]
using the following code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
String str = "http://massignment.zulutrade.com/api/rates";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskClass().execute(str);
}
class AsyncTaskClass extends AsyncTask<String, Void,String > {
private Exception exception;
protected String doInBackground(String ...params) {
URLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(str);
connection = url.openConnection();
connection.setDoOutput(true);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
StringBuilder builder = new StringBuilder();
int i=0;
while ((line = reader.readLine()) != null) {
builder.append(line+"\n");
// Log.w("Response ", "> " + line );
i++;
}
String xml = builder.toString();
}
catch( IOException e) {
e.printStackTrace();
}
return "0k";
}
protected void onPostExecute() {
}
}
}
I need to parse that xml/string to its contents.
Any idea how can i do that parsing?

Assuming that your code is in Java - there are some good XML parsers available. You may want to use one of them to parse your XML.

Related

How to get the returned value of AsyncTask in android studio

Helloo, I know there is a lot of posts abnout this but ITS SO confusing i'v read alot of them but i can't manage to solve a simple probleme. All i want is to get a Class from my main activity.kt when i do
val QuizzList = Network().execute(); (in main activity.kt)
I want QuizzList to be my class, not a Async task blabla.
What do i need to do in here to make this task returns a QuizCollection (its a custom class)?
package com.example.myapplication;
import android.os.AsyncTask;
import android.os.Build;
import androidx.annotation.RequiresApi;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Network extends AsyncTask<String, Integer, Object> {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public Network() {
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected QuizCollection doInBackground(String... params) {
try {
// On doit utiliser cet adresse URL, le 127.0.0.1 ne marche pas a cause du serveur qui
// Roule deja sur l'adresse.
//Get the content from the server
URL url = new URL("http://10.0.2.2:8080/api/quizz");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
Gson gson = new Gson();
JSONArray jsonArray = new JSONArray(content.toString());
System.out.println("Le content : "+content.toString());
QuizCollection quizz = new QuizCollection();
for (int i=0; i<jsonArray.length();i++){
System.out.println(jsonArray.get(0).toString());
Quiz quiz = gson.fromJson(jsonArray.getJSONObject(i).toString(), Quiz.class);
System.out.println("Titre "+quiz.Title);
quizz.addQuiz(quiz);
}
System.out.println("ca fonctionne?"+quizz.QuizArray.get(0).Title);
in.close();
return quizz;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Object page)
{
//onPostExecute
}
}
You should use callback
public interface OnTaskCompleted{
void onTaskCompleted(QuizCollection collection);
}
In your Activity:
//do whatever you want with collection which is the object returned from AsyncTask
Network(OnTaskCompleted { collection -> collection.toString() }).execute()
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,QuizCollection >{
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected QuizCollection doInBackground(String... params) {
return new QuizCollection();
}
protected void onPostExecute(QuizCollection collection){
// your stuff
listener.onTaskCompleted(collection);
}
}
I had to do this
protected void onPostExecute(QuizCollection result)
{
//onPostExecute
super.onPostExecute(result);
}
And do a .get() after calling execute

Extract json data from an api array or matrix java android studio

I can't extract data from this json. I believe it is because it is an array. I read about it but I didn't find anything specific for this case.
I just need to take the values ​​individually each time I close {}.
Eg: result [0] .getLoterias();
== INSTANTANEA
The connection is being made normally, I just can't extract the data.
httpservice2.java
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Gson().fromJson(resposta.toString(), CEP2.class);
}
}
Main3Activity.java:
package br.com.matheuscastiglioni.blog.requisicao_http;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutionException;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
import br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2;
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
final TextView resposta = findViewById(R.id.etMain_resposta2);
final TextView cep = findViewById(R.id.etMain_resposta3);
final TextView token = findViewById(R.id.etMain_resposta4);
Bundle extras = getIntent().getExtras();
String respostatoken = extras.getString("token");
String respostaid = extras.getString("id");
cep.setText(respostaid);
token.setText(respostatoken);
//alert(cep.getText().toString() + token.getText().toString());
try {
CEP2 retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get();
String loteria = retorno.getIdloteria();
resposta.setText(loteria);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private void alert(String s) {
Toast.makeText(this,s,Toast.LENGTH_LONG).show();
}
}
CEP2.java:
package br.com.matheuscastiglioni.blog.requisicao_http.model;
public class CEP2 {
private String idloteria;
public String getIdloteria() {
return idloteria;
}
public void setIdloteria(String idloteria) {
this.idloteria = idloteria;
}
}
currently:
I changed
return new Gson().fromJson(resposta.toString(), CEP2.class);
per
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
httpservic2 new:
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
}
}
I need to change the return from doinbackground However, I'm lost
It seems you only want the idloteria from the response which should be fine. But as you say it's an array and it should be parsed as an array or a List.
The:
return new Gson().fromJson(resposta.toString(), CEP2.class);
Should be
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
If you want the response be parsed as a list.
Another possibility is to get the data parsed as an array:
CEP2[] cep2Array = new Gson().fromJson(resposta.toString(), CEP2[].class);
return cep2Array;
and you'll need to change the return of the doInBackground in accordance with the response type you choose.
Lets choose to return a list. In this case change AsyncTask<Void, Void, CEP2> to AsyncTask<Void, Void, List<CEP2>> and also protected CEP2 doInBackground to protected List<CEP2> doInBackground.
The returned list will be received in onPostExecute parameter onPostExecute(List<CEP2> cep2List). And in this onPostExecute you can save the list, print it or do whatever you want to do with the received data.
But keep in mind that AsyncTask are deprecated in API level R. It's recommended using standard java.util.concurrent or Kotlin concurrency utilities instead.

Json data fetching lag problem from jsonbin.io

I'm working on a app that is a simple game, so here's a picture for the UI I have, the problem is when I fetch a level using Json web service, the first time I choose the level from activity_level_list, the picture and level number doesn't show, only the 4 words works but neither the image nor the level number appear like this.
NOTE: The image URL variable is null (because of the lag that happens the first time I open first level activity) so an error happen (that's why it shows ic_launcher instead of showing the level picture).
So, I said the problem was "lag" because when I go back to LevelList and click on level 1, the picture and the level number get fetched and everything becomes good.
How can I make it both the image and level ID appears in the first time I open the activity?
NOTE: I use jsonbin.io for data fetching.
Here's my Json data fetching class:
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FetchData extends AsyncTask<Void,Void,Void> {
String update = "4";
String data ="";
String id;
String img;
String w1;
String w2;
String w3;
String w4;
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
// for(int i = 0 ;i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(1);
id = (String) JO.get("id");
img = (String) JO.get("img");
w1 = (String) JO.get("w1");
w2 = (String) JO.get("w2");
w3 = (String) JO.get("w3");
w4 = (String) JO.get("w4");
// }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
int levelId = Integer.parseInt(id);
levelId++;
LevelActivity.levelID = String.valueOf(levelId);
LevelActivity.imageURL = img;
LevelActivity.button1Word = w1;
LevelActivity.button2Word = w2;
LevelActivity.button3Word = w3;
LevelActivity.button4Word = w4;
}
}
Thanks ^-^
I just needed to update the image and level text view number in onPostExecute method to make it load from the first time.
Answer by NIKHIL AGGARWAL

My HTML fetcher program in java returns incomplete results

My java code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class celebGrepper {
static class CelebData {
URL link;
String name;
CelebData(URL link, String name) {
this.link=link;
this.name=name;
}
}
public static String grepper(String url) {
URL source;
String data = null;
try {
source = new URL(url);
HttpURLConnection connection = (HttpURLConnection) source.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
/**
* Attempting to fetch an entire line at a time instead of just a character each time!
*/
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while((data = br.readLine()) != null)
str.append(data);
data=str.toString();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static ArrayList<CelebData> parser(String html) throws MalformedURLException {
ArrayList<CelebData> list = new ArrayList<CelebData>();
Pattern p = Pattern.compile("<td class=\"image\".*<img src=\"(.*?)\"[\\s\\S]*<td class=\"name\"><a.*?>([\\w\\s]+)<\\/a>");
Matcher m = p.matcher(html);
while(m.find()) {
CelebData current = new CelebData(new URL(m.group(1)),m.group(2));
list.add(current);
}
return list;
}
public static void main(String... args) throws MalformedURLException {
String html = grepper("https://www.forbes.com/celebrities/list/");
System.out.println("RAW Input: "+html);
System.out.println("Start Grepping...");
ArrayList<CelebData> celebList = parser(html);
for(CelebData item: celebList) {
System.out.println("Name:\t\t "+item.name);
System.out.println("Image URL:\t "+item.link+"\n");
}
System.out.println("Grepping Done!");
}
}
It's supposed to fetch the entire HTML content of https://www.forbes.com/celebrities/list/. However, when I compare the actual result below to the original page, I find the entire table that I need is missing! Is it because the page isn't completely loaded when I start getting the bytes from the page via the input stream? Please help me understand.
The Output of the page:
https://jsfiddle.net/e0771aLz/
What can I do to just extract the Image link and the names of the celebs?
I know it's an extremely bad practice to try to parse HTML using regex and is the stuff of nightmares, but on a certain video training course for android, that's exactly what the guy did, and I just wanna follow along since it's just in this one lesson.

Android: JSON parsing error nothing comes up

I am trying to parse JSON, I have done it there before but not quiet this way. I spent hours trying to solve the problem, but I dont know what is wrong with the code.I am attaching the entire code for the activity, Web Request class and the layout. Any help will be greatly appreciated.
I get this error
java.io.FileNotFoundException: /data/system/users/sdp_engine_list.xml: open failed: ENOENT (No such file or directory)
05-19 18:17:27.427 3450-3450/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
05-19 18:17:28.232 3450-3592/? W/DisplayManagerService: Failed to notify process 20004 that displays changed, assuming it died.
This is the activity Transactions class.
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import com.rectuca.iyzicodemo.Classes.Transaction;
import com.rectuca.iyzicodemo.Library.WebRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Transactions extends ListActivity {
// URL to get contacts JSON
private static String url = "http://www.mocky.io/v2/573dbd243700005f194dcdcc";
// JSON Node names
private static final String TAG_PAYMENTS= "payments";
private static final String TAG_PAYMENT_ID = "paymentId";
private static final String TAG_SENT_BY = "sentBy";
private static final String TAG_DATE_TIME = "dateTime";
private static final String TAG_SENT_TO = "sentTo";
private static final String TAG_BANK_NAME = "bankName";
private static final String TAG_INSTALLMENTS = "installments";
private static final String TAG_AMOUNT = "amount";
private static final String TAG_3DS = "threeDs";
private static final String TAG_CANCELLED = "cancelled";
private static final String TAG_RETURNED = "returned";
private static final String TAG_TRANSACTION_STATUS = "transactionStatus";
private static final String TAG_BLOCKAGE_AMOUNT = "blockage_amount";
private static final String TAG_BLOCKAGE_RELEASE_DATE = "blockageReleaseDate";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
// Calling async task to get json
new GetInfo().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetInfo extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> transactionInfoList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(Transactions.this);
proDialog.setMessage("Please Wait...");
proDialog.setCancelable(false);
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webReq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webReq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
transactionInfoList = ParseJSON(jsonStr);
return null;
}
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
transactionInfoList=new ArrayList<HashMap<String, String>>();
ListAdapter adapter = new SimpleAdapter(
Transactions.this, transactionInfoList,
R.layout.row_layout, new String[]{TAG_SENT_TO,TAG_DATE_TIME
,TAG_BANK_NAME,TAG_AMOUNT,TAG_3DS, TAG_CANCELLED,
TAG_RETURNED},
new int[]{R.id.name,R.id.dateTime ,R.id.bankName,R.id.amount,
R.id.threeDS, R.id.cancelled, R.id.returned});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> paymentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray payments = jsonObj.getJSONArray(TAG_PAYMENTS);
// looping through All Payments
for (int i = 0; i < payments.length(); i++) {
JSONObject c = payments.getJSONObject(i);
String dateTime =c.getString(TAG_DATE_TIME);
String sentTo =c.getString(TAG_SENT_TO);
String bankName =c.getString(TAG_BANK_NAME)+" ( "+c.getString(TAG_INSTALLMENTS)+" ) " ;
String amount =c.getString(TAG_AMOUNT);
String threeDS =c.getString(TAG_3DS);
String cancelled =c.getString(TAG_CANCELLED);
String returned =c.getString(TAG_RETURNED);
// temporary hashmap for a single payment
HashMap<String, String> payment = new HashMap<String, String>();
// adding every child node to HashMap key => value
payment.put(TAG_DATE_TIME, dateTime);
payment.put(TAG_SENT_TO, sentTo);
payment.put(TAG_BANK_NAME, bankName);
payment.put(TAG_AMOUNT, amount);
payment.put(TAG_3DS, threeDS);
payment.put(TAG_CANCELLED, cancelled);
payment.put(TAG_RETURNED, returned);
// adding student to students list
paymentList.add(payment);
}
return paymentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
This is the WebRequest Class
package com.rectuca.iyzicodemo.Library;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class WebRequest {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* #url - url to make request
* #requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* #url - url to make request
* #requestmethod - http request method
* #params - http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
This is what I am trying to do
http://lh3.googleusercontent.com/JqcySZU2Pz067NutlDvPP5Zq_3n_WSAllIuEdjQjOjyeGkKguaMNCrltaKbjBCi16g=h900-rw
I would suggest you to use
VOLLEY networking library by google
You should try to use Volley JSONOBJECTREQUEST() and you won't have any issue after that parsing will be easier.
add this to dependency section of your app
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

Categories