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.
Related
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
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
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
Please help me understand where i'm going wrong.!! I want to parse the json
objects only. But couldn't able to figure it out. The json consists of nested objects.
JSON Format
{"-3fsdfsdfsfsd3":{"abbreviation":"CC","level":"High
School","name":"Catholic
Central","picUrl":"https://firebasestorage.googleapis.com/v0/b/minihm-
584e8.appspot.com/o/cc.png?alt=media&token=2ff31f9e-90cf-45a8-b39c-
00c2ae932cba","uuid":"-3fsdfsdfsfsd3"},"-Kbhx1WaxclQwu56Hrb1":
{"abbreviation":"DC","level":"High School","name":"Divine
Child","picUrl":"https://firebasestorage.googleapis.com/v0/b/minihm-
584e8.appspot.com/o/dc.png?alt=media&token=14b4ebad-c017-46b5-89ec-
86e4c0d0edd3","uuid":"-Kbhx1WaxclQwu56Hrb1"},
The json structure consists of nested objects. and has no
array structure. **
**Mainactivity
public class MainActivity extends Activity {
**// Log tag**
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url =**json url goes here**
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
//Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
**// Creating volley request obj**
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json ( Edited with the previous post )
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonObject1 = jsonObject.getJSONObject("-3fsdfsdfsfsd3");
Movie movie = new Movie();
movie.setName(jsonObject1.getString("name"));
movie.setThumbnailUrl(jsonObject1.getString("picUrl"));
movie.setLevel(jsonObject1.getString("level"));
movieList.add(movie);
}
// adding content to model array
} 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
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
**LOGCAT ERRORS:**
07-19 22:29:50.321 4921-4921/com.manojgudihal.example D/Volley: [1]
2.onErrorResponse: MainActivity
Please help.!!
Parsing JsonObject try below like this..,
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonObject1 = jsonObject.getJSONObject("3fsdfsdfsfsd3");
Movie movie = new Movie();
movie.setName(jsonObject1.getString("name"));
movie.setThumbnailUrl(jsonObject1.getString("picUrl"));
movie.setLevel(jsonObject1.getString("level"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
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();
}
}
});
}
}
I have been struggling to understand the logic of the Android JSON Parsing with volley libraries.I am trying to get JSON Array and parse with Volley Libraries.I understand how JSON data is extracted from PHP file but I have big problems. makeJsonArrayRequest() function runs correctly and parse JSON Array from get_data.php file and add users ArrayList from User class in each iteration.I called this function in onCreate and userLogin function individually.Size of users ArrayList equals to 0 when I call makeJsonArrayRequest() function in onCreate method .However,Size of users ArrayList equals to nonzero number when I call makeJsonArrayRequest() function in userLogin method(This method called when clicked on Login Button).This is my problem.Why makeJsonArrayRequest() doesn't run on Create() method ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET_NAME = (EditText) findViewById(R.id.user_name);
ET_PASS = (EditText) findViewById(R.id.user_pass);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
makeJsonArrayRequest();
Toast.makeText(getApplicationContext(),"Size:" + users.size(),Toast.LENGTH_LONG).show();
}
public void userLogin(View view) {
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
String status = "1";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method, login_name, login_pass, status);
Intent i = new Intent(this,MapsActivity.class);
i.putExtra("username",login_name);
i.putExtra("userpass", login_pass);
makeJsonArrayRequest();
startActivity(i);
Toast.makeText(getApplicationContext(),"Size:" + users.size(),Toast.LENGTH_LONG).show();
}
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse ="";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String name = person.getString("name");
String username = person.getString("username");
String password = person.getString("password");
double latitude = Double.parseDouble(person.getString("latitude"));
double longitude = Double.parseDouble(person.getString("longitude"));
String status = person.getString("status");
User user = new User(name,username,password,latitude,longitude,status);
users.add(user);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
If what you're saying is :
I run the request in onCreate() and check - it's empty.
and then:
I run it again LATER, and Check - it's full.
then have you considered the request latency? it takes time (albeit - not much time) for the request to return, you might be checking before it does
EDIT:
Run what you want inside the onResponse(), that's only called when the request returns.
Hope this helps.