I'm trying to retrieve the JSON from an API but I'm not getting anything.
The JSON :
{"coord":{"lon":90.41,"lat":23.71},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50n"}],"base":"stations","main":{"temp":25,"feels_like":28.6,"temp_min":25,"temp_max":25,"pressure":1011,"humidity":83},"visibility":3500,"wind":{"speed":1.5,"deg":90},"clouds":{"all":75},"dt":1588093825,"sys":{"type":1,"id":9145,"country":"BD","sunrise":1588029983,"sunset":1588076702},"timezone":21600,"id":1185241,"name":"Dhaka","cod":200}
I did add INTERNET permission :
<uses-permission android:name="android.permission.INTERNET" />
My code :
private void httpGet() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
Log.d("TEST", "Fonction lancee 1/2" + url);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TEST", "Fonction lancee 3/2" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TEST", "Erreur");
}
});
queue.add(jsonObjectRequest);
}
I also tested with StringRequest with the same result, no response.
EDIT
My entire classe to see the context :
public class MainActivity extends AppCompatActivity {
TextView tempTxt;
String CITY = "dhaka,bd";
String API = "5694263c8d821570bfccff2a13246a73";
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTxt = findViewById(R.id.tempTxt);
httpGet();
//new weatherTask().execute();
Log.d("TEST", "TEST OUT CALL");
Button button2 = findViewById(R.id.definirp);
button2.setOnClickListener(new View.OnClickListener() {
//Passer a la seconde Activity
public void onClick(View v) {
Intent activity2 = new Intent(getApplicationContext(), Activity2.class);
startActivity(activity2);
finish();
}
});
//Affichage de l'heure
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView theure = (TextView) findViewById(R.id.date);
TextView tdate = (TextView) findViewById(R.id.heure);
long date = System.currentTimeMillis();
//Format de l'heure
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat sdfDate = new SimpleDateFormat("MMM dd yyyy");
String timeString = sdfDate.format(date);
String dateString = sdfTime.format(date);
theure.setText(timeString);
tdate.setText(dateString);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
private void httpGet() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
// 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) {
// Display the first 500 characters of the response string.
tempTxt.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tempTxt.setText("That didn't work!");
}
});
queue.add(stringRequest);
}
You can test the page of my JSON, the address is in comment in my code, (there is a comma in the city), it works.
Related
I'm new to android development. I'm trying to send some data to server using volley. But it is not sending parameters. Please help. The server is saying that the parameter is not set. I checked with the isset in php. When I tried sending data from a html form, it's working. But the volley is not sending the parameters.
public class MainActivity extends AppCompatActivity {
EditText uname;
EditText uotp;
RequestQueue myqueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText) findViewById(R.id.uname);
uotp = (EditText) findViewById(R.id.uotp);
myqueue = Volley.newRequestQueue(this);
}
public void sendotp(View v)
{
String unameval = uname.getText().toString();
if(unameval.matches(""))
{
Toast.makeText(getApplicationContext(), "Enter Phone Number", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, String> params = new HashMap<>();
params.put("phone", unameval);
String myUrl = "http://privateurlhere";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, myUrl, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String dispname = response.getString("stat");
Toast.makeText(getApplicationContext(), dispname, Toast.LENGTH_SHORT).show();
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Resp err" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
myqueue.add(request);
}
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
TextView price;
String url = "https://koinim.com/ticker/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn_get_information);
price = (TextView)findViewById(R.id.price);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId() == R.id.btn_get_information){
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString("sell")+ " " + "₺" );
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()),"Error",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
}
}
I am a new developer in android.
I looked at the sources and made the parse from one link. But I have four links. How do I parse the four links?
Instead of having a String url, create an ArrayList of Strings that holds all your URLs.
In the method onClick() loop through the URLs.
Note that the ArrayList is filled in onCreate. I also added a try/catch clause in onClick, so if something goes wrong with one URL, the others will be parsed anyways.
Handling different URLs:
For parsing the Koinim ticker, you needed the key "sell", for Paribu you will need "last".
In the loop I am checking if the URL contains either Koinim or Paribu and adjust they key accordingly.
ArrayList<String> urls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_get_information);
price = (TextView) findViewById(R.id.price);
urls.add("https://koinim.com/ticker/");
urls.add("url2");
urls.add("url3");
urls.add("url4");
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_get_information) {
for (String url : urls) {
try {
JsonObjectRequest request = null;
if(url.contains("koinim"))
{
request = getSellPrice("sell");
}
else if(url.contains("paribu"))
{
request = getSellPrice("last");
}
if(request != null)
{
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
} catch (Exception ex) {
// something went wrong, handle exception here
}
}
}
}
private JsonObjectRequest getSellPrice(String key)
{
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString(key) + " " + "₺");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()), "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
return jsonObjectRequest;
}
My app has a list and a button to add element to the list and reload it in the same activity, when pressing the button I need to reload the activity without blinking or time of reloading Like when you send message in messenger.I try the following code:
recreate()
tvSender.setText("");
And this code :
Intent intent = getIntent();
finish();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
This works but it's still not what i want exact any help pls
the full code :
public class ChatRoom extends AppCompatActivity {
String username;
String username1;
TextView userroom;
String image1;
Message_adapter adapter;
ListView L_MESSAGES;
ArrayList<Messages> messages= new ArrayList<Messages>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Intent intent = getIntent();
username = intent.getStringExtra("username");
username1 = intent.getStringExtra("username1");
userroom =(TextView) findViewById(R.id.userroom);
final EditText tvSender =(EditText) findViewById(R.id.Sender);
final ImageButton btSender=(ImageButton)findViewById(R.id.btSender);
final ImageButton btBack=(ImageButton)findViewById(R.id.back);
btBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatRoom.this, ChatActivity.class);
intent.putExtra("username", username);
intent.putExtra("username1", username1);
ChatRoom.this.startActivity(intent);
}
});
btSender.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
getsendMessages();
}
private void getsendMessages(){
String url =config_message.DATA_URL1+username+"&username1="+username1;
userroom.setText(username1);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJsonFriend(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(ChatRoom.this,volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJsonFriend(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config_message.JSON_ARRAY);
JSONObject collegeData =null;
messages.clear();
for(int i=0;i<result.length();i++) {
collegeData = result.getJSONObject(i);
String friend = collegeData.getString(config_message.KEY_SENDER);
image1 = collegeData.getString(config_message.KEY_IMAGE);
String time = collegeData.getString(config_message.KEY_Time);
String sender = collegeData.getString(config_message.KEY_Sender);
messages.add(new Messages(friend,image1,time,sender));
}
} catch (JSONException e) {
e.printStackTrace();
}
L_MESSAGES=(ListView) findViewById(R.id.chatRoomsList);
adapter = new Message_adapter(this,messages);
L_MESSAGES.setAdapter(adapter);
L_MESSAGES.setSelection(L_MESSAGES.getAdapter().getCount()-1);
}
}
this the button to refresh list:
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
There is no need to restart whole Activity. Instead you can insert an element in your list dataset(ArrayList<> or something) and call adapter.notifyDataSetChanged() to make the changes in listview.
I am fetching json data through Volley. The problem I am having
is that Volley's onResponse is never called, and hence the data are not parsed and displayed.
Sample JSON data
{
"title": "This is a sample text title title",
"cat": {
"origin" : "United states",
"target" : "Asia",
},
"content": "Lorem ipsum ipsum trxt hag jlak jshss jsyts pjqgq uuqtyq usiuqjo uwywh",
}
NewsActivity
public class NewsDetails extends AppCompatActivity {
private final String TAG = "NewsDetails";
private ProgressDialog mProgresscircle;
TextView newsTitle, newsOrigin, newsContent;
//private int news_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsOrigin = (TextView) findViewById(R.id.dnews_origin);
newsContent = (TextView) findViewById(R.id.dnews_content);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to load newss
loadNews();
} else {
final Context context;
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_titl);
alertDialog.setCancelable(false);
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage(R.string.failed_news);
alertDialog.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialog.show();
} else {
loadNews();
}
}
});
alertDialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
}
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DetailConfig.GET_DURL + news_id,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called NewsDetails");
//Dismissing progressbar;
if (mProgresscircle != null) {
mProgresscircle.dismiss();
}
//Calling method to parse json array
parseNews(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
//This method will parse json data of news
private void parseNews(JSONArray jsonArray) {
Log.d(TAG, "Parsing news array");
for (int i = 0; i<jsonArray.length(); i++) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
newsTitle.setText(title);
JSONObject pOrigin = jsonObject.getJSONObject("cat");
String origin = pOrigin.getString("origin");
newsOrigin.setText(origin);
String content = jsonObject.getString(DetailConfig.TAG_DPOST_CONTENT);
newsContent.setText(content);
} catch (JSONException w) {
w.printStackTrace();
}
}
}
}
The things I know
In logcat, loadNews method is called.
I'm logging Volley, and from logcat volley is not complaining in anyway
I can't see "onResponse called NewsDetails" in logcat, meaning that for some reason not known to me, it's not called
So, my question is why is onResponse not called and how should I fix it?
You should use JsonObjectRequest instead of JsonArrayRequest because you are getting jsonobject in the response.
For getting more knowledge you may go through Volley tutorial
/* you are getting json in response but your response listener method is get Json Array replace your code with below code and also add an debug point in your error listener method */
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
// or replace this code into your into your loadNews method
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
**
You can also refer below link for complete tutorial http://www.hackpundit.com/android-turorial-json-parse-volley/
**
all.
I am using volley to make a http request to my website server. And it works fine and response when click the commit button to add a request to request queue. But click the button again does not response. It still shows the progressdialog and response nothing. Is there something wrong ?
Here's code example below:
public class MainActivity extends ActionBarActivity {
private static final String URL = "http://www.google.com";
public RequestQueue mQueue = null;
public StringRequest request = null;
private Button mScanButton = null;
private TextView mDisplay = null;
private ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScanButton = (Button) findViewById(R.id.button_scan);
mDisplay = (TextView) findViewById(R.id.display);
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response retrieved");
mDisplay.setText(response);
dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mDisplay.setText("That didn't work.");
dialog.dismiss();
}
});
request.setShouldCache(false);
mScanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Mapping data", "please wait..");
mQueue = Volley.newRequestQueue(MainActivity.this);
mQueue.add(request);
System.out.println("Add to queue..");
}
});
}
try this May this guide you here is the complete source which helps you understand easily.
looking at this line
if (ServerConfig.isNetworkOnline(SplashScreen.this)) {
StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
};
AppController.getInstance().getRequestQueue().add(strReq);
} else {
Toast.makeText(getApplicationContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();
finish();
}
you can remove those above code leaving with below code.
StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
};
AppController.getInstance().getRequestQueue().add(strReq);
I try to move the area of request declaration to on-click method and it works fine. But I still don't understand how it works.
public class MainActivity extends ActionBarActivity {
private static final String URL = "http://www.google.com";
public RequestQueue mQueue = null;
public StringRequest request = null;
private Button mScanButton = null;
private TextView mDisplay = null;
private ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScanButton = (Button) findViewById(R.id.button_scan);
mDisplay = (TextView) findViewById(R.id.display);
mScanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Mapping data", "please wait..");
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response retrieved");
mDisplay.setText(response);
dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mDisplay.setText("That didn't work.");
dialog.dismiss();
}
});
mQueue = Volley.newRequestQueue(MainActivity.this);
mQueue.add(request);
System.out.println("Add to queue..");
}
});
}