Volley onResponse android not work - java

MainActivity:
RequestQueue requestQueue;
String url = "http://andriodtest.eb2a.com/show.php";
TextView textView;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = response.getJSONArray("users");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String info = respons.getString("name");
textView.append(id);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
When run app no data called
And file config is work 100%.
example
And if set Textview= "text" not work.
I think the problem is public void onResponse.
Please help me important

Your code seems fine, however it looks like your server's response is not returning a json object but instead a javascript file for setting a cookie (you can try hitting your url with Postman to look at the javascript response I'm mentioning).
Volley expects to receive a json response and that may be the reason why your app is currently not working as expected.
I would probably try to change the way the server responds. The following link has some suggestions in order to solve that issue:
Why I can't retrieve data from my webserver as json but i can when i test it on localhost

Related

I have been making an News API project in android studio but have volley got error in it. Error- com.android.volley.AuthFailureError. Using json

public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
List<news_Objects> newsList = new ArrayList<>();
//url for News API
String url="https://newsapi.org/v2/everything?q=apple&from=2021-08-31&to=2021-08-31&sortBy=popularity&apiKey=ca3d6c89eff24db2a8ef78868f0af555";
//making json object request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArr = response.getJSONArray("articles");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject newsDetail = jsonArr.getJSONObject(i);
//class name news_Objects created
news_Objects news = new news_Objects();
String imtUrl = newsDetail.getString("urlToImage");
String title = newsDetail.getString("title");
String detail = newsDetail.getString("description");
String newsUrl = newsDetail.getString("url");
String content = newsDetail.getString("content");
news.setNewsImageUrl(imtUrl);
news.setNewsTitle(title);
news.setNewsDetail(detail);
news.setNewsUrl(newsUrl);
news.setContent(content);
newsList.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("fine", "Something Wrong"+error);
Toast.makeText(MainActivity.this, "Something Wrong "+error, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
Your API Key is Invalid please check your API key. Getting this response:
{"status":"error","code":"apiKeyInvalid","message":"Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."}
Maybe Your API key is not live, please check your API key status than again hit the api.

Android JsonArrayRequest onResponse is never executed

this issue has been bugging me all day. I have stepped through the program with the debugger and it never goes into the Response.Listener. It doesn't go into onErrorResponse either so the API isn't throwing an error.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_rewards);
prf = new PrefManager(this);
getSupportActionBar().setIcon(R.drawable.ic_back_icon);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.earning_history);
listView = (ListView) findViewById(R.id.list);
TextView emptyText = (TextView) findViewById(R.id.empty);
emptyText.setText(getString(R.string.no_rewards_yet));
adapter = new UserHistoryAdapter(EarningHistoryActivity.this, historyList);
listView.setAdapter(adapter);
listView.setEmptyView(emptyText);
listView.setDivider(null);
pDialog = new ProgressDialog(this);
pDialog.setMessage(getString(R.string.loading));
pDialog.show();
// changing action bar color
// getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest historyReq = new JsonArrayRequest(Config.Base_Url+"api/earning_history.php?username="+App.getInstance().getUsername(), new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
UserHistory history = new UserHistory();
history.setTitle(obj.getString("type"));
history.setRating(obj.getString("date"));
history.setThumbnailUrl(Config.Base_Url+"images/reward.png");
history.setYear(obj.getString("points"));
//history.setGenre(obj.getString("time"));
historyList.add(history);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(historyReq);
}
Any help would be greatly appreciated.
Edit: I added more code from the entire onCreate method to give some more information to help.
You have created historyReq object of class JsonArrayRequest;
Now there should be some method call inside JsonArrayRequest class which make utilize the Response.ErrorListener() object that you injected inside the historyReq. The injected objected inside historyReq should make use of on onErrorResponse method.
For more info you can see behavior of Anonymous class.

Adapter.notifyDataSetChanged() not working inside onCreate()

I am trying to parse JSON using Volley.
I am using a vector to store parsed data and calling adapter.notifyDataSetChanged() inside onCreate() after filling vector. But no changes are there.
If I am calling adapter.notifyDataSetChanged() inside try-catch block of getData() then it is working fine. Why?
public class MainActivity extends AppCompatActivity{
Vector<Data> ve;
private Adapter adapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=(RecyclerView)findViewById(R.id.main_recycler_view);
ve=new Vector<Data>();
adapter=new Adapter(ve);
RecyclerView.LayoutManager lm=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(lm);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
getData(ve);
adapter.notifyDataSetChanged(); //not working
}
public void getData(final Vector<Data> ve)
{
String url = "https://api.androidhive.info/contacts/";
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String jsonString) {
try
{
JSONObject object = new JSONObject(jsonString);
JSONArray arr = object.getJSONArray("contacts");
int len=arr.length();
JSONObject obj;
for (int i = 0; i < len; i++)
{
obj = arr.getJSONObject(i);
ve.add(new Data(obj.getString("name"), obj.getString("email"));
}
//adapter.notifyDataSetChanged();working
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(),"JSON Parsing Exception",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
}
});
RequestQueue rQueue = Volley.newRequestQueue(this);
rQueue.add(request);
}
}
you cannot do that reason nothing volley used network requests which are designed to be asynchronous in nature , so the network request is put in queue and code continues to execute the notifyadapter changed method . The response to the network call occurs afterwards and add data, you should call that method after data is received by calling it inside volley on response method

string comparison in android / java

I have got a JSON response from an API that I have converted to a string and trying to compare it for true or false value,
On the log cat I can see the result:
{
"message": "success",
"status": "Auth_Successful",
"response": "Authentication successful"
}
I am trying fit it into an if statement like below
I have tried most of the comparison methods(==, .equals(), .compareTo()) but not getting any result
Can anyone let me know what is the correct way to approach it as I am still new to Java and Android. I have seen a lot of similar posts but unable to figure out.
Thank you very much for your time and assistance in this matter.
package com.example.shiben.fabapp;
public class MainActivity extends AppCompatActivity {
private Request request;
private static final String Tag = MainActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button LoginButton = (Button) findViewById(R.id.loginButton);
EditText userName = (EditText) findViewById(R.id.userName);
EditText userPassword = (EditText) findViewById(R.id.userPassword);
final TextView displayTest = (TextView) findViewById(R.id.displayTest);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "username=xxxxxxxxx&password=xxxxxxxxx");
Request request = new Request.Builder()
.url("http://9.xxx.xxx.xxx/test/xxxxx_api.aspx")
.post(body)
.addHeader("cache-control", "no-cache")
.addHeader("content-type", "application/json")
.build();
//execute the request
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.i(Tag, e.getMessage());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(Tag, response.body().string());
String result = response.body().toString();
//if (result==("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")){
if (result.compareTo("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")==0) {
//if (result.equals("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")) {
TastyToast.makeText(MainActivity.this, "String Comparison Success", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
}
}
});
}
});
}
}
You should parse the JSON string and compare the message.
if (message.equals("success"))
If you don't like to parse, you may try this one (Bad practice):
if(response.contains("success"))
String result = response.body().toString(); doesn't work. Please use string() method instead of toString()
#Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
doSomething(response.body().string());
}
}
private void doSomething(String response) {
}
Try this in your code .
String result = response.body().toString();
if(TextUtils.isEmpty(result)){
Toast.makeText(this, "result is null", Toast.LENGTH_SHORT).show();
return;
}
try {
JSONObject jsonObject = new JSONObject(result);
String message = jsonObject.optString("message");
String status = jsonObject.optString("status");
String response = jsonObject.optString("response");
if (TextUtils.equals("success", message)) {
TastyToast.makeText(MainActivity.this, "String Comparison Success", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
}
} catch (JSONException e) {
e.printStackTrace();
}
The problem is related with OkHttp
This is because when you called the following:
Log.i(Tag, response.body().string());
String result = response.body().toString();
String result will be empty because you've already called response.body() in Log. When you called it, it will be emptied.
So, you need to save it to the result before calling it from the log. Something like this:
String result = response.body().toString();
Log.i(Tag, result);
Here from the documentation:
The response body can be consumed only once.
This class may be used to stream very large responses. For example, it
is possible to use this class to read a response that is larger than
the entire memory allocated to the current process. It can even stream
a response larger than the total storage on the current device, which
is a common requirement for video streaming applications.
Because this class does not buffer the full response in memory, the
application may not re-read the bytes of the response. Use this one
shot to read the entire response into memory with bytes() or string().
Or stream the response with either source(), byteStream(), or
charStream().
I used volley instead of okhttp and got it sorted ,
Below is the code
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
private Button btnSendRequest;
private RequestQueue mRequestQueue;
//creating a string request
private StringRequest stringRequest;
private String url = "http://9.xxx.xxx.xxx/test/xxxxxxx.aspx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendRequest = (Button) findViewById(R.id.loginBtn);
btnSendRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//on click of the button send request and print the response
//initializing request queue and string request in sendRequestAndPrintResponse
sendRequestAndPrintResponse();
}
});
}
private void sendRequestAndPrintResponse() {
mRequestQueue = Volley.newRequestQueue(this);
stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, "Success" + response.toString());
String result = response.toString();
TextView displayText = (TextView) findViewById(R.id.displayText);
displayText.setText(result);
if (result.equalsIgnoreCase("{\"message\":\"success\",\"status\":\"Auth_Successful\",\"response\":\"Authentication successful\"}")){
Toast.makeText(getApplicationContext(), "comparison successful", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, error.toString());
}
}){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("username", "someone#example.com");
params.put("password", "myPassword");
return params;
}
};
mRequestQueue.add(stringRequest);
}
}
If anyone could let me know what went wrong with okhttp, it would be very helpful for future reference.

Parsing simple json to spinner entries

I've been trying to get into android/java programming and I've been having issues understanding how to properly get the value of this json and parse it into the options to select in a spinner.
My json is like:
["Result1","Result2","Result3"]
My current code is like:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://example.com/jsonfile.json";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
queue.add(stringRequest);
}
What would be the easiest way to get these values (Result1, Result2, Result3, etc.) into the spinner.entries?
Thanks in advance
Try this:
myString.replace("\"]","");
myString.replace("[\"","");
List<String> myList = new ArrayList<String>(Arrays.asList(s.split("\",\"")));
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myList);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
As per my knowledge you are sending json data in the wrong way.
If you want to send an array you have to place a jsonArray object in response with name to access that jsonArray.
Example
"cars":[ "Ford", "BMW", "Fiat" ]
Here, we are sending 3 car name in JsonArray of name "cars".
For accessing those entries:-
for (i in myObj.cars) {
carsArray += myObj.cars[i];
}
You need to make an assync call to get json data. Please refer the following tutorial
Android assync task example
and for parsing json data use Android json parsing example
#Override
public void onResponse(String response) {
//Do something with response
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
array.put(jsonArray.getString(i));
}
}
add this on your activity's OnCreate() metod
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this, array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
and put it
ArrayList<String> array = new ArrayList<String>();
Hello Try this if it may help
public class MainActivity extends AppCompatActivity {
Button btnCall;
final List<String> reviewList = new ArrayList<>();
List<String>resultList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCall=(Button)findViewById(R.id.btnCall);
final String jArrStr="[\"Result1\",\"Result2\",\"Result3\"]";
btnCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
JSONArray jArry=new JSONArray(jArrStr);
for (int i = 0; i < jArry.length(); i++) {
String strArr=jArry.getString(0);
resultList.add(jArry.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}

Categories