i have log in code who connecting to my php file on my host using volley
everything works great but when i log off and log in again, saved cache memory remember my old information even if i changed it.
i tried to use:
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
not clearing my cache
this is my code:
private void sendRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.GET,DBConstants.LOG_IN_USER + mEmail + "&password=" + mPassword,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray user = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
user = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject jo = user.getJSONObject(0);
gates = new ArrayList<String>(5);
gateData = new ArrayList<String>();
mEmail = jo.getString(DBConstants.KEY_LOGIN_EMAIL);
mPassword = jo.getString(DBConstants.KEY_LOGIN_PASSWORD);
name = jo.getString(DBConstants.KEY_LOGIN_NAME);
if(!mEmail.equals("null")) {
level = Integer.parseInt(jo.getString(DBConstants.KEY_LOGIN_LEVEL));
for (int i = 1; i < 6; i++) {
gates.add(jo.getString(DBConstants.KEY_LOGIN_GATE + i));
if(!gates.get(i-1).equals("null")) {
for (String dataString : gates.get(i-1).split(";")) {
gateData.add(dataString);
}
newGate = new Gate(gateData.get(0),gateData.get(1),gateData.get(2),
Integer.parseInt(gateData.get(3)),Integer.parseInt(gateData.get(4)),gateData.get(5));
myHandler.addNewGate(newGate);
getAuthorizedList(newGate);
gateData.clear();
}
}
login = true;
} else {
login = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
login = false;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this.getApplicationContext());
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
requestQueue.add(stringRequest);
}
sorry you can close
on my hosting account i had cache manager, i turned it off and it works great!
Related
I got a function where Im making an arrayrequest with the purpose to get the quantity of the registers from de callback; but, Im trying to return that number for the function.
I´m declaring a variable that gets the lenght or size of the temporal ArrayList, which it´s filled whith the response of the api request using the volley library.
public int Contar(int position){
final int[] Cant = new int[1];
ArrayList<Entidad_Decision> listaO = new ArrayList<>();
if (position == 0){
RequestQueue requestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, "http:My Api IP", null,
new Response.Listener<JSONArray>() {
#SuppressLint("SetTextI18n")
#Override
public void onResponse(JSONArray jsonArray) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String numero_de_decision = jsonObject.getString("NUMERO_DE_DECISION");
listaO.add(new Entidad_Decision(numero_de_decision,"","responsables","fecha" + " - " + "plazo", "observaciones", "procede", "status"));
}
//buscar.setText(listaO.size() + "");
Cant[0] = listaO.size();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(MY_DEFAULT_TIMEOUT4,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(arrayRequest);
}else if (position == 1){
RequestQueue requestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, "http:My API IP", null,
new Response.Listener<JSONArray>() {
#SuppressLint("SetTextI18n")
#Override
public void onResponse(JSONArray jsonArray) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String numero_de_decision = jsonObject.getString("NUMERO_DE_DECISION");
listaO.add(new Entidad_Decision(numero_de_decision,"","responsables","fecha" + " - " + "plazo", "observaciones", "procede", "status"));
}
//buscar.setText(listaO.size() + "");
Cant[0] = listaO.size();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(MY_DEFAULT_TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(arrayRequest);
}
return Cant[0];
}
When I´m calling that variable, the value is 0.
How can I solve this??
My json is:
{"status":"ok","result":
{"provider":"instagram","title":"lovely_songs_14u","link":
[{"link_name":"Download
Video","video_link":"https:\/\/scontent.cdninstagram.com\/v\/t50.2886-
16\/71650124_386743795596239_6119869649307488549_n.mp4?_nc_ht=scontent.cdninstagram.com&_nc_cat=111&oe=5D907D5B&oh=36ad5ad325cce7926307dfb730583b70"}]}}
Android Side:
StringRequest stringRequest = new StringRequest(Request.Method.GET, hp,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
Log.e("Response", response);
try {
JSONObject obj = new JSONObject(response);
categoryGetSet temp;
JSONArray ja_video = obj.getJSONArray("link");
for (int i = 0; i < ja_video.length(); i++) {
temp = new categoryGetSet();
JSONObject jo_data = ja_video.getJSONObject(i);
String txt_title = jo_data.getString("title");
String txt_link_name = jo_data.getString("link_name");
String txt_image = jo_data.getString("img_link");
String txt_video = jo_data.getString("video_link");
temp.setTitle(txt_title);
temp.setLinkName(txt_link_name);
temp.setImage(txt_image);
temp.setVideo(txt_video);
categoryGetSets.add(temp);
Log.e("dwnld", txt_link_name);
}
Log.e("try", "try");
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", "catch");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(networkResponse.statusCode), Toast.LENGTH_SHORT).show();
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
But it goes everytime into catch case, please let me know where i am doing it wrong
Your JSON is valid.
Use below code to parse your JSON.
try {
JSONObject obj = new JSONObject(json);
categoryGetSet temp;
JSONObject resultObject = (JSONObject) obj.get("result");
String txt_title = resultObject.getString("title");
String txt_provider = resultObject.getString("provider");
JSONArray ja_video = resultObject.getJSONArray("link");
for (int i = 0; i < ja_video.length(); ++i) {
temp = new categoryGetSet();
JSONObject jo_data = ja_video.getJSONObject(i);
String txt_link_name = jo_data.getString("link_name");
String txt_video = jo_data.getString("video_link");
temp.setTitle(txt_title);
temp.setLinkName(txt_link_name);
temp.setImage(txt_provider);
temp.setVideo(txt_video);
Log.e("jsonResponse: ", "txt_title" + txt_title);
Log.e("jsonResponse: ", "txt_link_name" + txt_link_name);
Log.e("jsonResponse: ", "txt_provider" + txt_provider);
Log.e("jsonResponse: ", "txt_video" + txt_video);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", e.getLocalizedMessage());
}
Because link array is inside result object but you are trying to get from outer object.so you are getting exception.
Try to parse like this
JSONObject obj = new JSONObject(response);
JSONObject resultObj=obj.getJSONObject("result");
JSONArray ja_video = resultObj.getJSONArray("link");
It's going in catch because you are trying to parse in the wrong way,
You need to pass every JSON object and array sequence by sequence, Bellow is your structure
Main Json Object
result Object
link Array
Sub Object with Data
And another wrong thing is you are trying some key which is not exist
Try Bellow code it will help you
StringRequest stringRequest = new StringRequest(Request.Method.GET, hp,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
Log.e("Response", response);
try {
JSONObject mainObject = new JSONObject(response);
JSONObject resultObj=mainObject.getJSONObject("result");
JSONArray linkJsonArrya = resultObj.getJSONArray("link");
categoryGetSet temp;
for (int i = 0; i < linkJsonArrya.length(); i++) {
temp = new categoryGetSet();
JSONObject jo_data = linkJsonArrya.getJSONObject(i);
if(jo_data.has("title")){
temp.setTitle(jo_data.getString("title"));
}else {
temp.setTitle(jo_data.getString(""));
}
if(jo_data.has("link_name")){
temp.setLinkName(jo_data.getString("link_name"));
}else {
temp.setLinkName(jo_data.getString(""));
}
if(jo_data.has("img_link")){
temp.setImage(jo_data.getString("img_link"));
}else {
temp.setImage(jo_data.getString(""));
}
if(jo_data.has("video_link")){
temp.setVideo(jo_data.getString("video_link"));
}else {
temp.setVideo(jo_data.getString(""));
}
categoryGetSets.add(temp);
}
Log.e("try", "try");
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", "catch");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(networkResponse.statusCode), Toast.LENGTH_SHORT).show();
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
I am adding String returned by Callback method from Volley's onRespond method.
I have already initialized GetterAndSetter Method inside OnCreate Method.
this is my code:
onRespond(){
...
AddtoList(CreateURL, new VolleyCallback() {
#Override
public void onSuccess(String result) {
getterAndSetter.addString(result);
}
});
....
}
My GetterAndSetter Class:
public class GetterAndSetter {
ArrayList<String> strings = new ArrayList<>();
public void addString(String string) {
this.strings.add(string);
}
public ArrayList<String> getList(){
return this.strings;
}
}
I tries to get all the strings added inside of this getterandsetter's ArrayList via following code inside my another method :
void LoadImages(MainActivity mainActivity){
...
List<String> details = getterAndSetter.getList();
Log.d("gs", getterAndSetter.getList().toString());
...
}
As seen above, I tried to print log, but it print "[]"(Empty String). I have seen alot of Answers on Stackoverflow, but can't solve my problem.
Update : I am adding more code so that you guys can understand the problem.
My OnCreate Method :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
getterAndSetter = new GetterAndSetter();
LoadImages(this);
}
LoadImages :
private void LoadImages(MainActivity mainActivity) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mView.dismiss();
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
List<String> details = getterAndSetter.getList();
Log.d("gs", getterAndSetter.getList().toString());
for (String urls : urlList) {
Log.d("urls", urls);
}
for (String title : titles) {
Log.d("tts", title);
}
for (String dt : details) {
Log.d("dts", dt);
}
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
JSONObject root = new JSONObject(URL);
JSONObject photos = root.getJSONObject("photos");
JSONArray photo = photos.getJSONArray("photo");
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL, new VolleyCallback() {
#Override
public void onSuccess(String result) {
getterAndSetter.addString(result);
}
});
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
AddtoList Method :
public void AddtoList(String CreateURL, VolleyCallback volleyCallback) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject root;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String str = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
volleyCallback.onSuccess(str);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My CallBack
public interface VolleyCallback {
void onSuccess(String result);
}
The problem is that you're trying to print the list BEFORE the callback is being invoked by Volley.
You parse a Json and for each element, you make a new request. After parsing the Json you print the list, it's empty because of the calls you make aren't ended at the moment you print the list.
You need to wait until all the request you start from inside the loop have ended.
**
the parameters of volley (company_id && branch_id)
equal null although I got its real data before via MyRequestQueue_Company so it causes volley response is nullpointer exception
Why do company_id and branch_id equal null in MyRequestQueue_Drivers? How can I solve this?
public class CheckinActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String company_id, branch_id;
Spinner driver_name_spinner;
private String User_URL = "http://example.com/api/user?token=";
private String Drivers_URL = "http://example.com/api/getDrivers?company_id=1&branch_id=15";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkin);
driver_name_spinner = (Spinner) findViewById(R.id.driver_name_spinner);
next = (Button) findViewById(R.id.next);
SharedPreferences sharedPref = getSharedPreferences("userinfo", getApplicationContext().MODE_PRIVATE);
final String token = sharedPref.getString("token", "");
final RequestQueue MyRequestQueue_Company = Volley.newRequestQueue(this);
// GET COMPANY_ID AND BRANCH_ID FORM API
StringRequest MyStringRequest_Company = new StringRequest(Request.Method.GET, User_URL + token, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue_Company.add(MyStringRequest_Company);
// CALL ANOTHER WEBSERVICES TO GET DRIVERS DATA
RequestQueue MyRequestQueue_Drivers = Volley.newRequestQueue(getApplicationContext());
StringRequest MyStringRequest_Drivers = new StringRequest(Request.Method.POST, Drivers_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Drivers Response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONArray jarray = jsono.getJSONArray("Drivers");
List<String> drivers;
drivers = new ArrayList<String>();
for (int i = 0; i < jarray.length(); i++) {
JSONObject newobject = jarray.getJSONObject(i);
driver_name_txt = newobject.getString("name");
Log.d("Driver Name", driver_name_txt);
drivers.add(driver_name_txt);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, drivers);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
driver_name_spinner.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Drivers Error",error.toString());
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
}
};
MyRequestQueue_Drivers.add(MyStringRequest_Drivers);
driver_name_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
TextView tmpView = (TextView) driver_name_spinner.getSelectedView().findViewById(android.R.id.text1);
tmpView.setTextColor(Color.WHITE);
driver_name_txt = parent.getItemAtPosition(position).toString();
Log.d("driver_name_original", driver_name_txt);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
If you want to use getParams function, than I would suggest to define a flag and modify your function like:
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
requestFinished = true;
} catch (JSONException e) {
e.printStackTrace();
}
}
And your getParams would look like :
protected Map<String, String> getParams() {
if(!requestFinished) return null;
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
But I would suggest to you to use the Observer pattern instead.
I am developing an application using android and i'm trying to get the jSon Array displayed in Listfragment using the loadInBackground() method below in my DataListLoader class:
class DataListLoader extends AsyncTaskLoader<List<Model>> {
List<Model> mModels;
String jsonString;
String name = "Daniel Nyerere", phone = "0652400670";
public DataListLoader(Context context) {
super(context);
loadInBackground();
}
public List<Model> loadInBackground() {
// You should perform the heavy task of getting data from
// Internet or database or other source
// Here, we are generating some Sample data
// Create corresponding array of entries and load with data.
final List<Model> entries = new ArrayList<Model>(50);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().contains("server_response")) {
jsonString = response.toString();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("name");
phone = jo.getString("user_phone");
entries.add(new Model(name, phone));
System.out.println("DATA FROM JSON ARRAY: " + name + " " + phone);
count++;
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);
entries.add(new Model(name, phone));
return entries;
}
But when i try to run it the data from System.out.println("DATA ENTRIES: "+entries); comes as null list ,so no data get displayed in the fragment activity . Anyone who can help me to fix it so that i get data from json because it consume me a lot of time
//You can call it in UI thread
final List<Model> entries = new ArrayList<Model>(5);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//you need to update the `ListView` content here
//If you need you can create new thread here too e.g. using AsyncTask
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);