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...
}
Related
I am successfully deleting an Item from the recyclerView. The Items gets deleted successfully, but the recyclerView is not refreshed after the delete operation.
This is my Adapter code :
holder.removeProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences myPrefs = context.getSharedPreferences("loginToken", Context.MODE_PRIVATE);
getToken = myPrefs.getString("token", null);
new AlertDialog.Builder(context)
.setTitle("Remove from Cart")
.setMessage("Are you sure you want to remove this Item from cart ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteDialog = ProgressDialog.show(context, "",
"Please Wait...", true);
final RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST,
REMOVE_CART_URL + "?token=" + getToken + "&product_id=" + cartModel.getProductid()
, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("success");
if (message.equals("true")) {
Toast.makeText(context, "Item Deleted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Delete error", e.getLocalizedMessage());
}
deleteDialog.dismiss();
notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
deleteDialog.dismiss();
}
});
requestQueue.add(request);
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_delete)
.show();
}
});
The Item after deletion stays there until I close the App and reopen. How do I fix this , so I dont have to reopen app everytime.
Instead of notifyDataSetChanged() write this code:
if (yourAdapterList.size() > 0) {
ourAdapterList.remove(position);
notifyItemRemoved(position);
}
I need help for showing toast and progress dialog inside volley request, and I use a custom adapter file when click on the card will send data with volley, please give better flow or fixing this code.
this is my onBindViewHolder inside adapter file
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final DataPicking task = taskList.get(position);
holder.numberid.setText(task.getNomorid());
holder.nama.setText(task.getNamakonsumen());
holder.rate.setText(task.getRate());
holder.tanggal.setText(task.getTanggal());
holder.salesman.setText(task.getSalesman());
holder.cardList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setTitle("Proses Picking")
.setMessage("Apakah kamu yakin ingin memproses picking data ini?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String nomorid = taskList.get(position).getNomorid();
PickingActivity picking = new PickingActivity();
picking.kirimData(nomorid);
}})
.setNegativeButton(android.R.string.no, null).show();
}
});
}
and this is kirimData function for send data with volley
public void kirimData(final String nomorid){
// Log.e("ini kirimdata ",nomorid);
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Loading ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Constants.URL_SET_PICKING, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Picking Response: " + response.toString());
//hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Log.e(TAG, "obj: " + jObj.toString());
String error = jObj.getString("status");
Log.e(TAG, "obj: " + error);
// Check for error node in json
if (error.equals("1")) {
// user successfully logged in
// Create login session
mAdapter.notifyDataSetChanged();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getBaseContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/*Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();*/
Log.e(TAG, "Proses Picking Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Proses Picking Failed", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("nomorid", nomorid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
and this is the error log
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.sip.gotrack.PickingActivity.kirimData(PickingActivity.java:167)
at com.sip.gotrack.PickingAdapter$1$1.onClick(PickingAdapter.java:69)
please help me for this error
Where is your pDialog being initialized?
Inside kirimData, initialize pDialog like this in the beginning.
pDialog = new ProgressDialog(context);
It seems pDialog is not initialized before this method is called.
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
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/
**
In the onCreate method, I have a network operation that is to return JSON that is parsed into ArrayLists, to be set into a CharSequence[] array and used in an alert dialog.
However, when selected, the alert does not populate with the resulting JSON data. Thus far, I know the Volley implementation works and the data is passed into the ArrayLists. The area of failure is passing the ArrayList data into the CharSequence[] array that is then to be passed into the AlertDialog:
// Initialize Volley:
final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
getUsersGroupsURL = usersGroupsActionURL + hardUserName + JSON;
JsonObjectRequest getGroupData = new JsonObjectRequest(Request.Method.GET, getUsersGroupsURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
groupResults = response.getJSONArray("users_groups");
for (int i = 0; i <= groupResults.length() - 1; i++) {
JSONObject oneGroup = groupResults.getJSONObject(i);
groupNameList.add(oneGroup.getString("groupName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getGroupData);
groupNames = groupNameList.toArray(new CharSequence[groupNameList.size()]);
inviteFriend.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
final CharSequence[] items = {
"Share an Idea", "Share a story"
};
AlertDialog.Builder builder = new AlertDialog.Builder(SingleSpecial.this);
builder.setTitle(R.string.sharing_type);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int selection) {
if (selection == 0) {
// Create the lists of groups and friends
// If the first, go to the selection of friend/group
AlertDialog.Builder openFriends = new AlertDialog.Builder(SingleSpecial.this);
openFriends.setTitle(R.string.sharing_type);
openFriends.setItems(groupNames, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int selection) {
}
});
AlertDialog openFriendsAlert = openFriends.create();
openFriendsAlert.show();
} else if (selection == 1) {
// If the second, select location, then the friend/group
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
I think the failure has to do with the time for the network operation to finish and the populating of the AlertDialog.
How can I get the nested AlertDialog to be populated with the data?
How can I get the nested AlertDialog to be populated with the data?
Call addAll and notifyDataSetChanged for update AlertDialog data :
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
...
ListView list = openFriendsAlert.getListView();
ArrayAdapter adapter = (ArrayAdapter)list.getAdapter();
adapter.addAll(groupNameList);
adapter.notifyDataSetChanged();
}