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!
Related
people so I have a valid URL with JSON data in it, I pull the data with volley but it's not working for some reason, when I change the URL it works. But I need to use this URL with this data in my project. I think the structure of the URL is the problem, but I don't know how to fix it, Please help. Thank you!
The URL I am using is https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk
public class TestOne extends AppCompatActivity {
String url = "https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk";
RecyclerView recyclerView;
PonudiAdapter adaptor;
ArrayList<Ponudi> ponudis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_one);
switchSve = findViewById(R.id.switch1);
recyclerView = findViewById(R.id.testRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adaptor = new PonudiAdapter(getApplicationContext());
recyclerView.setAdapter(adaptor);
ponudis = new ArrayList<>();
getData("1");
switchSve.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
getData("sve");
} else {
getData("1");
}
}
});
private void getData(final String Sport) {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals(Sport)) {
ponudis.add(ponudi);
} if (Sport.equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
}
In response you are getting below error.
"javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found."
I found some answers here is reference that will help you.
Trusting all certificates using HttpClient over HTTPS
Replace getData() Method
Write This method -
private void getData() {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals("1")) {
ponudis.add(ponudi);
} else if(ponudi.getSh_sport_id().equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
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);
}
i am getting below error
setOnRefreshListener
(android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener)
in SwipeRefreshLayout cannot be applied
to
(in.com.goalert.activity.MainActivity)
at
swipeRefreshLayout.setOnRefreshListener(this);
full code is below
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private SessionManager pref;
private SQLiteHandler db;
private ListView listView;
private FeedListAdapter listAdapter;
public static List<FeedItem> feedItems =new ArrayList<>();
private SwipeRefreshLayout swipeRefreshLayout;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
static int count = 0;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pref = new SessionManager(getApplicationContext());
db = new SQLiteHandler(getApplicationContext());
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
public void onRefresh() {
Log.i("onRefresh","onRefresh");
fetchfeed();
}
private void fetchfeed() {
Log.i("fetchfeed","fetchfeed");
String URL_FEED = "http://www.goalert.in/feed/engineering.json";
swipeRefreshLayout.setRefreshing(true);
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Response",response.toString());
if (response != null) {
swipeRefreshLayout.setRefreshing(false);
parseJsonFeed(response);
}
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonReq);
// Adding request to volley request queue
//AppController.getInstance().addToRequestQueue(jsonReq);
// showing refresh animation before making http call
}
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
You can try to use below code for swipeRefreshLayout This code is work for me.
Here is SwipeRefreshLayout XML code snippiest.
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:divider="#null"
android:dividerHeight="0dp" />
</android.support.v4.widget.SwipeRefreshLayout>
Here is the java code snippiest look like as per your requirement or code
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
try {
onRefresh();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 3000);
}
});
// user defined on-refresh method
private void onRefresh() {
Log.i("onRefresh","onRefresh");
fetchfeed();
}
private void fetchfeed() {
Log.i("fetchfeed","fetchfeed");
String URL_FEED = "http://www.goalert.in/feed/engineering.json";
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Response",response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonReq);
}
Remains you can use your code as per your requirement.
I suggest to try to use this solution. It will work
you have to implement the MainActivity with android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener
my problem is solved by
doing
implements SwipeRefreshLayout.OnRefreshListener
I am using Volley Library for getting response from server.
Response get successfully earlier but now suddenly not getting response.
I don't know, What is the problem in my code?
My code is,
public static void makeJsonData(final Activity activity, final String topic_id, final String user_id) {
context = activity;
dbAdapter = new DBAdapter(context);
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
showpDialog();
JSONObject params = new JSONObject();
try {
params.put("topic_id", topic_id);
params.put("user_id", user_id);
params.put("action", "getquestions");
System.out.println("!!!!!!!!!params======"+params);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
Url.URL, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
Boolean resultFlag = response.getBoolean("resultFlag");
if (resultFlag == true) {
String success = response.getString("successMessage");
JSONArray json_array_question = response.getJSONArray("Questions");
for (int i = 0; i < json_array_question.length(); i++) {
JSONObject json_object_question = json_array_question.getJSONObject(i);
quiz_id = json_object_question.getInt("QuizID");
question_type = json_object_question.getString("questionType");
time_required = json_object_question.getString("timeRequired");
}
} else if (resultFlag == false) {
String error = response.getString("errorMessage");
Toast.makeText(activity.getApplicationContext(), error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(activity,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(activity,
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
private static void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private static void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
And Response is,
{
"resultFlag": true,
"successMessage": "Data Received",
"Questions": [
{
"QuizID": 958,
"questionType": "Trivia",
"timeRequired": "10",
}
]
}
Please suggest me.
Thanks.
// follow this sample code step by step
public class MainActivity extends Activity {
TextView output ;
String loginURL=""; // your URL
String data = "";
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState!=null){
Log.d("STATE",savedInstanceState.toString());
}
requestQueue = Volley.newRequestQueue(this);
output = (TextView) findViewById(R.id.jsonData);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray ja = response.getJSONArray("posts");
for(int i=0; i < ja.length(); i++){
JSONObject jsonObject = ja.getJSONObject(i);
// int id = Integer.parseInt(jsonObject.optString("id").toString());
String title = jsonObject.getString("title");
String url = jsonObject.getString("URL");
data += "Blog Number "+(i+1)+" \n Blog Name= "+title +" \n URL= "+ url +" \n\n\n\n ";
}
output.setText(data);
}catch(JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error");
}
}
);
requestQueue.add(jor);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am using volley library to fetch json array via POST request. when I use get method am able to fetch the desired values but when I use POST method am unable to fetch any value instead am getting this error
value of type org.json.jsonobject cannot be converted to jsonarray
Here is my code
public class xyz extends Activity {
private static final String url = "http://example.com/q.php";
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.listview_main);
listView = (ListView) findViewById(R.id.listview);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError errorResponce)
{
VolleyLog.d( "Error: " + errorResponce.getMessage());
hidePDialog();
}
};
Response.Listener<JSONArray > jsonArrayListener = new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// TODO Auto-generated method stub
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("ttl"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
};
Map<String, String> mParam = new HashMap<String, String>();
mParam.put("q", "ram");
PostJsonArrayRequest req = new PostJsonArrayRequest(Request.Method.POST, url , null, jsonArrayListener, errorListener,mParam);
// Creating volley request obj
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
// Adding request to request queue
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
private Map<String,String> mParam;
private Response.Listener<JSONArray> mListener;
public PostJsonArrayRequest(int method, String url, String requestBody,
Response.Listener<JSONArray> listener, Response.ErrorListener errorListener,Map param) {
super(method, url, requestBody, listener, errorListener);
mListener=listener;
mParam=param;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return mParam;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONArray response) {
mListener.onResponse(response);
}
}
}
please guide me where am making the mistake. am i passing the params correctly?