LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data;
TextView graphOneTV, graphTwoTV, graphThreeTV;
GraphView graph;
String x, y;
public Graph_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_graph_, container, false);
}
HttpURLConnection connection;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
graph = (GraphView) getView().findViewById(R.id.graph1);
//graphDataClass gdc = new graphDataClass();
//gdc.execute();
String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\"," +
"\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";
String data = "";
try {
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("name").toString();
float salary = Float.parseFloat(jsonObject.optString("salary").toString());
data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
}
graphOneTV.setText(data);
} catch (JSONException e) {e.printStackTrace();}}}
So I was trying to parse JSON array by using the above code and it worked but later I was trying to fetch the JSON from my localhost pc but that JSON is not having a array name. The json which i am trying to fetch is given below.
[{"twitter":"200","googleplus":"60"},{"twitter":"150","googleplus":"180"},{"twitter":"90","googleplus":"120"}]
The code for fetching and parsing this JSON array is given below.
LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data,data2;
TextView graphOneTV, graphTwoTV, graphThreeTV;
GraphView graph;
//String x, y;
public Graph_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_graph_, container, false);
}
HttpURLConnection connection;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
graph = (GraphView) getView().findViewById(R.id.graph1);
graphDataClass gdc = new graphDataClass();
gdc.execute();
/*String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\"," +
"\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";
String data = "";
try {
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("name").toString();
float salary = Float.parseFloat(jsonObject.optString("salary").toString());
data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
}
graphOneTV.setText(data);
} catch (JSONException e) {e.printStackTrace();}
*/
}
public class graphDataClass extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL("http://192.168.1.34/getGraphData.php?");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jsonRootObject = new JSONObject(data);
JSONArray jsonArray = jsonRootObject.optJSONArray("");
for(int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int x = Integer.parseInt(jsonObject.optString("twitter").toString());
int y = Integer.parseInt(jsonObject.optString("googleplus").toString());
data2 += "Node" + i + " : \n id= " + x + " \n Name= " + y ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
graphOneTV.setText(data2);
}
}
}
But as is said earlier this JSON is not having a array name, so what should I write a the place where array name is required.
JSONArray jsonArray = jsonRootObject.optJSONArray("What show I write HERE ???? (No Array Name in JSON!!!");
modify the php code file
<?php
if($connect){
die('Could Not Connect :'.mysqli_error());
}
$result = mysqli_query($connect,"SELECT * FROM table_name);
while($row=mysqli_fetch_assoc($result)){
$output[]=$row;
}
print(json_encode(array('yourarrayname' =>$output),JSON_PRETTY_PRINT));
mysqli_close($connect);
?>
JSONArray jsonArray = jsonRootObject.optJSONArray("yourarrayname_define_php_json_file");
I Hope this will work for you.
parse like this.
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String twitter = jsonObject.getString("twitter");
String googleplus = jsonObject.getString("googleplus");
Log.e("googleplus", googleplus);
Log.e("twitter", twitter);
}
} catch (Exception e) {
}
And add data to arraylist.
If you know your string is a JSON array, then parse the string with JSONArray instead of JSONObject. Then use the array accessors like JSONArray.get.
JSONArray jsonArray = new JSONArray(json);
JSONObject first = jsonArray.optJSONObject(0);
Otherwise use gson:
Type collectionType = new TypeToken<Collection<Map<String, Object>>>(){}.getType();
Collection<Map<String, Object>> items = gson.fromJson(json, collectionType);
Or jackson:
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>();
List<Map<String, Object>> items = new ObjectMapper().readValue(json, typeReference);
Try this way :
ArrayList<HashMap<String, String>> arrayListSocial = new ArrayList<>();
String string = "[{\"twitter\":\"200\",\"googleplus\":\"60\"},{\"twitter\":\"150\",\"googleplus\":\"180\"},{\"twitter\":\"90\",\"googleplus\":\"120\"}]";
try {
JSONArray jsonarray = new JSONArray(string);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String socailTwiter= jsonobject.getString("twitter");
String socailGplus = jsonobject.getString("googleplus");
Log.e("socailTwiter",socailTwiter);
HashMap<String, String> hashMap = new HashMap<>();
hashMap .put("twitter",socailTwiter);
hashMap .put("googleplus",socailGplus );
arrayListSocial.add(hashMap);
}
}catch (Exception e){
e.printStackTrace();
}
I'm having troubles finding a way how to parse this JSONObject on Java:
{"market_cap":[[1518987267000,183700781183],
[1518987567000,183687424480],
[1518987868000,183687424480],
.
.
.
[1519080954726,7730730000]]}
This is the full json: JSON
I´m looking for save these data on a List Array...
I have updated my full function:
static String urlJsonArry2 = "http://coincap.io/history/1day/BTC";
private JSONObject responseJsonObject;
private void GettingDataGraph(){
progressDialog.setMessage("Getting Data");
progressDialog.show();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry2,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
ArrayList<Object> MARKET_CAP_ARRAY_LIST = new ArrayList<>();
JSONArray marketCapArray = responseJsonObject.optJSONArray("volume");
for (int i=0; i< marketCapArray.length(); i++){
JSONArray array1 = (JSONArray) marketCapArray.get(i);
for (int j=0; j < array1.length(); j++){
MARKET_CAP_ARRAY_LIST.add(array1.get(j));
}
}
Log.d(TAG, String.valueOf(MARKET_CAP_ARRAY_LIST));
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "ERROR " + e.getMessage());
progressDialog.dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d(TAG, "ERROR " + error.getMessage());
progressDialog.dismiss();
}
});
AppController.getInstance().addToRequestQueue(req);
}
My updated logcat is this:
D/Volley: [1] 5.onErrorResponse: ListMain
D/ListMain: ERROR org.json.JSONException: Value {"volume":[[1518987267000,9151900000],[1518987567000,9157160000],[1518987868000,9169080000],[1518988166000,9161370000],[1518988467000,9154150000],[1518988765000,9144130000],[1518989067000,9128060000],[1518989366000,9117040000],[1518989665000,9113130000],[1518989965000,9094710000],[1518990267000,9110340000],[1518990567000,9144620000],[1518990868000,9168270000],[1518991167000,9179440000],[1518991467000,9181180000],[1518991767000,9175010000],[1518992067000,9175640000],[1518992366000,9161110000],[1518992667000,9140220000],[1518992966000,9146430000],[1518993266000,9164780000],[1518993567000,9136680000],[1518993866000,9087550000],[1518994167000,9035050000],[1518994466000,8991310000],[1518994766000,8990680000],[1518995067000,8973400000],[1518995367000,8941170000],[1518995667000,8895200000],[1518995966000,8853810000],[1518996267000,8821540000],[1518996566000,8778680000],[1518996867000,8778560000],[1518997167000,8802030000],[1518997467000,8808330000],[1518997767000,8793550000],[1518998068000,8778190000],[1518998367000,8744010000],[1518998667000,8730850000],[1518998967000,8739700000],[1518999266000,8708270000],[1518999566000,8692760000],[1518999867000,8696210000],[1519000167000,8691320000],[1519000467000,8704830000],[1519000768000,8701960000],[1519001067000,8703500000],[1519001366000,8690490000],[1519001666000,8654650000],[1519001966000,8645390000],[1519002266000,8642730000],[1519002567000,8594570000],[1519002867000,8634390000],[1519003166000,8671810000],[1519003466000,8673840000],[1519003769000,8680670000],[1519004068000,8676080000],[1519004369000,8672160000],[1519004666000,8635240000],[1519004969000,8601340000],[1519005266000,8610940000],[1519005567000,8609810000],[1519005869000,8623850000],[1519006173000,8627350000],[1519006467000,8593110000],[1519006765000,8582360000],[1519007066000,8558920000],[1519007367000,8520250000],[1519007666000,8534120000],[1519007969000,8565770000],[1519008268000,8568240000],[1519008568000,8568010000],[1519008867000,8551680000],[1519009168000,8520880000],[1519009467000,8505580000],[1519009769000,8499980000],[1519010069000,8460400000],[1519010368000,8443030000],[1519010667000,8435930000],[1519010969000,8385870000],[1519011267000,8336820000],[1519011567000,8314420000],[1519011866000,8306510000],[1519012167000,8289780000],[1519012467000,8265550000],[1519012767000,8230840000],[1519013067000,8198170000],[1519013368000,8184000000],[1519013668000,8183500000],[1519013967000,8177700000],[1519014268000,8173580000],[1519014567000,8169000000],[1519014868000,8156480000],[1519015166000,8142310000],[1519015466000,8135780000],[1519015767000,8146410000],[1519016067000,8142550000],[1519016368000,8121680000],[1519016668000,8100770000],[1519016967000,8107950000],[1519017268000,8058870000],[1519017566000,7990860000],[1519017867000,7953970000],[1519018169000,7918280000],[1519018467000,7881990000],[1519018768000,7823290000],[1519019067000,7815010000],[1519019366000,7808360000],[1519019667000,7784880000],[1519019968000,7749460000],[1519020267000,7735900000],[1519020566000,7734530000],[1519020865000,7718370000],[1519021166000,7699210000],[1519021467000,7685120000],[1519021767000,7677750000],[1519022067000,7660540000],[1519022365000,7627040000],[1519022666000,7621670000],[1519022966000,7620360000],[1519023267000,7613420000],[1519023568000,7583250000],[1519023867000,7563660000],[1519024167000,7581690000],[1519024467000,7592450000],[1519024767000,7575950000],[1519025068000,7623950000],[1519025368000,7705190000],[1519025666000,7750020000],[1519025967000,7794050000],[1519026267000,7820790000],[1519026567000,7814480000],[1519026868000,7819060000],[1519027167000,7811230000],[1519027467000,7812310000],[1519027766000,7806300000],[1519028069000,7717960000],[1519028367000,7717970000],[1519028666000,7739410000],[1519028967000,7770270000],[1519029267000,7787760000],[1519029567000,7778010000],[1519029867000,7753830000],[1519030166000,7743590000],[1519030467000,7744180000],[1519030767000,7712770000],[1519031066000,7684790000],[1519031367000,7648400000],[1519031667000,7630540
I'm getting a onErrorResponse
In case someone is interested...this code works good for this array:
ArrayList<Object> MARKET_CAP_ARRAY_LIST = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("market_cap");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray array1 = (JSONArray) jsonArray.get(i);
for (int j=0; j < array1.length(); j++){
MARKET_CAP_ARRAY_LIST.add(array1.get(j));
Log.d("ARRAY: ", String.valueOf(MARKET_CAP_ARRAY_LIST));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Thanks...
You can parse JSON like this.
private void parseJsonObject(JSONObject responseJsonObject) throws JSONException {
ArrayList<Object> MARKET_CAP_ARRAY_LIST = new ArrayList<>();
JSONArray marketCapArray = responseJsonObject.optJSONArray("market_cap");
for (int i=0; i< marketCapArray.length(); i++){
JSONArray array1 = (JSONArray) marketCapArray.get(i);
for (int j=0; j < array1.length(); j++){
MARKET_CAP_ARRAY_LIST.add(array1.get(j));
}
}
}
private class JsonAsyncTask extends AsyncTask<Void, Void, Void> {
String url ;
public JsonAsyncTask(String url) {
this.url = url;
}
#Override
protected Void doInBackground(Void... voids) {
processApiResponse(url);
return null;
}
private void processApiResponse(String url) {
try {
URL jsonUrl = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(jsonUrl.openStream()));
String inputLine;
StringBuilder jsonStringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null)
jsonStringBuilder.append(inputLine);
in.close();
String jsonString = jsonStringBuilder.toString();
Volume volume = new Gson().fromJson(jsonString, Volume.class);
System.out.println(volume);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The POJO classes
private class Volume {
ArrayList<VolumeObject> market_cap;
ArrayList<VolumeObject> volume;
}
private class VolumeObject extends ArrayList<Double> {
}
You can use
// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
to add Gson in your project.
And to call the AsyncTask in an activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy);
JsonAsyncTask task = new JsonAsyncTask("http://coincap.io/history/1day/BTC");
task.execute();
}
I hope this helps
Note: For the network operation you can use any other library. Whereas retrofit is preferred by me.