Items Update on second click - android

I am working on a project in which we enter an email and that is checked with the emails present in different tables of the database. Depending upon tables in which the entered email is present I want to display a list of check boxes in a dialog box on clicking a button. My problem is the names of check boxes get updated only on the second click and on further clicks the order of names change. I am not able to figure out this and spent many hours in same. Please help!
MainActivity.java
public class MainActivity extends AppCompatActivity {
public EditText et;
public Main2Activity act;
private String s;
private String[] st = {"","",""};
private int i,j;
private Boolean x;
private String url1 = "http://192.168.56.1:80/axis/results.json";
private String url2 = "http://192.168.56.1:80/hdfc/results.json";
private String url3 = "http://192.168.56.1:80/sbi/results.json";
private ProgressDialog pDialog;
private static String TAG = MainActivity.class.getSimpleName();
private String[] items= {"","",""};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//mail entered into the edittext
et = (EditText)findViewById(R.id.editText);
j=0;
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// on click
public void makeJsonArrayRequest(View view) {
j=0;
s=et.getText().toString();//email to string
JsonArrayRequest req1 = new JsonArrayRequest(url1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("Axis");
//if present in the table add to list
addItem("AXIS");
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
JsonArrayRequest req2 = new JsonArrayRequest(url2,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)) {
System.out.println("HDFC");
addItem("HDFC");
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
JsonArrayRequest req3 = new JsonArrayRequest(url3,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("SBI");
addItem("SBI");}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(req1);
AppController.getInstance().addToRequestQueue(req2);
AppController.getInstance().addToRequestQueue(req3);
dialogadd();
}
public void addItem(String s)
{
items[j]=s;
j++;
}
public void dialogadd()
{
Dialog dialog;
final ArrayList itemsSelected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select banks you want to connect to: ");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
})
.setPositiveButton("Done!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Your logic when OK button is clicked
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();}
}
here is the log cat
logcat
on first click
on second click
on third click

AppController.getInstance().addToRequestQueue(req1); // this will take some time get data
AppController.getInstance().addToRequestQueue(req2); // even this will take some time get data
AppController.getInstance().addToRequestQueue(req3); //last this also will take some time get data
dialogadd(); // but this is an instant call. which will show the dialog, since previous all three call are pending your data get shown unless they complete.
solution : use below call to show the dialog
JsonArrayRequest req3 = new JsonArrayRequest(url3,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("SBI");
addItem("SBI");}
// use this last call show dialog
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Advice
use Future request in volley, i think wt you need is synchronous call one after another

Related

I have a problem in Fragment Page refresh after dialog is dismiss from adapter of that fragment

My Dialog close
if (status.equals("true")) {
Toast.makeText(context, "" + msg, Toast.LENGTH_LONG).show();
notifyDataSetChanged();
dialog.dismiss();
}
I have used notifyDataSetChanged() but still the Fragment layout is not refreshing or not updating
Adapter.java
holder.txt_payRef_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (orderlistArrayList.get(position).getPaymentStatus().equals("0")) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_payment_reference);
Window window = dialog.getWindow();
window.setLayout(Toolbar.LayoutParams.FILL_PARENT, Toolbar.LayoutParams.WRAP_CONTENT);
final TextView txt_orderId = (TextView) dialog.findViewById(R.id.txt_orderId);
final TextView txt_total_amount = (TextView) dialog.findViewById(R.id.txt_total_amount);
final TextView txt_doPayment = (TextView) dialog.findViewById(R.id.txt_doPayment);
final TextView edtxt_order_referenece_id = (EditText) dialog.findViewById(R.id.edtxt_order_referenece_id);
txt_orderId.setText("Order ID " + orderlistArrayList.get(position).getOrderId());
txt_total_amount.setText("Total Due Amount " + (context.getResources().getString(R.string.Rs)) + orderlistArrayList.get(position).getTotalPrice());
edtxt_order_referenece_id.setText(orderlistArrayList.get(position).getPayRef());
txt_doPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Reference_Id = edtxt_order_referenece_id.getText().toString();
if (!Reference_Id.equalsIgnoreCase("")) {
DoUpdatePaymentRef(orderlistArrayList.get(position).getOrderId(), Reference_Id);
// Toast.makeText(context, "Done!!", Toast.LENGTH_LONG).show();
// dialog.dismiss();
} else {
Toast.makeText(context, "Please Put Order Reference ID!!", Toast.LENGTH_LONG).show();
}
}
private void DoUpdatePaymentRef(String orderId, String reference_id) {
progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.setCancelable(false);
progress.show();
JSONObject params = new JSONObject();
try {
params.put("orderId", orderId);
params.put("payRef", reference_id);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Params orderPayRefUpdate--> " + params.toString());
System.out.println(" URL_orderPayRefUpdate--> " + Constant.orderPayRefUpdate);
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.POST, Constant.orderPayRefUpdate, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String status = "";
progress.dismiss();
System.out.println("orderPayRefUpdate Response -->" + response.toString());
try {
JSONObject objStatus = new JSONObject(response
.toString());
status = objStatus.getString("valid");
String msg = objStatus.getString("msg");
if (status != null && !status.equalsIgnoreCase("")) {
if (status.equals("true")) {
Toast.makeText(context, "" + msg, Toast.LENGTH_LONG).show();
// adapter.notifyDataSetChanged();
dialog.dismiss();
} else {
Toast.makeText(context, "" + msg, Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
progress.dismiss();
e.printStackTrace();
//Toast.makeText(PersonalInfo_QRActivity.this, "e." + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
System.out.println("Error : " + error.toString());
}
});
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(context).getRequestQueue()
.add(jsonArrayRequest);
}
});
dialog.show();
}
}
});
Fragment.java
adapterOrderList = new AdapterOrderList(getActivity(), orderlistArrayList);
adapterOrderList.notifyDataSetChanged();
grid_view_fragment.setAdapter(adapterOrderList);
Once you updated, you should update the values in your orderlistArrayList
For example if you want to update the text that you have entered in this edit text edtxt_order_referenece_id you should get the strign value from the edit text and you should update it in the item position orderlistArrayList.get(position).setPayRef(edtxt_order_referenece_id.getText().toString())
Once you have done you should call the notifyDataSetChanged(); or notifyItemChanged(position);

when i am pressing back button(up button) it is showing "app stopped unfortunately" after using volley

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
but1=(Button)findViewById(R.id.btnlogin);
//
final String Token=getIntent().getExtras().getString("token");
// Toast.makeText(getApplicationContext(),Token, Toast.LENGTH_SHORT).show();
final String firstName=getIntent().getExtras().getString("firstname");
//getting cardview data's
String url =
com.android.volley.toolbox.JsonObjectRequest jsonRequest = new com.android.volley.toolbox.JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
JSONArray obj = response.getJSONArray("result");
int o = obj.length();
Log.v("Length", String.valueOf(o));
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
//listname.add(jsonObject.getString("templateId"));
listehr.add(jsonObject.getString("templateId"));
listdate.add(jsonObject.getString("startTime"));
listtime.add(jsonObject.getString("category"));
// ehrUid.add(jsonObject.getString("ehrUid"));
List<String> compositionUid = new ArrayList<>();
// String startTime = jsonObject.getString("startTime");
// Log.v("startTime",startTime);
}
Log.v("listtime", String.valueOf(listtime.size()));
Log.v("Response", response.toString());
String total = response.getString("total");
Log.v("Total",total);
String result = response.getString("result");
Log.v("Result",result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization",Token);
return headers;
}
};
com.android.volley.toolbox.Volley.newRequestQueue(NavigationActivity.this).add(jsonRequest);
//
You have to send String Values for these two Keys "token","firstname".
final String Token=getIntent().getExtras().getString("token");
final String firstName=getIntent().getExtras().getString("firstname");
If you cant find it send the code snippet of intent in another class.
Punithapriya this is the code for main activity
public class MainActivity extends AppCompatActivity {
TextView t;
private EditText username;
private EditText password;
EditText showPsd;
CheckBox mCbShowPwd;
public Button but1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//login page using json
but1=(Button)findViewById(R.id.btnlogin);
username=(EditText)findViewById(R.id.editText2);
password=(EditText)findViewById(R.id.btnpass);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//validation for login
if(username.getText().toString().length()==0){
username.setError("Username not entered");
username.requestFocus();
}
else if(password.getText().toString().length()==0){
password.setError("Password not entered");
password.requestFocus();
}
//
String url = ;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
Log.v("Hai", response.toString());
String firstName = response.getString("firstName");
Log.v("firstName", firstName);
String organizationList = response.getString("organizationList");
Log.v("organizationList",organizationList);
String token = response.getString("token");
Log.v("token",token);
Toast.makeText(getApplicationContext(),"Logged in Suceessfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,NavigationActivity.class);
i.putExtra("token",token);
i.putExtra("firstname",firstName);
startActivity(i);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
Toast.makeText(getApplicationContext(),"Login Error", Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(MainActivity.this).add(jsonRequest);
}
});
//password
showPsd = (EditText) findViewById(R.id.btnpass);
// get the show/hide password Checkbox
mCbShowPwd = (CheckBox) findViewById(R.id.btnshow);
// add onCheckedListener on checkbox
// when user clicks on this checkbox, this is the handler.
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
showPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
} else {
// hide password
showPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
}
}
});
//
//Textview calling
final TextView regLink=(TextView)findViewById(R.id.register1);
final TextView forLink=(TextView)findViewById(R.id.forgot);
//register
regLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regIntent=new Intent(MainActivity.this,RegisterActivity.class);
MainActivity.this.startActivity(regIntent);
}
});
//forgot
forLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forIntent=new Intent(MainActivity.this,ForgotActivity.class);
MainActivity.this.startActivity(forIntent);
}
});
}
//exit dialog box
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("EHR Store");
builder.setIcon(R.drawable.sd);
builder.setMessage("Do you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

Volley Request Response not working error.getMessage()

I am working on my app, till morning it was working fine. I used volley in my app. suddenly it stopped working . I am not able to send request to server and get response. It goes to onErrorResponse method. Following is my snippet code
private void makeJsonArrayRequestCountry() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( myorderlist_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
placeorderlists=new ArrayList<MyOrderModel>();;
if(response.length() > 0)
{
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyOrderModel movie = new MyOrderModel();
movie.setOrder_Id(obj.getString("orderID"));
movie.setOrder_Name(obj.getString("packDesc"));
movie.setOrder_Imgpath(obj.getString("packImagePath"));
movie.setOrder_Img(obj.getString("packImageName"));
movie.setOrder_date(obj.getString("orderDate"));
movie.setOrder_Status(obj.getString("orderStatus"));
movie.setCancel_Status(obj.getString("isCancelled"));
placeorderlists.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
textcounter.setText("Total Order : "+placeorderlists.size());
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MyOrderListActivity.this);
builder.setMessage("You Have No Order");
String positiveText = getString(android.R.string.ok);
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// positive button logic
Intent intentc=new Intent(MyOrderListActivity.this,OrderActivity.class);
startActivity(intentc);
}
});
String negativeText = getString(android.R.string.cancel);
builder.setNegativeButton(negativeText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}
// Parsing json
rcAdapter = new RecyclerViewAdapterMyorderlist(MyOrderListActivity.this, placeorderlists);
rView.setAdapter(rcAdapter);
// notifying list adapter about data changes
// so that it renders the list view with updated data
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
in my logcat it shows blank message and getting blank toast
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Once check with below code snippet for error.
#Override
public void onErrorResponse(VolleyError error) {
String body;
//get status code here
String statusCode = String.valueOf(error.networkResponse.statusCode));
//get response body and parse with appropriate encoding
if(error.networkResponse.data!=null) {
try {
body = new String(error.networkResponse.data,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//do stuff with the body...
}

Why is Volley's onResponse not called

I am fetching json data through Volley. The problem I am having
is that Volley's onResponse is never called, and hence the data are not parsed and displayed.
Sample JSON data
{
"title": "This is a sample text title title",
"cat": {
"origin" : "United states",
"target" : "Asia",
},
"content": "Lorem ipsum ipsum trxt hag jlak jshss jsyts pjqgq uuqtyq usiuqjo uwywh",
}
NewsActivity
public class NewsDetails extends AppCompatActivity {
private final String TAG = "NewsDetails";
private ProgressDialog mProgresscircle;
TextView newsTitle, newsOrigin, newsContent;
//private int news_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsOrigin = (TextView) findViewById(R.id.dnews_origin);
newsContent = (TextView) findViewById(R.id.dnews_content);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to load newss
loadNews();
} else {
final Context context;
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_titl);
alertDialog.setCancelable(false);
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage(R.string.failed_news);
alertDialog.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialog.show();
} else {
loadNews();
}
}
});
alertDialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
}
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DetailConfig.GET_DURL + news_id,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called NewsDetails");
//Dismissing progressbar;
if (mProgresscircle != null) {
mProgresscircle.dismiss();
}
//Calling method to parse json array
parseNews(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
//This method will parse json data of news
private void parseNews(JSONArray jsonArray) {
Log.d(TAG, "Parsing news array");
for (int i = 0; i<jsonArray.length(); i++) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
newsTitle.setText(title);
JSONObject pOrigin = jsonObject.getJSONObject("cat");
String origin = pOrigin.getString("origin");
newsOrigin.setText(origin);
String content = jsonObject.getString(DetailConfig.TAG_DPOST_CONTENT);
newsContent.setText(content);
} catch (JSONException w) {
w.printStackTrace();
}
}
}
}
The things I know
In logcat, loadNews method is called.
I'm logging Volley, and from logcat volley is not complaining in anyway
I can't see "onResponse called NewsDetails" in logcat, meaning that for some reason not known to me, it's not called
So, my question is why is onResponse not called and how should I fix it?
You should use JsonObjectRequest instead of JsonArrayRequest because you are getting jsonobject in the response.
For getting more knowledge you may go through Volley tutorial
/* you are getting json in response but your response listener method is get Json Array replace your code with below code and also add an debug point in your error listener method */
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
// or replace this code into your into your loadNews method
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
**
You can also refer below link for complete tutorial http://www.hackpundit.com/android-turorial-json-parse-volley/
**

Endless RecyclerView - progress bar are not disappearing

I am using a RecyclerView and fetching objects from an API in batches of ten. For pagination, I use EndlessRecyclerOnScrollListener and following this tutorial Endless RecyclerView. My problem: on scrolling programm adding progress bar and delete it after data from server fetched. But in my case it doesn't work. ProgressBar still downloading
Method that fetched data
private void makeJsonObjectRequest(int startList,int endList,final JsonObjectListener listener) {
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
i = startLsit;
while(i < endList) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
/***** TONS OF CODE *****/
movieList.add(movie);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
i++;
lastNumber = i;
}
mAdapter.notifyDataSetChanged();
listener.onDone(lastNumber);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
Place where I use method:
makeJsonObjectRequest(0, 9, new JsonObjectListener() {
#Override
public void onDone(int lastNumberI) {
lastNumber = lastNumberI;
}
#Override
public void onError(String error) {
}
}); }
mAdapter = new RVAdapter(getContext(),movieList,this,mRecyclerView);
mAdapter.setClickListener(this);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
movieList.add(null);
mAdapter.notifyItemInserted(movieList.size()-1);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
movieList.remove(movieList.size()-1);
mAdapter.notifyItemRemoved(movieList.size());
//add items one by one
int start = lastNumber;
int end = start + 9;
makeJsonObjectRequest(start, end, new JsonObjectListener() {
#Override
public void onDone(int lastNumberI) {
lastNumber = lastNumberI;
}
#Override
public void onError(String error) {
}
});
mAdapter.setLoaded();
}
}, 2000);
}
});
My adapter like this Endless RecyclerView
After getting response, you have to remove that null movie object and notify the adapter
private void makeJsonObjectRequest(int startList,int endList,final JsonObjectListener listener) {
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
movieList.remove(movieList.size()-1);
mAdapter.notifyItemRemoved(movieList.size());
i = startLsit;
while(i < endList) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
/***** TONS OF CODE *****/
movieList.add(movie);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
i++;
lastNumber = i;
}
mAdapter.notifyDataSetChanged();
listener.onDone(lastNumber);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}

Categories

Resources