Filter RecyclerView with loadmore - java

I am using adapter filter and it works fine, but only on loaded data list, when trying to scroll recyclerview while searching things are massed up, code as below.
my try for solution is mixed with current code.
I tried filtering on server side, but its slow while searching.
I need a solution that keeps things fast and simple.
==> activity search view:
srchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (s.length() != 0) {
if (adapterAll != null) {
adapterAll.getFilter().filter(s);
if (s != null)
saveSearchingText(s);
searching = true;
}
}else
searching = false;
return true;
}
});
==> 2 methods for starting and loadmore as below.
private void loadAllData(int index) {
tag_string_req_loadAll = "req_loadAll";
String currentUrl = Constants.url_get_all_data;
strReq_loadAll = new StringRequest(Request.Method.POST,
currentUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray jArray = jObj.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
Model model = new Model("data");
if (!c.getString("status").equals("rejected")) {
model.setData(data);
list.add(model);
}
}
adapterAll.notifyDataSetChanged();
} else {
String errorMsg = jObj.getString("message");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userId", userId);
params.put("index", String.valueOf(index));
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq_loadAll, tag_string_req_loadAll);
}
private void loadMore() {
rv_all_data.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
if (notLoading) {
int currentSize;
if(searching){
currentSize = adapterAll.getItemCount() - 1;
}else
currentSize = list.size() - 1;
if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == currentSize) {
rv_all_data.post(new Runnable() {
public void run() {
Model model = new Model("progress");
model.setType("progress");
list.add(model);
adapterAll.notifyItemInserted(list.size() - 1);
notLoading = false;
String tag_string_req_loadMore = "req_loadAMore";
String currentUrl = Constants.url_get_all_data;
StringRequest strReq_loadMore = new StringRequest(Request.Method.POST,
currentUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
list.remove(list.size() - 1);
adapterAll.notifyItemRemoved(list.size());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray jarray;
String noMoreItems = jObj.getString("end");
jarray = jObj.getJSONArray("items");
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
Model model = new Model("data");
if (!c.getString("status").equals("rejected")) {
model.setData(data);
list.add(model);
}
}
if (noMoreItems.equals("yes")) {
notLoading = false;
} else {
//filtering new data
if (adapterAll != null) {
adapterAll.getFilter().filter(getSearchingText());
}
adapterAll.notifyDataSetChanged();
notLoading = true;
}
} else {
String errorMsg = jObj.getString("message");
Toast.makeText(getActivity(), "OOps, Something Went Wrong, Try again.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "OOps, Something Went Wrong, Try again.", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "OOps, Something Went Wrong, Try again.", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userId", userId);
params.put("index", String.valueOf(list.size() - 1));
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq_loadMore, tag_string_req_loadMore);
}
});
}
}
}
});
}
==>adapter filter:
//filter in adapter
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charSequence = constraint.toString();
if (charSequence.isEmpty()) {
list = searchList;
} else {
List<ModelAllCars> filteredResults = new ArrayList<>();
for (Model model : searchList) {
if (model.getType().equals("data")) {
if (model.getBrand().toLowerCase().contains(charSequence)) {
filteredResults.add(model);
}
}
}
list = filteredResults;
}
FilterResults filterResults = new FilterResults();
filterResults.values = list;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
list = (ArrayList<Model>) results.values;
notifyDataSetChanged();
}
};
}

From what i understand you want to load all data from the list when the user clicks the "see more" button, right ?
Knowing this, recyclerview must be recycling the list elements. You can just to change scroll Vertically to false.
new LinearLayoutManager(getApplicationContext()) {
#Override
public boolean canScrollVertically() {
return false;
}
};

Related

How to return the status code in parseNetworkResponse in Android?

How can i return the status code of my api?
i know that the status code is generating in the parseNetworkResponse but i am using the parseNetworkResponse for the saving of cache, how can i still return the status code? is there other way to do this by using volley?
here is my code.
int status_code = 0;
public void loadAnnouncement(){
final Constant WebConfig = new Constant();
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, WebConfig.url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try {
JSONArray details = response.getJSONArray("data");
for (int i=0; i<details.length(); i++) {
JSONObject object = details.getJSONObject(i);
announcementList.add(new AnnouncementModel(
object.getInt("a"),
object.getString("b"),
object.getString("c"),
object.getString("d"),
object.getString("e"),
object.getString("f")
));
//creating adapter object and setting it to recyclerview
adapter = new AnnouncementAdapter(getActivity(), announcementList);
announcementRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
//This is for Headers If You Needed
#Override
public Map< String, String > getHeaders() throws AuthFailureError {
Map < String, String > params = new HashMap< String, String >();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("X-API-KEY", WebConfig.test);
params.put("Authorization", WebConfig.test1);
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), cacheEntry);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(JSONObject response) {
super.deliverResponse(response);
}
#Override
public void deliverError(VolleyError error) {
super.deliverError(error);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
};
queue.add(getRequest);
}
this is working, but i still need to return the status_code of it.
any help would be really appreciated.

JSON Volley Nested JSON Array com.android.volley.ParseError: org.json.JSONException

I wanna getJudul(), getExcerpt(), and getPostImg() from https://www.kisahmuslim.com/wp-json/wp/v2/categories. But it show me com.android.volley.ParseError: org.json.JSONException
Below the code you can check...
DaftarCategories
public class CallingPage extends AsyncTask<String, String, String> {
HttpURLConnection conn;
java.net.URL url = null;
private int page = 1;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFav(false);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("https://www.kisahmuslim.com/wp-json/wp/v2/categories");
}
catch(MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
protected void onPostExecute(String result)
{
JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, SumberPosts.HOST_URL+"wp/v2/categories/", null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d(TAG, response.toString() + "Size: "+response.length());
// agar setiap kali direfresh data tidak redundant
typeForPosts.clear();
for(int i=0; i<response.length(); i++) {
final CategoriesModel post = new CategoriesModel();
try {
Log.d(TAG, "Object at " + i + response.get(i));
JSONObject obj = response.getJSONObject(i);
post.setId(obj.getInt("id"));
post.setPostURL(obj.getString("link"));
//Get category name
post.setCategory(obj.getString("name"));
//////////////////////////////////////////////////////////////////////////////////////
// getting article konten
JSONObject postCategoryParent = obj.getJSONObject("_links");
JSONArray postCategoryObj = postCategoryParent.getJSONArray("wp:post_type");
for(int c=0; c<postCategoryObj.length(); c++) {
JSONObject postCategoryIndex = postCategoryObj.getJSONObject(c);
String postCategoryUrl = postCategoryIndex.getString("href");
if(postCategoryUrl != null) {
Log.d(TAG, postCategoryIndex.getString("href"));
JsonObjectRequest getKonten = new JsonObjectRequest(Request.Method.GET, postCategoryUrl, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
// Get category title
JSONObject titleObj = response.getJSONObject("title");
post.setJudul(titleObj.getString("rendered"));
//Get category excerpt
JSONObject exerptObj = response.getJSONObject("excerpt");
post.setExcerpt(exerptObj.getString("rendered"));
// Get category content
JSONObject contentObj = response.getJSONObject("content");
post.setContent(contentObj.getString("rendered"));
//////////////////////////////////////////////////////////////////////////////////////
// getting URL of the Post fetured Image
JSONObject featureImage = response.getJSONObject("_links");
JSONArray featureImageUrl = featureImage.getJSONArray("wp:featuredmedia");
for(int y=0; y<featureImageUrl.length(); y++){
JSONObject featureImageObj = featureImageUrl.getJSONObject(y);
String fiurl = featureImageObj.getString("href");
if(fiurl != null) {
Log.d(TAG, featureImageObj.getString("href"));
JsonObjectRequest getMedia = new JsonObjectRequest(Request.Method.GET, fiurl, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONObject exerptObj = response.getJSONObject("guid");
post.setPostImg(exerptObj.getString("rendered"));
}
catch (JSONException e) {
e.printStackTrace();
}
//notifyDataSetChanged untuk mendapatkan gambar
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getMedia);
} //if fiurl
} //for image url
} //try 2
catch (JSONException e) {
e.printStackTrace();
}
} //onResponse2
}, new Response.ErrorListener() { //getKonten
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getKonten);
} //if postCategoryUrl
} //for postCategory
//////////////////////////////////////////////////////////////////////////////////////
typeForPosts.add(post);
} //try 1
catch (JSONException e) {
e.printStackTrace();
}
} //for 1
pb.setVisibility(View.GONE);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} //onResponse1
}, new Response.ErrorListener() { //stringRequest
#Override
public void onErrorResponse(VolleyError error) {
showNoFav(true);
pb.setVisibility(View.GONE);
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} //onPostExecute
} //CallingPage
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
excerpt = click.getExcerpt();
gambar = click.getPostImg();
judul = click.getJudul();
url = click.getPostURL();
content = click.getContent();
Bundle bundle = new Bundle();
bundle.putString("excerpt", excerpt);
bundle.putString("gambar", gambar);
bundle.putString("judul", judul);
bundle.putString("url", url);
bundle.putString("content", content);
PostsBasedOnCategory bookFragment = new PostsBasedOnCategory();
bookFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContainerFragment, bookFragment).addToBackStack(null).commit();
}
PostsBasedOnCategory
public class PostsBasedOnCategory extends Fragment implements AdapterCategoryPosts.PostingAdapterListener {
public static PostsBasedOnCategory newInstance()
{
return new PostsBasedOnCategory();
}
private RecyclerView recycleViewWordPress;
private AdapterCategoryPosts mAdapter;
private RequestQueue queue;
public ArrayList<CategoriesModel> typeForPosts;
private SwipeRefreshLayout swipeRefreshLayout;
private ProgressBar pb;
public static final int CONNECTION_TIMEOUT = 2000;
public static final int READ_TIMEOUT = 2000;
public static String TAG = "postFrag";
private int index;
private TextView noFavtsTV;
private SearchView searchView;
private String content, gambar, judul, url;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_wordpress, container,false);
ButterKnife.bind(this,view);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
swipeRefreshLayout =(SwipeRefreshLayout) getActivity().findViewById(R.id.swipeRefreshLayout);
recycleViewWordPress =(RecyclerView) getActivity().findViewById(R.id.recycleViewWordPress);
pb = (ProgressBar) getActivity().findViewById(R.id.loadingPanel);
noFavtsTV = getActivity().findViewById(R.id.no_favt_text);
Bundle bundel = this.getArguments();
if(bundel != null){
String title = bundel.getString("judul");
String excerpt = bundel.getString("excerpt");
String pict = bundel.getString("gambar");
String url = bundel.getString("url");
String konten = bundel.getString("konten");
CategoriesModel post = new CategoriesModel();
post.setJudul(title);
post.setExcerpt(excerpt);
post.setPostImg(pict);
post.setPostURL(url);
post.setContent(konten);
typeForPosts = new ArrayList<CategoriesModel>();
typeForPosts.add(post);
recycleViewWordPress.setHasFixedSize(true);
recycleViewWordPress.setLayoutManager(new LinearLayoutManager(getContext()));
recycleViewWordPress.setNestedScrollingEnabled(false);
mAdapter = new AdapterCategoryPosts(getContext(), typeForPosts, this);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
pb.setVisibility(View.VISIBLE);
}
else {
pb.setVisibility(View.GONE);
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
pb.setVisibility(View.VISIBLE);
recycleViewWordPress.setAdapter(mAdapter);
}
});
}
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
content = click.getContent();
gambar = click.getPostImg();
judul = click.getJudul();
url = click.getPostURL();
Intent fullScreenIntent = new Intent(getContext(), DetailCategoryPost.class);
fullScreenIntent.putExtra("content", content);
fullScreenIntent.putExtra("gambar", gambar);
fullScreenIntent.putExtra("judul", judul);
fullScreenIntent.putExtra("url", url);
startActivity(fullScreenIntent);
}
private void showNoFav(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recycleViewWordPress.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_search, menu);
inflater.inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return true;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return true;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
//Menu
if (id == R.id.action_settings) {
//startActivity(new Intent(this, SettingsActivity.class));
//return true;
}
else
if (id == R.id.about_us) {
//startActivity(new Intent(this, AboutUs.class));
//return true;
}
return super.onOptionsItemSelected(item);
}
}
AdapterCategoryPosts
public class AdapterCategoryPosts extends RecyclerView.Adapter<AdapterCategoryPosts.ViewHolder> implements Filterable {
private Context context;
private List<CategoriesModel> typeForPosts;
private List<CategoriesModel> typeForPostsFiltered;
private PostingAdapterListener listener;
public AdapterCategoryPosts(Context context, List<CategoriesModel> typeForPosts, PostingAdapterListener listener) {
this.context = context;
this.typeForPosts = typeForPosts;
this.typeForPostsFiltered = typeForPosts;
this.listener = listener;
}
public interface PostingAdapterListener {
void onPostingSelected(int pos);
}
#Override
public AdapterCategoryPosts.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.postitem, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.tempelData(typeForPosts.get(position), holder.getAdapterPosition());
holder.viewCari(typeForPostsFiltered.get(position), holder.getAdapterPosition());
}
#Override
public int getItemCount() {
return typeForPostsFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
typeForPostsFiltered = typeForPosts;
}
else {
List<CategoriesModel> filteredList = new ArrayList<>();
for (CategoriesModel row : typeForPosts) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getJudul().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
typeForPostsFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = typeForPostsFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
typeForPostsFiltered = (ArrayList<CategoriesModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
TextView title, excerpt;
ImageView blog_image;
private String TAG = "LoadImage";
public ViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.title);
excerpt = (TextView) v.findViewById(R.id.excerpt);
blog_image = (ImageView) v.findViewById(R.id.blog_image);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
if (listener != null){
int position = getAdapterPosition();
String name = typeForPostsFiltered.get(position).getJudul();
for (int i=0; i<typeForPosts.size(); i++){
if( name.equals(typeForPosts.get(i).getJudul()) ){
position = i;
break;
}
}
if(position != RecyclerView.NO_POSITION) {
listener.onPostingSelected(position);
}
}
}
});
}
public void tempelData(final CategoriesModel item, final int adapterPosition) {
String judulx = item.getJudul();
if(judulx != null){
title.setText(Html.fromHtml(item.getJudul()));
}
String desk = item.getExcerpt();
if(desk != null){
if(desk.length() >= 254){
excerpt.setText(Html.fromHtml(desk.substring(0, 254)));
}
else {
excerpt.setText(Html.fromHtml(item.getExcerpt()));
}
}
Glide.with(context).load(item.getPostImg()).thumbnail(0.2f).apply(fitCenterTransform()).thumbnail(0.2f).apply(fitCenterTransform()).into(blog_image);
} // tempeldata
public void viewCari(final CategoriesModel stori, final int adapterPosition) {
final CategoriesModel posting = typeForPostsFiltered.get(adapterPosition);
title.setText(posting.getJudul());
Glide.with(context).load(posting.getPostImg()).into(blog_image);
} //viewCari
}
}
SumberPosts
public class SumberPosts {
public static String HOST="192.168.1.100";
public static String HOST_URL="https://www.kisahmuslim.com/wp-json/";
public static String AMP="amp/";
public static String CHECK_URL="http://localhost/";
public static String REPLACE_URL="http://"+HOST.trim()+"/";
public static String TEMPLATE_FOR_TIME = "yyyy-MM-dd";
public static String RESPONSE = "for_post";
public static String RESPONSE_1 = "id";
public static String RESPONSE_2 = "name";
public static String RESPONSE_3 = "link";
public static String RESPONSE_4 = "time";
public static String RESPONSE_5 = "content";
public static String RESPONSE_6 = "author";
public static String RESPONSE_7 = "image";
public static String RESPONSE_8 = "category";
}
Add dependencies as follows:
implementation 'com.google.code.gson:gson:2.8.5'
Set the DoInput flag to true if you intend to use the URL connection for input, false if not. The default is true.
Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.
Change your code from
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true)
to
// open http connection
conn = (HttpURLConnection) new URL(url).openConnection();
// http method
conn.setRequestMethod("GET");
// enable read mode (always)
conn.setDoInput(true);
// disable write (for GET, HEAD, OPTIONS, TRACE)
conn.setDoOutput(false);
and
protected void onPostExecute(String result)
{
if ((result.startsWith("{") || result.startsWith("["))) {
// JSON output
JsonArray arr = gson.fromJson(content, (Type) JsonArray.class);
if (arr != null) {
for (int i = 0; i < arr.size(); i++) {
JsonObject obj = (JsonObject) arr.get(i);
if (obj != null) {
Log.i("TAG_:", "\n\n------------------------------------{ " + (i + 1) + " }");
if (obj.has("id")) {
Log.i("TAG_id:", obj.get("id").getAsString());
}
if (obj.has("count")) {
Log.i("TAG_count:", obj.get("count").getAsString());
}
if (obj.has("description")) {
Log.i("TAG_description:", obj.get("description").getAsString());
}
if (obj.has("link")) {
Log.i("TAG_link:", obj.get("link").getAsString());
}
if (obj.has("name")) {
Log.i("TAG_name:", obj.get("name").getAsString());
}
if (obj.has("slug")) {
Log.i("TAG_slug:", obj.get("slug").getAsString());
}
if (obj.has("taxonomy")) {
Log.i("TAG_taxonomy:", obj.get("taxonomy").getAsString());
}
if (obj.has("parent")) {
Log.i("TAG_parent:", obj.get("parent").getAsString());
}
if (obj.has("meta")) {
JsonArray arr1 = obj.get("meta").getAsJsonArray();
if (arr1 != null) {
for (int j = 0; j < arr1.size(); j++) {
JsonObject obj1 = (JsonObject) arr1.get(j);
if (obj1 != null) {
Log.i("TAG_meta:", obj1.get("").getAsString());
}
}
}
}
if (obj.has("_links")) {
JsonObject obj2 = obj.get("_links").getAsJsonObject();
if (obj2 != null) {
if (obj2.has("self")) {
JsonArray arr2 = obj2.get("self").getAsJsonArray();
if (arr2 != null) {
for (int j = 0; j < arr2.size(); j++) {
JsonObject obj3 = arr2.get(j).getAsJsonObject();
if (obj3 != null) {
Log.i("TAG_self_href:", obj3.get("href").getAsString());
}
}
}
}
if (obj2.has("collection")) {
JsonArray arr3 = obj2.get("collection").getAsJsonArray();
if (arr3 != null) {
for (int j = 0; j < arr3.size(); j++) {
JsonObject obj4 = arr3.get(j).getAsJsonObject();
if (obj4 != null) {
Log.i("TAG_collection_href:", obj4.get("href").getAsString());
}
}
}
}
if (obj2.has("about")) {
JsonArray arr4 = obj2.get("about").getAsJsonArray();
if (arr4 != null) {
for (int j = 0; j < arr4.size(); j++) {
JsonObject obj5 = arr4.get(j).getAsJsonObject();
if (obj5 != null) {
Log.i("TAG_about_href:", obj5.get("href").getAsString());
}
}
}
}
if (obj2.has("up")) {
JsonArray arr5 = obj2.get("up").getAsJsonArray();
if (arr5 != null) {
for (int j = 0; j < arr5.size(); j++) {
JsonObject obj6 = arr5.get(j).getAsJsonObject();
if (obj6 != null) {
Log.i("TAG_up_embeddable:", obj6.get("embeddable").getAsString());
Log.i("TAG_up_href:", obj6.get("href").getAsString());
}
}
}
}
if (obj2.has("wp:post_type")) {
JsonArray arr6 = obj2.get("wp:post_type").getAsJsonArray();
if (arr6 != null) {
for (int j = 0; j < arr6.size(); j++) {
JsonObject obj7 = arr6.get(j).getAsJsonObject();
if (obj7 != null) {
Log.i("TAG_wp:post_type_href:", obj7.get("href").getAsString());
}
}
}
}
if (obj2.has("curies")) {
JsonArray arr7 = obj2.get("curies").getAsJsonArray();
if (arr7 != null) {
for (int j = 0; j < arr7.size(); j++) {
JsonObject obj8 = arr7.get(j).getAsJsonObject();
if (obj8 != null) {
Log.i("TAG_curies_name:", obj8.get("name").getAsString());
Log.i("TAG_curies_href:", obj8.get("href").getAsString());
Log.i("TAG_curies_templated:", obj8.get("templated").getAsString());
}
}
}
}
}
}
}
}
}
}
}
result:
TAG_:: ------------------------------------{ 1 }
TAG_id:: 12
TAG_count:: 57
TAG_link:: https://kisahmuslim.com/category/kisah-nyata/biografi-ulama
TAG_name:: Biografi Ulama
TAG_slug:: biografi-ulama
TAG_taxonomy:: category
TAG_parent:: 29
TAG_self_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/12
TAG_collection_href:: https://kisahmuslim.com/wp-json/wp/v2/categories
TAG_about_href:: https://kisahmuslim.com/wp-json/wp/v2/taxonomies/category
TAG_up_embeddable:: true
TAG_up_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/29
TAG_wp:post_type_href:: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=12
TAG_curies_name:: wp
TAG_curies_href:: https://api.w.org/{rel}
TAG_curies_templated:: true
TAG_:: ------------------------------------{ 2 }
TAG_id:: 26
TAG_count:: 8
TAG_link:: https://kisahmuslim.com/category/download
TAG_name:: Download
TAG_slug:: download
TAG_taxonomy:: category
TAG_parent:: 0
TAG_self_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/26
TAG_collection_href:: https://kisahmuslim.com/wp-json/wp/v2/categories
TAG_about_href:: https://kisahmuslim.com/wp-json/wp/v2/taxonomies/category
TAG_wp:post_type_href:: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=26
TAG_curies_name:: wp
TAG_curies_href:: https://api.w.org/{rel}
TAG_curies_templated:: true
// saya sengaja tidak tampilkan semua disini untuk menghemat ruang.
TAG_:: ------------------------------------{ 10 }
TAG_id:: 29
TAG_count:: 255
TAG_link:: https://kisahmuslim.com/category/kisah-nyata
TAG_name:: Kisah Nyata
TAG_slug:: kisah-nyata
TAG_taxonomy:: category
TAG_parent:: 0
TAG_self_href:: https://kisahmuslim.com/wp-json/wp/v2/categories/29
TAG_collection_href:: https://kisahmuslim.com/wp-json/wp/v2/categories
TAG_about_href:: https://kisahmuslim.com/wp-json/wp/v2/taxonomies/category
TAG_wp:post_type_href:: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=29
TAG_curies_name:: wp
TAG_curies_href:: https://api.w.org/{rel}
TAG_curies_templated:: true

How to Change order of List view's Items according to some Specific input

I want to change the sequence of my list view's items according to a specific input string which is matches with any of list view items contents and that item comes on the top of list view. I have tried hard but getting no success till now.if any other query please ask.
Here is the code for fetching data from server:
Here date2 is string input which I'm trying to compare
private void caladata() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(false);
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
try {
jsonarray = object.getJSONArray("Table");
} catch (JSONException e) {
e.printStackTrace();
}
Calenndar_Model movie = new Calenndar_Model();
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
movie.setUserid(obj.getString("userid"));
movie.setHost(obj.getString("eventname"));
String str = obj.getString("eventdate").replaceAll("\\D+","");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new Date(Long.parseLong(upToNCharacters));
// System.out.println(time);
movie.setDate(String.valueOf(timeZoneFormat.format(time)));
movie.setColor(obj.getString("eventcolor"));
movie.setAutoid(obj.getString("autoid"));
// Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
int index=calList.indexOf(date2);
calList.add(movie);
calList.remove(date2);
calList.add(0, movie);
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
// listView.smoothScrollToPositionFromTop(selectedPos,0,300);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
params.put("clientid", get1);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Here is my adapter class:
public class CalendarListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Calenndar_Model> movieList;
public CalendarListAdapter(Activity activity, List<Calenndar_Model> movieList) {
this.activity = activity;
this.movieList = movieList;
}
public void swapList(List<Calenndar_Model> movieList) {
this.movieList = movieList;
notifyDataSetChanged();
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.calendar_listrow, null);
ImageView serial = (ImageView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView date1 = (TextView) convertView.findViewById(R.id.date1);
title.setText(movieList.get(position).getHost());
date1.setText(movieList.get(position).getDate());
return convertView;
}
}
Model Class:
public class Calenndar_Model {
private String host, date,userid,color,autoid;
//private double rating;
public Calenndar_Model() {
}
public Calenndar_Model(String host,String date,String userid,String color,String autoid) {
this.host = host;
this.date = date;
this.userid = userid;
this.color = color;
this.autoid = autoid;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getAutoid() {
return autoid;
}
public void setAutoid(String autoid) {
this.autoid = autoid;
}
}
UPDATE: I found usage of date2 (the real name of variable, not data2 as you menthioned in description).
All you need is to sort your List<Calenndar_Model>:
private void caladata() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(false);
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
try {
jsonarray = object.getJSONArray("Table");
} catch (JSONException e) {
e.printStackTrace();
}
calList = new ArrayList<>();
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
Calenndar_Model movie = new Calenndar_Model();
movie.setUserid(obj.getString("userid"));
movie.setHost(obj.getString("eventname"));
String str = obj.getString("eventdate").replaceAll("\\D+","");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new Date(Long.parseLong(upToNCharacters));
//System.out.println(time);
movie.setDate(String.valueOf(timeZoneFormat.format(time)));
movie.setColor(obj.getString("eventcolor"));
movie.setAutoid(obj.getString("autoid"));
//Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
calList.add(movie);
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
//sort calList list
Comparator<Calenndar_Model> calendarModelComparator = new Comparator<Calenndar_Model>() {
#Override
public int compare(Calenndar_Model cm1, Calenndar_Model cm2) {
boolean firstContainsData2 = calendarModelContainsData2(cm1);
boolean secondContainsData2 = calendarModelContainsData2(cm2);
if (firstContainsData2 && secondContainsData2) {
return 0;
} else if (firstContainsData2) {
return -1;
} else if (secondContainsData2) {
return 1;
} else return cm2.getData().compareTo(cm1.getData());
}
private boolean calendarModelContainsData2(Calenndar_Model cm) {
return cm.getData().contains(data2);
}
};
Collections.sort(calList, calendarModelComparator);
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.swapList(calList);
//listView.smoothScrollToPositionFromTop(selectedPos,0,300);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
params.put("clientid", get1);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Suppose date2 is eventname you want to compare.
if(date2.equals(movie.getHost())
{
// store Movie object on index 0, if it equals date2
calList.add(0, movie);
}
else
{
calList.add(movie);
}
Remove the Following Lines from caladata().
int index=calList.indexOf(date2);
calList.add(movie);
calList.remove(date2);
calList.add(0, movie);

How do I set an Async Task for this code?

I am having trouble with my listblogs=parseJSONResponse(result), result is underlined red and if I hover over it it says that, I cannot apply a parseJsonResponse JSONARRAY to a JSONARRAY[]. Does anyone know why this is being caused does it have something to do with the params?
class YourTask extends AsyncTask<JSONArray, String, ArrayList<Blogs> > {
#Override
protected ArrayList<Blogs> doInBackground(JSONArray... result) {
listblogs.clear(); // here you clear the old data
listblogs=parseJSONResponse(result);
return listblogs;
}
#Override
protected void onPostExecute(ArrayList<Blogs> blogs) {
mAdapterDashBoard.setBloglist(listblogs);
}
}
private void JsonRequestMethod() {
final long start = SystemClock.elapsedRealtime();
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.print(response);
listblogs = new YourTask().doInBackground();
listblogs.clear();
listblogs=parseJSONResponse(response);
try {
listblogs = new YourTask().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(response);
Log.d("Testing", "Time elapsed: " + (SystemClock.elapsedRealtime() - start));
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String studentId = currentQuestions.getString("studentId");
String DateCreated=currentQuestions.getString("created");
long time=Long.parseLong(DateCreated.trim());
data.append(text + "\n" + points + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
//The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
blogs.setDateCreated(getTimeAgo(time));
System.out.println(time + "time");
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
AsyncTask
public class MyAsyncTask extends AsyncTask<Void, Void, ArrayList> {
JsonArray myJsonArray;
#Override
protected void onPreExecute() {
super.onPreExecute();
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
listblogs.clear();
}
#Override
protected ArrayList doInBackground(Void... params) {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
myJsonArray = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
return null;
}
#Override
protected void onPostExecute(ArrayList arrayList) {
super.onPostExecute(arrayList);
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < myJsonArray.length(); i++) {
JSONObject currentQuestions = myJsonArray.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String studentId = currentQuestions.getString("studentId");
String DateCreated=currentQuestions.getString("created");
long time=Long.parseLong(DateCreated.trim());
data.append(text + "\n" + points + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
//The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
blogs.setDateCreated(getTimeAgo(time));
System.out.println(time+"time");
blogsArrayList.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
return blogsArrayList;
}
ArrayList
synchronous:
listblogs = new MyAsyncTask().execute().get();
asynchronous:
....
} catch (JSONException e) {
e.printStackTrace();
}
listblogs = blogsArrayList;
return blogsArrayList;
}
new MyAsyncTask().execute();
you can run any code inside an async task like this:
public class YourTask extends AsyncTask<String, Void, ArrayList<Blogs> > {
private static final String TAG = YourTask.class.getSimpleName();
private JSONArray mResponse;
private Activity mActivity;
public YourTask(final Activity activity, final JSONArray response) {
super();
this.mActivity = activity;
this.mResponse = response;
}
#Override
protected ArrayList<Blogs> doInBackground(String... params) {
if (!mResponse.equals("")) {
// Your Code
}
return listblogs;
}
#Override
protected void onPostExecute(final ArrayList<Blogs> blogs) {
if (mActivity instanceOf YourActivity) {
((YourActivity) activity).finishTask(blogs);
}
}
#Override
protected void onCancelled() {}
}
call this Task from your activity like:
AsyncTask<String, Void, JSONArray> task = new YourTask(this, response);
task.executeContent();
Basically just send the JSONArray you want to parse to the Async Task and handle all the UI in den finishTask method in your Activity. The advantage is that you can extract your task in an extra file and leave your activity to just handle controlling your views.

Android Volley Lib ArrayList always Null?

Arraylist catPages is always null. It is supposed to be filled in method getPages(), but after request its size is "0" and null. WHY? How can I store this ArrayList without losing its values? Can you help me?
public class ImageActivity extends ActionBarActivity {
int frIndex;
ProgressDialog pDialog;
Context context;
String catalog_id;
private static final String TAG = ImageActivity.class.getSimpleName();
private static String url = "api_url";
private static String full_url;
public static ArrayList<Pages> catPages;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
catalog_id = getIntent().getStringExtra("catalog_id");
full_url = url + "/" + catalog_id;
if(savedInstanceState!=null)
{
catPages = (ArrayList<Pages>) savedInstanceState.getSerializable("catPages");
}
else
{
catPages = new ArrayList<Pages>();
getPages();
}
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
frIndex = getIntent().getIntExtra(Constants.Extra.FRAGMENT_INDEX, 0);
Fragment fr = null;
String tag ="";
int titleRes;
if(frIndex == ImagePagerFragmentBase.INDEX)
{
tag = ImagePagerFragmentBase.class.getSimpleName();
fr = getSupportFragmentManager().findFragmentByTag(tag);
String s = catPages.get(0).getPhoto_medium_url();
if (fr == null) {
fr = new ImagePagerFragmentBase();
fr.setArguments(getIntent().getExtras());
}
}
else if(frIndex==ImageGalleryFragmentBase.INDEX)
{
tag = ImageGalleryFragmentBase.class.getSimpleName();
fr = getSupportFragmentManager().findFragmentByTag(tag);
String s = catPages.get(0).getPhoto_medium_url();
if (fr == null) {
fr = new ImageGalleryFragmentBase();
Bundle bundleObject = new Bundle();
bundleObject.putString("catalog_id",catalog_id);
fr.setArguments(bundleObject);
}
}
titleRes = R.string.app_name;
setTitle(titleRes);
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, fr, tag).addToBackStack("fragment").commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fr;
String tag;
switch (item.getItemId()) {
case android.R.id.home:
tag = ImagePagerFragmentBase.class.getSimpleName();
if (new ImageGalleryFragmentBase() == getSupportFragmentManager().findFragmentByTag(tag)) {
getFragmentManager().popBackStack();
// finish();
return true;
} else {
getFragmentManager().popBackStack();
// finish();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
public void getPages() {
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest catReq = new JsonObjectRequest(Request.Method.GET, full_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
try {
JSONObject obj = response.getJSONObject("result");
JSONObject catalog = obj.getJSONObject("catalog");
JSONArray pageArray = catalog.getJSONArray("pages");
for (int i = 0; i < pageArray.length(); i++) {
Pages page = new Pages();
JSONObject object = (JSONObject) pageArray.get(i);
page.setId(object.getString("id"));
page.setCatalog_id(object.getString("catalog_id"));
page.setPhoto_file_name(object.getString("photo_file_name"));
page.setPhoto_file_size(object.getString("photo_file_size"));
page.setPhoto_medium_url(object.getString("photo_medium_url"));
page.setPhoto_original_url(object.getString("photo_original_url"));
catPages.add(page);
Log.e("CATPAGES", String.valueOf(catPages.size()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
Log.e("Hata", "errorresponse ");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("email", "api_header");
return headers;
}
};
AppController.getInstance().addToRequestQueue(catReq);
}
#Override
public void onSaveInstanceState(final Bundle outState) {
outState.putSerializable("catPages",catPages);
super.onSaveInstanceState(outState);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Thanks for your replies.

Categories