Android Volley Lib ArrayList always Null? - java

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.

Related

Filter RecyclerView with loadmore

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;
}
};

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

Populating TextView after Spinner Selection

I'm Having difficulty populating TextViews from my SQL Database. I have one column populating a spinner and then I want the Two Textviews to be populated by MySQL Columns from the same row of the spinner selection.
I cannot find the correct code to add to the OnSelectedItem portion.
MainActivity.java
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
Context c;
TextView colorDensity;
Spinner colorSpinner= findViewById(R.id.colorSpinner);
ArrayList<String> colors=new ArrayList<>();
final static String urlAddress = "http://www.burtkuntzhandjobs.org/dbcolors.php";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Downloader(MainActivity.this,urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(this,"Select Color", Toast.LENGTH_SHORT).show();
}
}
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setIu(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
Spinner colorSpinner;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, Spinner colorSpinner) {
this.c = c;
this.urlAddress = urlAddress;
this.colorSpinner = colorSpinner;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching");
pd.show();
}
#Override
protected String doInBackground(Void...params) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s == null) {
Toast.makeText(c,"Unable to Retrieve",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Success",Toast.LENGTH_SHORT).show();
DataParser parser=new DataParser(c,colorSpinner,s);
parser.execute();
}
}
private String downloadData() {
HttpURLConnection con= (HttpURLConnection) Connector.connect(urlAddress);
if(con == null) {
return null;
}
InputStream is = null;
try {
is = new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer response=new StringBuffer();
if(br != null){
while ((line=br.readLine()) !=null) {
response.append(line+"\n");
}
br.close();
} else {
return null;
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null){
try{
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Make following changes & add required code,
1. Remove Spinner colorSpinner= findViewById(R.id.colorSpinner); from class variable.
2. Add Spinner colorSpinner= findViewById(R.id.colorSpinner); in onCreate` method.
Look this spinet,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
Spinner colorSpinner= findViewById(R.id.colorSpinner);
new Downloader(this, urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
3. Access colors list from DataParser class,
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
private static ArrayList<Colors> colorsList=new ArrayList<>(); // add this line
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setUi(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
colorsList.add(s); // add this line
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
public static List<Colors> getColorsList() { // add this method
return colorsList;
}
}
4. Set density accordingly in onItemSelected() method of activity class.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<Colors> colorsList = DataParser.getColorsList();
colorDensity.setText(colorsList.get(position).getDensity());
}

volley- How do I return the ArrayList from OnResponse Method In Volley

I am using volley to parse the Movie Details from a REST api and I am saving the parsed Data in an Arraylist of objects called detailsMovies. But I can't access the ArrayList outside the onResponse Method. I am new to Android So I dont know what to do exactly.
Any Help is appreciated!
Here's the code:`
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
// private String movieTitle ;
// private String movieSummary ;
// private int movieYear;
// private long movieRating;
// private String movieYoutubeId;
// private String movieUrlThumbnail;
// private String movieDownloadLink720p;
// private String movieQuality720p;
// private String moviefileSize720p;
// private String movieDownloadLink1080p;
// private String movieQuality1080p;
// private String moviefileSize1080p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails();
}
public void parseMovieDetails(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
Define an Interface in your class and implement that.
So Simple trick here is interface with callback.
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails(new CallBack() {
#Override
public void onSuccess(ArrayList<MovieDetails> detailsMovies) {
// Do Stuff
}
#Override
public void onFail(String msg) {
// Do Stuff
}
});
}
public void parseMovieDetails(final CallBack onCallBack){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
onCallBack.success(detailsMovies);
} catch (JSONException e) {
e.printStackTrace();
onCallBack.onFail(e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
public interface CallBack {
void onSuccess(ArrayList<MovieDetails> detailsMovies);
void onFail(String msg);
}

java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 ERROR

I have an issue with my app when retrieving data from array.
SchedulePage:
public class SchedulePage extends Activity {
List<MyTask> tasks;
List<Test_Sched> SchedList;
// Intent intent = getIntent();
// String Username = intent.getStringExtra("Username2");
int Count = 0;
String SendCount = "";
TextView endtv, durationtv;
//storage of Test_Name
private static ArrayList<String> Test_Name = new ArrayList<String>();
//storage of x values in array private
private static ArrayList<Integer> Duration = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_page);
endtv = (TextView) findViewById(R.id.Endtv);
durationtv = (TextView) findViewById(R.id.Durationtv);
//Use this to Create Layouts Dynamically
//RelativeLayout relativeLayout = new RelativeLayout(this);
tasks = new ArrayList<>();
GetSchedule();
//GridView gv = (GridView) findViewById(R.id.grid);
//gv.setAdapter(new ImageAdapter(getApplicationContext()));
//Storing test name Arraylist in a array
final String [] web = Test_Name.toArray(new String[Test_Name.size()]);
//Storing images in a array
ArrayList<Integer> imagesAL = new ArrayList<Integer>();
for(int i = 0; i < Test_Name.size(); i++){
// String testname = web[i];
String lf = "One Leg(Left)", rf = "One Leg(Right)", sf = "Separate Foot", sbsf= "Side By Side Foot", tthr ="Toe To Heel(Right)", tthl ="Toe To Heel(Left)";
if(lf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.leftfoot);
}
if(rf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.rightfoot);
}
if(sf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.feetapart);
}
if(sbsf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.sidebysidefoot);
}
if(tthr.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.righttoetoleftheel);
}
if(tthl.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.lefttoetorightheel);
}
}
Integer [] imageId = imagesAL.toArray(new Integer[imagesAL.size()]);
ImageAdapter adapter = new ImageAdapter(SchedulePage.this, web, imageId);
GridView grid;
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(SchedulePage.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.schedule_page, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Login Stuff
public static ArrayList<Integer> getDuration() {
return Duration;
}
public static ArrayList<String> getTestName() {
return Test_Name;
}
private void GetSchedule(){
String jsonOutput = "http://172.20.34.112/IBBTS_WebService_MobileAndDevice/Service1.asmx/GetSchedule";
if (isOnline()) {
//while(End == "not yet"){
requestData(jsonOutput);
//}
}else {
Toast.makeText(SchedulePage.this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
private static String doJSONHTTPCall(String urlStr) {
String output2 = "";
try {
URL url;
try {
url = new URL(urlStr);
}
catch (MalformedURLException e) {
throw e;
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
output2 += output;
}
conn.disconnect();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return output2;
}
private void requestData(String uri) {
//Send the integer to String
Bundle gt=getIntent().getExtras();
String usernamePass =gt.getString("userName2");
SendCount = Integer.toString(Count);
RequestPackage p = new RequestPackage();
p.setMethod("GET");
p.setUri(uri);
p.setParam("Username", usernamePass);
MyTask task = new MyTask();
task.execute(p);
}
protected void updateDisplay(){
if (SchedList != null) {
for (Test_Sched test_Sched : SchedList) {
Duration.add(test_Sched.getDuration());
Test_Name.add(test_Sched.getTest_Name());
Count++;
}
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class MyTask extends AsyncTask<RequestPackage, String, String>{
#Override
protected void onPreExecute() {
//updateDisplay("Starting Task");
if (tasks.size() == 0) {
//progress.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
#Override
protected String doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return content;
}
#Override
protected void onPostExecute(String result) {
SchedList = ScheduleJSONParser.parseFeed(result);
updateDisplay();
tasks.remove(this);
if (tasks.size() == 0) {
//progress.setVisibility(View.INVISIBLE);
}
}
#Override
protected void onProgressUpdate(String... values) {
//updateDisplay(values[0]);
}
}
}
ScheduleJSONParsor
public class ScheduleJSONParser {
public static List<Test_Sched> parseFeed(String content) {
try {
JSONArray ar = new JSONArray(content);
List<Test_Sched> SchedList = new ArrayList<>();
for (int i = 0; i < ar.length(); i++) {
JSONObject obj = ar.getJSONObject(i);
Test_Sched test_Sched = new Test_Sched();
test_Sched.setDuration(Integer.parseInt(obj.getString("Duration")));
test_Sched.setTest_Name(obj.getString("Test_Name"));
SchedList.add(test_Sched);
}
return SchedList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}}
The logcat does not indicate which line has the error and I find it difficult to troubleshoot.
The idea is that it retrieves the schedule from the database and pass it to an array. then the app will display image buttons for each of the exercise name.
Also when I click the schedulePage button from the main menu, it shows up blank and I have to re-click the schedulePage the second time. The second time shows the arrayoutofbounds error..
any help would be appreciated.
The reason is this both lines
GetSchedule();
final String [] web = Test_Name.toArray(new String[Test_Name.size()]);
in GetSChedule() you are running thread in background and from response of webservice you are filling Test_Name array. But before calling webservice you are copying Test_Name data to web array, so your web[] will be blank because there is no data in Test_Name.
Make web[] global
String [] web;
fill it in updateDisplay()
protected void updateDisplay(){
if (SchedList != null) {
for (Test_Sched test_Sched : SchedList) {
Duration.add(test_Sched.getDuration());
Test_Name.add(test_Sched.getTest_Name());
Count++;
}
web = Test_Name.toArray(new String[Test_Name.size()]);
}
}

Categories