I want app to show dates in listview. My app has TabLayout which imitates this and Listviews which imitate this.So, tabs have listview. After showing all json dates in listview, they load json dates again. It happens when I swipe each tabs like tab1→tab2→tab3→tab1→tab3.... This is may code. If anyone knows what is wrong, please teach me.
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Tab 1 (Tab2 and Tab3 are almost same)
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new CSadapter(getActivity(),movieList);
setListAdapter(adapter);
getListView().setScrollingCacheEnabled(false);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Song movie = new Song();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("jacket"));
movie.setNumber(obj.getString("number"));
movie.setYear(obj.getString("release"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
In a pager the default page limit is 1 .If you go beyond that your page activity is created again.This may be the case happening here.You can increase the page limit to avoid re creation
Related
I have a query to a mysql database, it asks for all the favorite courses, but first I need to pass the user to it. How could I do that?
file java:
public class FavoritosFragment extends Fragment {
RecyclerView recyclerView;
MyFavoritosRecyclerViewAdapter AdapterFavoritos;
List<Cursos>cursosList;
RequestQueue requestQueue;
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
public FavoritosFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favoritos_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
cursosList=new ArrayList<>();
ejecutarServicio();
obtenerCursos();
//asociamos el adaptador al recyclerview
AdapterFavoritos=new MyFavoritosRecyclerViewAdapter(cursosList, mListener);
recyclerView.setAdapter(AdapterFavoritos);
}
return view;
}
private void ejecutarServicio() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.URL_favo) , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error de registro!"+error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
final String usuario = "avo";
params.put("usu_usuario",usuario);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}
public void obtenerCursos() {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.URL_favo),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("Curso");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
boolean add = cursosList.add(
new Cursos(
jsonObject1.getString("id_curso"),
jsonObject1.getString("titulo"),
jsonObject1.getString("descripcion"),
jsonObject1.getString("categoria"),
jsonObject1.getString("imagen")
)
);
}
AdapterFavoritos=new MyFavoritosRecyclerViewAdapter(cursosList, mListener);
recyclerView.setAdapter(AdapterFavoritos);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
);
requestQueue.add(stringRequest);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(Cursos item);
}
}
this is my php file.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include 'conexion.php';
$usu_usuario=$_POST['usu_usuario'];
$miDato='';
$consultado="SELECT id_usuario FROM usuario WHERE usu_usuario='".$usu_usuario."'";
$result=mysqli_query($conexion,$consultado);
while($mostrar=mysqli_fetch_array($result)){
$miDato= $mostrar['id_usuario'];
}
// echo $miDato;
$consulta = " SELECT * FROM curso RIGHT JOIN favoritos ON curso.id_curso=favoritos.id_curso WHERE favoritos.id_usuario='".$miDato."'";
$resultado=$conexion->query($consulta);
$datos = array();
while($resultados = $resultado->fetch_assoc()) {
$datos[] = $resultados;
}
//echo json_encode($datos);
echo json_encode(array("Curso" => $datos));
mysqli_query($conexion,$consulta) or die (mysqli_error());
mysqli_close($conexion);
?>
here my two files java and php to the database query ..
I'm desperate you know how angry when the code does not understand me hahaha;)
here my two files java and php to the database query ..
I'm desperate you know how angry when the code does not understand me hahaha;)
what I want is to send the user to the query and volley returns the result, I know how to do it separately but I do not understand how to do that in a single request
I am facing a problem where my POST request parameters are not going to server after 1st time. I know Volley is using cache mechanism for responses, but in my case my request parameter values can be changed at runtime as i am using pagination in Recyclerview.
So my questions is how can i send Post request parameter every time and wont loose cache mechanism of volley.
I have tried using below ones and get my things done (calling getParams() every-time).. but it loses caches response and i don't want that.
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
Also have Searched Google and below links but cant find any proper solution. below are the SO links
Volley not calling getParams() for second time
Volley not calling getParams()
Android volley does not calling getParams in POST request
Volley not calling getParams() for standard POST request
Below is my code:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RES", response);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a"); //Format of our JSON dates
Gson gson = gsonBuilder.create();
NewsFeedPOJO resultObj = (NewsFeedPOJO) gson.fromJson(response, (Class) NewsFeedPOJO.class);
inCurrPage = Integer.parseInt(resultObj.getPagination().getCurrent_page());
inTotalPage = Integer.parseInt(resultObj.getPagination().getTotal_pages());
inCurrPage++;
arrayList.addAll(resultObj.getNewsFeedList());
if (isFtym) {
isFtym = false;
layoutManager = new LinearLayoutManager(MainActivity.this);
rcNewsFeed.setLayoutManager(layoutManager);
adapter = new NewsFeedAdapter(MainActivity.this, arrayList);
rcNewsFeed.setAdapter(adapter);
} else {
adapter.notifyItemInserted(arrayList.size());
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("user_id", "188");
if (inCurrPage == 0)
map.put("page", "1");
else {
map.put("page", "" + inCurrPage);
}
Log.e("RES", inCurrPage + " PARA");
return map;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//requestQueue.add(stringRequest);
//requestQueue.getCache().clear();
//AppController.getInstance().addToRequestQueue(stringRequest);
// stringRequest.setShouldCache(false);
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
using below Volley Dependency.
compile 'com.android.volley:volley:1.1.0'
If need more information please do let me know. Thanks in advance. Your efforts will be appreciated.
Did you check your Volley Singleton?
import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class VolleySingleton {
private static AppSingleton mAppSingletonInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mContext;
private AppSingleton(Context context) {
mContext = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized AppSingleton getInstance(Context context) {
if (mAppSingletonInstance == null) {
mAppSingletonInstance = new AppSingleton(context);
}
return mAppSingletonInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req,String tag) {
req.setTag(tag);
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Or maybe there is another issue in your code...
I would like to send a new JsonObjectRequest request (GET)
Here is my code below:
final VolleyApplication volleyApplication = VolleyApplication.getInstance();
volleyApplication.init(getApplicationContext());
JsonArrayRequest req = new JsonArrayRequest("http://localhost:8080/webapi/", new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
System.out.print(response.toString());
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
Type listType = new TypeToken<List<MyEntity>>() {
}.getType();
myList = gson.fromJson(response.toString(), listType);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
System.out.print(error.getMessage());
}
}
);
RequestQueue requestQueue = volleyApplication.getRequestQueue();
requestQueue.add(req);
this works on onCreate and list some object but it does not. As i see in debug mode,process works two times for this method. In first time when it is at RequestQueue requestQueue = volleyApplication.getRequestQueue(); requestQueue.add(req);.... line
it jumps out to end of the method. But it works and gets data for second time. This messed up my code.
And also my VolleyApplication class here below
public final class VolleyApplication {
private static VolleyApplication instance = null;
public static final VolleyApplication getInstance() {
if (instance == null) {
instance = new VolleyApplication();
}
return instance;
}
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private boolean initialized = false;
private VolleyApplication() {
}
public void init(final Context context) {
if (initialized) {
return;
}
requestQueue = Volley.newRequestQueue(context);
int memory = ((ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
int cacheSize = 1024 * 1024 * memory / 8;
// imageLoader = new ImageLoader(requestQueue, new BitmapLruCache(cacheSize));
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
throw new RuntimeException("Init first");
}
return requestQueue;
}
public ImageLoader getImageLoader() {
if (imageLoader == null) {
throw new RuntimeException("Init first");
}
return imageLoader;
}
}
#seradd
You are interpreting it wrong.
It is actually executing only one time.
What you are seeing in debug mode is that,
First time it is creating requestObject and adding it to RequestQueue.
RequestQueue then execute it and once it will get response from URL it will execute its callback functions onResponse() and onErrorResponse() from Response.Listener and Response.ErrorListener interface respectively.
So what I suggest you , whatever task you are doing after adding task
to RequestQueue call add that code to onResponse() method
I have a main page where I fetch a bunch of items from server using Volley and then I load them up on screen. If I click on an item, it should take me to the item page displaying its details which I'm fetching from server again using Volley. The latter (getting details for a single item on the single item page) works only once.
So for example if I access item page the first time, Volley gets me the response, so I can load data to screen. But if I press back or just go back to main page and select another item, Volley fails to give any responses, so the item page is empty. How do I make Volley send request and get response every time I access the Item page? or at least tell me why is it working only the first time?
My singleton class
public class MyApplication extends Application {
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getReqQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToReqQueue(Request<T> req, String tag) {
getReqQueue().add(req);
}
public <T> void addToReqQueue(Request<T> req) {
getReqQueue().add(req);
}
public void cancelPendingReq(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
How I make request and deal with response on Item Page, my ReadDataFromDB() method...
private void ReadDataFromDB() {
JsonObjectRequest jreq = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
int success = response.getInt(TAG_SUCCESS);
if (success == 1) {
//parse JSON
JSONObject productJSONObject = response.getJSONObject(TAG_PRODUCTS);
product = new ProdItem (productJSONObject.getString(TAG_PRODUCT_PICTURE), productJSONObject.getString(TAG_PRODUCT_TITLE), productJSONObject.getString(TAG_PRODUCTS_DESCRIPTION),
productJSONObject.getString(TAG_PRODUCTS_DATETIME), productJSONObject.getDouble(TAG_PRODUCTS_RATING),
productJSONObject.getDouble(TAG_PRODUCTS_PRICE), productJSONObject.getInt(TAG_PRODUCT_ID), productJSONObject.getInt(TAG_CAT_ID), productJSONObject.getInt(TAG_PRODUCTS_VIEWS),
productJSONObject.getInt(TAG_PRODUCTS_SHOPID), productJSONObject.getInt(TAG_PRODUCT_POINTS), 1, productJSONObject.getString(TAG_PRODUCTS_SHOPNAME));
} // if ends
//update UI
runOnUiThread(new Runnable() {
#Override
public void run() {
adTitleLBL.setText(product.getProdTitle());
shopNameLBL.setText(product.getShopName());
prodDescriptionLBL.setText(product.getProdDescription());
shopIDLBL.setText(String.valueOf(product.getProdShopID()));
catIDLBL.setText(String.valueOf(product.getMasterCatID()));
prdoIDLBL.setText(String.valueOf(product.getProdID()));
adRating.setRating((float) product.getProdRating());
loadAdImage(product.getProdImage());
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Server is terrible", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
//add request to queue
MyApplication.getInstance().addToReqQueue(jreq);
}
I checked for other questions here, but they're not what I'm looking for. I'm probably using Volley wrong, just need to know what I'm missing or what is it.
I'm have add volley for request to get Json object and cache data. but when i clear all cache, seem all data not delele.
Because when i turn off my network and restart my app .It still using cache.
I do the following code
public class AppController extends Application {
public static final String TAG = AppController.class.getName();
public static AppController mIntance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
/**
* onCreate of class that is extend Application always call first when app laucher . to benefit
* create object singleton.
*
* #param err
* #param context
* #return
*/
#Override
public void onCreate() {
super.onCreate();
mIntance = this;
}
public static synchronized AppController getIntance() {
return mIntance;
}
public RequestQueue getRequestQueue() {
/*
* if (requestQueue == null) { requestQueue =
* MyRequest.newRequestQueue(getApplicationContext()); }
*/
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// hoa ra settag la cho req nay ,. minh cu tuong no set cho c�i
// requestqueue
req.setTag(tag.equals("") ? TAG : tag);
getRequestQueue().add(req);
}
// using request with string default
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelRequest(Object tag) {
if (requestQueue != null) {
requestQueue.cancelAll(tag);
}
}
public void cancelAllRequest() {
if (requestQueue != null) {
requestQueue.cancelAll("feed_request");
}
}
/*
* clear some cache
*/
public void DeletelCacheFromSomeURL(ArrayList<String> array) {
for (int i = 0; i < array.size(); i++) {
requestQueue.getCache().remove(array.get(i));
}
}
}
i have clear all cache flowing
AppController.getIntance().getRequestQueue().getCache()
.clear();
Anyone explain and give me solution . thank !