How to get response using Volley Library in android? - android

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);
}
}

Related

How to set JSON Array values to seter class in Android Studio with volley

I'm trying to display my row tables on the database in my ListView , However I dont know how to convert JSONObject to JSONArray and set it to my setter class. I get my JSON through Volley String Request
I have the JSON output like this :
{
"error": false,
"message": "Status Fetched",
"status": [
{
"OrderCode": "5x2azu",
"GuestName": "Try",
"ProductName": "Mie Ayam Super Jumbo Komplit",
"ProductType": "Kuah",
"NoTable": 4,
"Status": "Disiapkan",
"TotalPrice": "58000"
},
{
"OrderCode": "etent3",
"GuestName": "Try",
"ProductName": "Nasi Soto Daging Sapi",
"ProductType": "Soto",
"NoTable": 4,
"Status": "Disiapkan",
"TotalPrice": "27000"
},
{
"OrderCode": "ro1eyx",
"GuestName": "Try",
"ProductName": "Mie Ayam Original",
"ProductType": "Kuah",
"NoTable": 4,
"Status": "Disiapkan",
"TotalPrice": "23000"
}
]
}
and here is my String Request :
public void StringRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.STATUS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting Status from response
JSONObject statusJson = obj.getJSONObject("status");
Status status = new Status(
statusJson.getString("OrderCode"),
statusJson.getString("GuestName"),
statusJson.getString("ProductName"),
statusJson.getString("ProductType"),
statusJson.getString("NoTable"),
statusJson.getString("Status"),
statusJson.getString("TotalPrice")
);
} else {
Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("tablecode",TableCode);
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
}
I dont know how to convert it from JSONObject to JSONArray
here is my Setter and getter class
package com.example.pesanpalgading20.Getter.Status;
import java.util.ArrayList;
public class Status {
private String OrderCode,Name,FoodName,TypeFood,NoTable,Status,TotalPrice;
public Status(){
}
public Status(String orderCode, String name, String foodName, String typeFood, String noTable, String status, String totalPrice) {
OrderCode = orderCode;
Name = name;
FoodName = foodName;
TypeFood = typeFood;
NoTable = noTable;
Status = status;
TotalPrice = totalPrice;
}
public String getOrderCode() {
return OrderCode;
}
public void setOrderCode(String orderCode) {
OrderCode = orderCode;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getFoodName() {
return FoodName;
}
public void setFoodName(String foodName) {
FoodName = foodName;
}
public String getTypeFood() {
return TypeFood;
}
public void setTypeFood(String typeFood) {
TypeFood = typeFood;
}
public String getNoTable() {
return NoTable;
}
public void setNoTable(String noTable) {
NoTable = noTable;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getTotalPrice() {
return TotalPrice;
}
public void setTotalPrice(String totalPrice) {
TotalPrice = totalPrice;
}
}
so how do I set the value of the each JSON to SetterandGetter class ?
try {
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
//getting Status from response
JSONArray statusJson = obj.getJSONArray("status");
for (int i = 0; i < statusJson.length(); i++) {
Status status = new Status(
statusJson.getJSONObject(i).getString("OrderCode"),
statusJson.getJSONObject(i).getString("GuestName"),
statusJson.getJSONObject(i).getString("ProductName"),
statusJson.getJSONObject(i).getString("ProductType"),
statusJson.getJSONObject(i).getString("NoTable"),
statusJson.getJSONObject(i).getString("Status"),
statusJson.getJSONObject(i).getString("TotalPrice")
);
// Add Status In your Array list and enjoy
}
} else {
Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
You can use Gson library and convert your json to a model class
To do it first you have to add gson as a dependancy
implementation "com.google.code.gson:gson:2.8.6"
And then since your status in json is array use it like this
JSONArray status = obj.getJSONArray("status");
//Code to convert json array to arraylist of object
Arraylist<Status> arraylist = Gson().fromJson(
status.toString(),
new TypeToken<ArrayList<Status>>(){}.getType()
)
Above code will store your json array status to arraylist variable
so the gettin JSON array is completed but it still display one list from the array this is the code
public void StringRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.STATUS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting Status from response
JSONArray statusJson = obj.getJSONArray("status");
for (int i = 0; i < statusJson.length(); i++) {
Status status = new Status(
statusJson.getJSONObject(i).getString("OrderCode"),
statusJson.getJSONObject(i).getString("GuestName"),
statusJson.getJSONObject(i).getString("ProductName"),
statusJson.getJSONObject(i).getString("ProductType"),
statusJson.getJSONObject(i).getString("NoTable"),
statusJson.getJSONObject(i).getString("Status"),
statusJson.getJSONObject(i).getString("TotalPrice")
);
ArrayList<Status> statusList = new ArrayList<Status>();
statusList.add(status);
statusAdapter = new StatusAdapter(getActivity(),statusList);
StatusListView.setAdapter(statusAdapter);
}
} else {
Toast.makeText(getContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("tablecode",TableCode);
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
}
I dont know where to put the increment in the setting adapter in
statusList.add(status);
edit : It solved! Thanks to #Pratik Fagadiya
I put the setting adapter outside of the loop and it worked and added more than 1 list

Volley is not pulling Json data from my URL

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);
}

How to update textview text(server data) with time interval?

I want to update data in Textview text with 5 second interval. The data should comes for server. I call the "handler" with 15000 ms interval.
Problem is few times app crass due to call handler. Please tell me is there any other process to update data with time interval. I am sending the following code which I have used.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if(dataFromLogin.trim().equals("yes"))
{
checkUrlToFetchData(personLoginName);
}
else
{
checkUrlForExtraVideo(latestVideoID);
checkUrlToFetchDataCreaterLogin(personLoginName);
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 15000);
=============================
void checkUrlToFetchData(final String useridt)
{
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/notifications/index";
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v( "response:",response);
try {
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
if(success == true)
{
JSONArray notifications = jsonObj.getJSONArray("notifications");
if(notifications.length()>0)
{
JSONObject jo= notifications.getJSONObject(0);
createNotification(jo.getString("message"));
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id",userIdfromLogin);
return params;
}
};
queue.add(stringRequest);
}
void checkUrlToFetchDataCreaterLogin(final String useridt)
{
//Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/LiveNotifications/index";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
//progressDialog.dismiss();
//Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();
Log.v( "response:",response);
try {
//Log.v( "try:","1");
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
String profileimages="",profileimages1="",profileimages2="",profileimages3="",profileimages4="",profileimages5="";
if(success == true)
{
JSONArray notifications = jsonObj.getJSONArray("LiveNotifications");
if(notifications.length()>0)
{
JSONObject jo= notifications.getJSONObject(0);
createNotification(jo.getString("message"));
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id",userIdfromLogin);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
void checkUrlForExtraVideo(final String checkUrlForExtraVideo)
{
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/user-videos/newvideo";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
//progressDialog.dismiss();
//Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();
Log.v( "response:",response);
try {
//Log.v( "try:","1");
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
if(success == true)
{
int newVideo = jsonObj.getInt("newVideo");
if(newVideo>0)
{
getResourceUriRecyclerViewtruenew(swipeRefreshLayout);
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("video_id",latestVideoID);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
If you want to do some task for every 5 seconds , You can use
Handler handler = new Handler();
new Runnable()
{
#Override
public void run() {
//do your task
handler.postDelayed(this, 5000);
}
}.run();
You can try this for the 5-second timer
private Handler mCountdownHandler;
private final static int INTERVAL = 5 * 1000;
private Runnable mTimer = new Runnable() {
#Override
public void run() {
// Do something
...
...
// Reschedule the timer to execute after 5 seconds
mCountdownHandler.postDelayed(this, INTERVAL);
}
};
private void startTimer() {
stopTimer();
mCountdownHandler = new Handler(getMainLooper());
mCountdownHandler.post(mTimer);
}
private void stopTimer() {
if (mCountdownHandler != null) {
mCountdownHandler.removeCallbacks(mTimer);
mCountdownHandler = null;
}
}
Don't forget to free the handler when you destroy the activity
#Override
protected void onDestroy() {
super.onDestroy();
stopTimer();
}

How to apply setText() to onclicked item in Recyclerview android

I wanna upadate recyclerview child item when itself clicked.It takes the data from server and updates it self. kindly provide any solution for this scenario.Here i have tried as i know but it is not updating.
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
SQLiteHandler db = new SQLiteHandler(context);
HashMap<String, String> user = db.getUserDetails();
String tag_string_req = "req_login";
final String uid = user.get("uid");
Log.d("hello", uid);
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.Upvote, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String upvote_no = jObj.getString("upcount");
String text = "Upvoted " + upvote_no;
((TextView) v).setText(text);
//Log.d("resp", upvote);
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(context, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("qries_user_id", uid);
params.put("qries_answer_id", answered_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
});
In the above code i am trying to taking response from Json and updating to self child item as ((TextView) v).setText(text); but it is not updating.Thanks in Advance!
Try to cast your clicked view in TextView
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) v).setText("something");
}
});

Consuming APIs with volley?

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!

Categories

Resources