I am trying to get urls of songs from a server. I want to get all urls in an arraylist which can be shown in a recycler view in next activity. URLs are correctly received when I try to see them using Toast or log. But when I try to get them as a return result of AsyncTask it shows size = 0 for the arraylist returned. I have followed the answers from this question specially by Blackbelt. But that proved to be of no use. Comments are disabled on that answer. So, here I am posting my question with the modified code. Here is the code I have written.
interface OnFetchUrlsListener
{
public void onUrlsFetched(ArrayList<String> arrayList);
public void onUrlsError(String error);
}
public class SplashScreen extends AppCompatActivity implements OnFetchUrlsListener{
#Override
public void onUrlsFetched(ArrayList<String> arrayList) {
Toast.makeText(this, "result size : "+arrayList.size(), Toast.LENGTH_SHORT).show();
}
#Override
public void onUrlsError(String error) {
}
private static RequestQueue mQueue;
public static ArrayList<String> songsArray ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
songsArray = new ArrayList<String>();
String uri = Uri.parse("https://dee9c999.ngrok.io/audio/data/WebsiteSourceCode/api/all_songs.php/?allsongs=allsongs").toString();
new FetchSongs(this).execute(uri);
}
private class FetchSongs extends AsyncTask<String, String, ArrayList<String>> {
private OnFetchUrlsListener mListener;
public FetchSongs(OnFetchUrlsListener listener){
mListener = listener;
}
#Override
protected ArrayList<String> doInBackground(String... params) {
//some heavy processing resulting in a Data String
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, params[0], null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
songsArray.add(jsonArray.getString(i));
}
}
catch (JSONException e) {
e.printStackTrace();
Log.d("JSON Parse", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(SplashScreen.this, "Load error!!", Toast.LENGTH_SHORT).show();
}
});
mQueue.add(request);
return songsArray;
}
#Override
protected void onPreExecute() {}
#Override
protected void onPostExecute(ArrayList<String> result) {
if(mListener!=null)
{
mListener.onUrlsFetched(result);
}
}
}
}
[Edit]
private ArrayList<String> startHeavyProcessing(String uri) {
final ArrayList<String> result = new ArrayList<String>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, uri, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
result.add(jsonArray.getString(i));
Toast.makeText(SplashScreen.this, jsonArray.getString(i), Toast.LENGTH_SHORT).show();
}
songs_fetched = true;
}
catch (JSONException e) {
e.printStackTrace();
songs_fetched = false;
Log.d("JSON Parse", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(SplashScreen.this, "Load error!!", Toast.LENGTH_SHORT).show();
}
});
mQueue.add(request);
return result;
}
Now, when I try to print result of the function startHeavyProcessing() it is returning an arraylist of size 0 but inside the function it is getting the songs urls perfectly fine.
I've solved Your problem on a different way ...
as usual define this interface
public interface OnFetchUrlsListener {
void onUrlsFetched(ArrayList<String> arrayList);
void onUrlsError(String error);
}
write down a class, say, VolleyCall where volley get request will happen & result/response will be returned using listener
public class VolleyCall {
private String TAG = VolleyCall.class.getSimpleName();
private String mUrl;
private OnFetchUrlsListener mOnFetchUrlsListener;
private ArrayList<String> mSongs;
private RequestQueue mQueue;
public VolleyCall(Context context, String url, OnFetchUrlsListener onFetchUrlsListener) {
mSongs = new ArrayList<>();
mUrl = url;
mOnFetchUrlsListener = onFetchUrlsListener;
mQueue = Volley.newRequestQueue(context);
}
public void parse() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, mUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e(TAG, "_log : onResponse : response : " + response.toString());
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
mSongs.add(jsonArray.getString(i));
}
mOnFetchUrlsListener.onUrlsFetched(mSongs);
} catch (JSONException e) {
Log.e(TAG, "_log : onResponse : JSONException : " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "_log : onErrorResponse : error : " + error.getMessage());
mOnFetchUrlsListener.onUrlsError(error.getMessage());
}
});
mQueue.add(request);
Log.e(TAG, "_log : songsArray_size : " + mSongs.size());
}
}
modify your main activity
public class SplashScreen extends AppCompatActivity implements OnFetchUrlsListener {
private String TAG = SplashScreen.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "https://dee9c999.ngrok.io/audio/data/WebsiteSourceCode/api/all_songs.php/?allsongs=allsongs";
VolleyCall call = new VolleyCall(SplashScreen.this, url, SplashScreen.this);
call.parse();
}
#Override
public void onUrlsFetched(ArrayList<String> arrayList) {
Log.e(TAG, "_log : onUrlsFetched : is_arrayList_null : " + (arrayList == null));
if (arrayList != null) {
Log.e(TAG, "_log : onUrlsFetched : arrayList_size : " + arrayList.size());
}
String file_names = "";
for (String s : arrayList) {
file_names = file_names.concat(s + "\n");
}
TextView tv = findViewById(R.id.text);
tv.setText(file_names);
}
#Override
public void onUrlsError(String error) {
Log.e(TAG, "_log : onUrlsError : " + error);
}
}
Try this, you dont need to return arraylist if you use this, at the end of function arraylist will have all the values
ArrayList<String> result = new ArrayList<>();
private void startHeavyProcessing(String uri) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, uri, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
result.add(jsonArray.getString(i));
}
}
catch (JSONException e) {
e.printStackTrace();
Log.d("JSON Parse", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
Related
This is my MainActivity, I am unable to understand and write the unit test code for this can someone help me by providing reference or the code for this problem.In the main activity I have created the methods to call the API how can I mock the API response and get the unit tests for this.
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private final String Url="https://dev-smartoffice-api.sharpb2bcloud.com/rmi/v1/checkVersion";
IResult mResultCallback = null;
public MainActivity(IResult iResult)
{
this.mResultCallback=iResult;
}
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService.getDataVolley("GETCALL",Url);
mVolleyService = new VolleyService(mResultCallback,this);
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
// mVolleyService.postDataVolley("POSTCALL", "http://localhost/androidphpmysql/registrationapi.php?apicall=login", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String request,JSONObject response) {
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
// return error;
}
};
}
}
These are my interfaces,here there are two interfaces notify-success and notify error with return type void I don't know how to use them for mocking please help me
public interface IResult {
public void notifySuccess(String requestType, JSONObject response);
public void notifyError(String requestType, VolleyError error);
}
This is my volleyservice class
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
JSONObject message;
public VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
})
{
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest( Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
message=response;
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
}){
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
e.printStackTrace();
}
}
}
I am sending server request to handle response and error i have implemented interface. I just want to know how to handle if "mResultCallBack ==null" without editing condition if(mResultCallBack!=null). code are as follow:-
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and code for interface
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (loginSessionManager.isLogin()){
cServerRequest = new CServerRequest(mResultcallBack,mContext);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put(CRequestKey.AGENT_CODE, m_szMobileNumber.trim());// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put(CRequestKey.PIN, m_szEncryptedPassword.trim());// same here as said above
Log.e(TAG,"Request::"+jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String s_szWalletURL = CAPIStorage.IREWARDS_URL + CAPIStorage.WALLET_BALANCE_URL;
cServerRequest.postWalletRequest("POST",s_szWalletURL,jsonObject);
}else {
Log.e(TAG,"Not loggedin");
}
}
});
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
if(jsonObject.getJSONArray.length() == 0) {
System.out.println("JSONArray is null");
}
else{
System.out.println("JSONArray is not null");
//parse your string here
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
}
} catch (Exception e) {
e.printStackTrace();
}
}
how to create a separate class in which define all about volley
and in another activity we directly pass URL,CONTEXT and Get Response...
First create callback interface to get result in Activity
public interface IResult {
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
}
Create a separate class with volley function to response the result through interface to activity
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
}
Then initialize callback interface into main activity
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
Now create object of VolleyService class and pass it context and callback interface
mVolleyService = new VolleyService(mResultCallback,this);
Now call the Volley method for post or get data also pass requestType which is to identify the service requester when getting result back into main activity
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
Final MainActivity
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
IResult mResultCallback = null;
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
}
Find the whole project at following link
https://github.com/PatilRohit/VolleyCallback
JsonParserVolley.java
(A separate class where we will get the response)
public class JsonParserVolley {
final String contentType = "application/json; charset=utf-8";
String JsonURL = "Your URL";
Context context;
RequestQueue requestQueue;
String jsonresponse;
private Map<String, String> header;
public JsonParserVolley(Context context) {
this.context = context;
requestQueue = Volley.newRequestQueue(context);
header = new HashMap<>();
}
public void addHeader(String key, String value) {
header.put(key, value);
}
public void executeRequest(int method, final VolleyCallback callback) {
StringRequest stringRequest = new StringRequest(method, JsonURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
jsonresponse = response;
Log.e("RES", " res::" + jsonresponse);
callback.getResponse(jsonresponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return header;
}
}
;
requestQueue.add(stringRequest);
}
public interface VolleyCallback
{
public void getResponse(String response);
}
}
MainActivity.java
(Code Snippet written in onCreate method)
final JsonParserVolley jsonParserVolley = new JsonParserVolley(this);
jsonParserVolley.addHeader("Authorization", "Your value");
jsonParserVolley.executeRequest(Request.Method.GET, new JsonParserVolley.VolleyCallback() {
#Override
public void getResponse(String response) {
jObject=response;
Log.d("VOLLEY","RES"+jObject);
parser();
}
}
);
parser() is the method where the json response obtained is used to bind with the components of the activity.
you actually missed one parameter in the above VolleyService class. You needed to include, it is,...
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null,new Response.Listener() {
/..../
}
null is the parameter should be included else it gives error
Create Listeners(since they are interface they can't be instantiated but they can be instantied as an anonymous class that implement interface) inside the activity or fragment. And Pass this instances as parameters to the Request.(StringRequest, JsonObjectRequest, or ImageRequest).
public class MainActivity extends Activity {
private static final String URI = "";
// This is like BroadcastReceiver instantiation
private Listener<JSONObject> listenerResponse = new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
// Do what you want with response
}
};
private ErrorListener listenerError = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// Do what you want with error
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Next, create a class that has request and pass this listeners to this class' request method , that's all. I don't explain this part this is same as creating a request object in any tutorials.But you can customize this class as you wish. You can create singleton RequestQueue to check priority, or set body http body parameters to this methods as paremeters.
public class NetworkHandler {
public static void requestJSON(Context context, String url, Listener<JSONObject> listenerResponse, ErrorListener listenerError) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);
Volley.newRequestQueue(context).add(jsonRequest);
}
}
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context)
{
mResultCallback = resultCallback;
mContext = context;
}
//--Post-Api---
public void postDataVolley(String url,final Map<String,String> param){
try {
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPost(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return param;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance(mContext).addToRequestQueue(sr);
}catch(Exception e){
}
}
//==Patch-Api==
public void patchDataVolley(String url,final HashMap<String,Object> param)
{
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PATCH, url, new JSONObject(param),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPatch(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
};
AppController.getInstance(mContext).addToRequestQueue(request);
}
}
public interface IResult {
void notifySuccessPost(String response);
void notifySuccessPatch(JSONObject jsonObject);
void notifyError(VolleyError error);
}
I am parsing a JSON response and when I click a button it updates the text but only on refresh, how do I get it to instantly, and dynamically update the texT??
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
String selectedId = currentQuestions.getString("selected");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
blogs.setSelected(selectedId);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
The only thing I have tried it recalling the jsonarray in my listener
public void OnDown(View view) {
CharSequence IdDownVote = ((TextView) ((RelativeLayout) view.getParent()).getChildAt(1)).getText();
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_DOWN = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
I am trying to consume APIs with the library volley, but i can't because it doesn't show me anything when I run the app.
I think the problem is that the URL API has that in it (json):
{"books":[{"book":{PARAMETERS...}}]}
so I can't access my parameters. Then my URL API doesn't have .json at the end of the URL but I don't think that's the problem.
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://############";
private ProgressDialog pDialog;
private List<Books> booksList = new ArrayList<Books>();
private ListView listView;
private Adapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new Adapter(this, booksList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
//getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest booksReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Books books = new Books();
Books.setTitle(obj.getString("title"));
Books.setPhoto_url(obj.getString("image"));
booksList.add(books);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Controller.getInstance().addToRequestQueue(booksReq);
}
#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;
}
}
My json in the URL API:
{
"books": [
{
"book": {
"title": "namebook",
"photo_url": {
"src": "http://######",
"alt": ""
}
}
}
]
}
So how can I get to show them?
Try using
JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) instead of JsonArrayRequest as your response seems to be JSONObject
Also, there is no such key image in your response
Books.setPhoto_url(obj.getString("image"));
Looking at your JSON response, if you try following code, it should work:
JsonObjectRequest artistReq = new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
if (response.optJSONArray("books") != null) {
JSONArray books = response.getJSONArray("books");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
String title = book.getString("title");
// next K,V pair consist of JSONObject photo_url
JSONObject photoUrl = book.getJSONObject("photo_url");
String photoSrc = photoUrl.getString("src");
String photoAlt = photoUrl.getString("alt");
// use extracted values in your Book object
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Hope it would help!