My app is not showing JSON data from an URL - android

I am new to the android studio and I am trying to make my simple app get JSON data from URL i.e fetch JSON data from the server with Volley in Android Studio. When I debug on my device, it works fine but don't show any data and I am sure there is something wrong
my code:
package imo.meteoiraq;
import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
TextView nameText,descriptionText,fbUrlText,youtubeUrlTxt;
int humidity;
int wind_speed;
int temperature;
String url="/stationlookupstation=I1410&units=metric&v=2.0&format=json";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq= Volley.newRequestQueue(this);
nameText= (TextView) findViewById(R.id.tempText);
descriptionText = (TextView) findViewById(R.id.wind_speed);
fbUrlText = (TextView) findViewById(R.id.humidity);
sendjsonrequest();
}
public void sendjsonrequest(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
temperature = response.getInt("temperature");
wind_speed= response.getInt("wind_speed");
humidity= response.getInt("type");
nameText.setText(temperature);
descriptionText.setText(humidity);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rq.add(jsonObjectRequest);
}
}
my data json:
{
"stations": {
"I1410": {
"updated": 1499668936,
"ageh": 0,
"agem": 0,
"ages": 58,
"type": "PWS",
"wind_dir_degrees": 315,
"wind_speed": 6.1,
"wind_gust_speed": 11.1,
"humidity": 10,
"temperature": 40.5,
"precip_rate": null,
"precip_today": 0,
"pressure": 1002.26,
"dewpoint": null,
"windchill": null
}
}
}

first get JsonObject stations and I1410 , then use ages = I1410JO.getInt("ages");
JSONObject stationsJO = response.getJSONObject("stations");
JSONObject I1410JO = stationsJO.getJSONObject("I1410");
int ages = I1410JO.getInt("ages");

There are 2 issues in the program.
1st issue already explained by Rasoul Miri about accessing stationsJO JSON object and then I1410JO JSON object.
2nd issue is that temperature is not of integer format but of double format and so you need to use I1410JO.getDouble("temperature") to get it.

There is error in your Url and you have not parsed response correctly.Send Correct Url with proper(GET or POST) method.

Related

List is empty after loading it with procedure

I am beginner in android development.
I used volley library for HTTP connections
The program is supposed to load data from the server into a list called listItems and push it to a recyclerview. The program works fine but I can't make access to list values outside the procedure loadRecyclerView
This is the code:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private ArrayList<ListItem> listItems;
private TextView dateTextView;
private static final String URL_DATA = "http://10.0.2.2:8080/json/csv.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateTextView = (TextView) findViewById(R.id.Date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateTextView.setText("Date:" + simpleDateFormat.format(new Date()));
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.hasFixedSize();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerView();
// I want to access values of the list right here
Log.i("list", "onCreate: "+this.listItems.size());
}
private void loadRecyclerView() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URL_DATA,
// this is an anonymous class, make it a public class and instantiate from it
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String salle = object.getString("salle");
String matiere = object.getString("matiere");
String groupe = object.getString("groupe");
String nomEnseignant = object.getString("nomEnseignant");
String typeSeance = "";//object.getString("typeSeance");
String seance = ""; //object.getString("seance");
String regime = "";//object.getString("regime");
ListItem listItem = new ListItem(matiere,typeSeance, groupe, salle, nomEnseignant,regime,"",seance,simpleDateFormat.format(new Date()));
listItems.add(listItem);
}
adapter = new RecyclerViewAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Log.i("list", "onResponse: "+listItems.size());
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
if (error instanceof NetworkError) {
Toast.makeText(getApplicationContext(),"Cannot connect to Internet...Please check your connection!",Toast.LENGTH_SHORT).show();
}
else if (error instanceof ServerError) {
Toast.makeText(getApplicationContext(),"The server could not be found. Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(),"AuthFailureError",Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
Toast.makeText(getApplicationContext(),"Parsing error! Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),"NoConnectionError",Toast.LENGTH_SHORT).show();
} else if (error instanceof TimeoutError) {
Toast.makeText(getApplicationContext(),"Connection TimeOut! Please check your internet connection.",Toast.LENGTH_SHORT).show();
}
}
}
);
Log.i("list", "size: "+listItems.size());
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I read on google that anonymous class can change attributes but the change is not maintained outside it.
Any solution?
String request is executed in the background thread. It finishes after your attempt to check the list size, so the list is empty yet. You will have filled list in onResponse() callback.

JSON data not returning

I have written a code to access the below api and get the corresponding values of namaz timings, but the onResponse method is not getting invoked. I have given internet permissions in the android manifest file. I am new to Android, please help.
While Installing app is not asking for internet permissions though I mentioned it in manifest file.
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class NamazTiming extends AppCompatActivity {
private TextView fazarId, zoharid, asarid, magribid, ishaid, location;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namaz_timing);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Namaz Timings");
fazarId = findViewById(R.id.fazarid);
zoharid = findViewById(R.id.zoharid);
asarid = findViewById(R.id.asarid);
magribid = findViewById(R.id.magribid);
ishaid = findViewById(R.id.ishaid);
location = findViewById(R.id.location);
Button locationbutton = findViewById(R.id.locationbutton);
mQueue = Volley.newRequestQueue(this);
locationbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
//String loc = location.getText().toString().trim();
String url ="https://muslimsalat.com/uravakonda.json?key=ba8d0b5ba55c6db3cebbe3fefd6090f8";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(NamazTiming.this, "Entered onresponse", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(NamazTiming.this, "Entered into TRY", Toast.LENGTH_SHORT).show();
String Fazar = response.getJSONArray("items").getJSONObject(0).get("fajr").toString();
String Zohr = response.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
String Asar = response.getJSONArray("items").getJSONObject(0).get("asr").toString();
String Magrib = response.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
String Isha = response.getJSONArray("items").getJSONObject(0).get("isha").toString();
fazarId.setText(Fazar);
zoharid.setText(Zohr);
asarid.setText(Asar);
magribid.setText(Magrib);
ishaid.setText(Isha);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
});
}
You need to add your request object to the Volley queue (in your case, mQueue) in order for the request to be executed.
Example:
mQueue.add(request);
Internet permission is normal permission so the android system will not ask internet permission.
You just call this line:
mQueue.add(request);
end of the request.
Add below line after errorListener method at end of your request
mQueue.add("your request type");

Convert a Timestamp from data JSON URL

am new in android studio and I am trying to make my simple app get JSON data from URL using Volley , everything good but i have problem with time format Timestamp in URL i want him show in local time .
my code
package imo.meteoiraq;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.Timestamp;
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
TextView timeDesc,tempDesc,windspeedDesc,windguestDesc,humdityDesc;
int ages;
int temp;
int windspeed;
int windguest;
int humdity;
String timeupdate;
String url="/stationlookup?station=I1410&units=metric&v=2.0&format=json";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq= Volley.newRequestQueue(this);
timeDesc= (TextView) findViewById(R.id.timeupdateDesc);
tempDesc= (TextView) findViewById(R.id.tempid);
windspeedDesc= (TextView) findViewById(R.id.windid);
windguestDesc= (TextView) findViewById(R.id.windgustid);
humdityDesc= (TextView) findViewById(R.id.humdid);
sendjsonrequest();
}
public void sendjsonrequest(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject stationsJO = response.getJSONObject("stations");
JSONObject I1410JO = stationsJO.getJSONObject("I1410");
temp = I1410JO.getInt("temperature");
windspeed = I1410JO.getInt("wind_speed");
windguest = I1410JO.getInt("wind_gust_speed");
humdity = I1410JO.getInt("humidity");
timeupdate = I1410JO.getString(Timestamp,"updated");
timeDesc.setText(timeupdate);
tempDesc.setText(Integer.toString(temp));
windspeedDesc.setText(Integer.toString(windspeed));
windguestDesc.setText(Integer.toString(windguest));
humdityDesc.setText(Integer.toString(humdity));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rq.add(jsonObjectRequest);
}
}
json
{
"stations": {
"I1410": {
"updated": 1499842858,
"ageh": 0,
"agem": 1,
"ages": 6,
"type": "PWS",
"wind_dir_degrees": 270,
"wind_speed": 7.2,
"wind_gust_speed": 9.7,
"humidity": 12,
"temperature": 38.9,
"precip_rate": null,
"precip_today": 0,
"pressure": 1000.56,
"dewpoint": null,
"windchill": null
}
}
}
For converting a time stamp to Date format
Checkout Imports
//Imports are as below
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
//convert timestamp (seconds) to milliseconds
String timeupdate = "1499842858";
long timestamp = Long.parseLong(timeupdate) * 1000L;
Toast.makeText(getApplicationContext(),"Date:"+getDate(timestamp),Toast.LENGTH_SHORT).show();
timeDesc.setText(getDate(timestamp));
private String getDate(long timeStamp){
try{
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
Date netDate = (new Date(timeStamp));
return sdf.format(netDate);
}
catch(Exception ex){
return "xx";
}
}
I checked code and its working fine
you can use this code :
long millisecond = I1410JO.getLong("updated")*1000L;
timeupdate = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
timeDesc.setText(timeupdate);

How to create bar graph with remote server data using volley in Android?

I want to create bar graph like this one with mysq database using volley
I have managed to retrieve data from db and view in text view it work fine but when I try to use those data to populate bar graph nothing happen I don’t know what is wrong with it.
My Json:
{"result":[{"id":"1","std1":"30","std2":"55","std3":"70","std4":"47","std5":"91","std6":"10","std7":"54"}]}
And Below is my entire java code I followed the barGraph concept from here
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
public class MainActivity extends AppCompatActivity {
TextView textView;
RequestQueue requestQueue;
BarChart chart ;
ArrayList<BarEntry> BARENTRY ;
ArrayList<String> BarEntryLabels ;
BarDataSet Bardataset ;
BarData BARDATA ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.viewData);
chart = (BarChart) findViewById(R.id.chart1);
BARENTRY = new ArrayList<>();
BarEntryLabels = new ArrayList<String>();
AddValuesToBarEntryLabels();
Bardataset = new BarDataSet(BARENTRY, "Projects");
BARDATA = new BarData(BarEntryLabels, Bardataset);
Bardataset.setColors(ColorTemplate.COLORFUL_COLORS);
chart.setData(BARDATA);
chart.animateY(3000);
AddValuesToBARENTRY();
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest
=new JsonObjectRequest(Request.Method.POST, http://**/**/barGraphData2.php", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray= response.getJSONArray("result");
for(int i=0;i<jsonArray.length();i++){
JSONObject result= jsonArray.getJSONObject(i);
String std1= result.getString("std1");
String std2= result.getString("std2");
String std3= result.getString("std3");
String std4= result.getString("std4");
String std5= result.getString("std5");
String std6= result.getString("std6");
String std7= result.getString("std7");
// View data in text few
textView.setText(
"bar 1 -->"+std1+"\n"
+"bar 2 -->"+std2+"\n"
+"bar 3 -->"+std3+"\n"
+"bar 4 -->"+std4+"\n"
+"bar 5 -->"+std5+"\n"
+"bar 6 -->"+std6+"\n"
+"bar 7 -->"+std7+"\n"
);
//call method to use information in barGraph
AddValuesToBARENTRY (std1, std2, std3, std4, std5, std6);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"there is error bro",Toast.LENGTH_LONG).show();
}
}
) ;
requestQueue.add(jsonObjectRequest);
}
public void AddValuesToBARENTRY(String std1,String std2,String std3,String std4,String std5,String std6){
BARENTRY.add(new BarEntry(Float.parseFloat(std1), 0));
BARENTRY.add(new BarEntry(Float.parseFloat(std2), 1));
BARENTRY.add(new BarEntry(Float.parseFloat(std3), 2));
BARENTRY.add(new BarEntry(Float.parseFloat(std4), 3));
BARENTRY.add(new BarEntry(Float.parseFloat(std5), 4));
BARENTRY.add(new BarEntry(Float.parseFloat(std6), 5));
}
public void AddValuesToBarEntryLabels(){
BarEntryLabels.add("January");
BarEntryLabels.add("February");
BarEntryLabels.add("March");
BarEntryLabels.add("April");
BarEntryLabels.add("May");
BarEntryLabels.add("June");
}
}
According to the wiki of the Github Link, you need to refresh the bar chart after data is set.
try
//call method to use information in barGraph
AddValuesToBARENTRY (std1, std2, std3, std4, std5, std6);
// refresh the bar chart
chart.invalidate();

How to parse JSON using volley library android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I parsed JSON response using Volley library as done in this video. But I am getting an error. The error is:
E/VOLLEY: ERROR
Can somebody help me, please? I don't know what the problem is.
EDIT: Added code
package com.example.hello.Project;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Activity1 extends Activity {
Button start;
TextView textView;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
start = (Button) findViewById(R.id.btn);
textView = (TextView) findViewById(R.id.textView2);
requestQueue = Volley.newRequestQueue(this);
start.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://example.com/abc.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("abc");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject student = jsonArray.getJSONObject(i);
String a= student.getString("a");
String b= student.getString("b");
String c= student.getString("c");
String d= student.getString("d");
textView.append(a+" \n"+b+" \n"+c+" \n "+d+" \n");
}
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
});
}
}
This is the code.
This isn't going to fix your problem, but it will tell you what's going wrong.
Change
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}
to
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}
This way it will actually say what the error is, not just "ERROR".
The conclusion was that the sample JSON was invalid and therefore not being read in correctly.
Further to #TJ_'s answer you also need to add comma's between each attribute.
You had (which is invalid):
{
"buli1617sp": [
{
name: "Embolo"
vereine: "Von Basel zu Schalke"
geld: "29 Mio Euro"
datum: "01.08.2016"
},
{
name: "Coke"
vereine: "Von Sevilla zu Schalke"
geld: "4 Mio Euro"
datum: "02.08.2016"
},
{
name: "Bentaleb"
vereine: "Von Basel zu Schalke"
geld: "Leihe mit Kaufoption über 19 Mio Euro"
datum: "03.08.2016"
}
]
}
The correct JSON:
{
"buli1617sp": [
{
"name": "Embolo",
"vereine": "Von Basel zu Schalke",
"geld": "29 Mio Euro",
"datum": "01.08.2016"
},
{
"name": "Coke",
"vereine": "Von Sevilla zu Schalke",
"geld": "4 Mio Euro",
"datum": "02.08.2016"
},
{
"name": "Bentaleb",
"vereine": "Von Basel zu Schalke",
"geld": "Leihe mit Kaufoption über 19 Mio Euro",
"datum": "03.08.2016"
}
]
}
When working with JSON I suggest using an online JSON parser such as this to verify the JSON is correctly formatted.

Categories

Resources