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()]);
}
}
Related
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
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());
}
**here is my code in on create for questions on next button...**
public class QuizActivity extends AppCompatActivity {
private TextView quizQuestion;
private RadioGroup radioGroup;
private RadioButton optionOne;
private RadioButton optionTwo;
private RadioButton optionThree;
private RadioButton optionFour;
private int currentQuizQuestion;
private int quizCount;
private int score=0;
private int pagecount=1;
private QuizWrapper firstQuestion;
private List<QuizWrapper> parsedObject;
TextView pgcount;
ArrayList<String> arrayList;
int id=0;
**this is on oncareate function**
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
quizQuestion = (TextView)findViewById(R.id.quiz_question);
arrayList=new ArrayList<String>();
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
optionOne = (RadioButton)findViewById(R.id.radio0);
optionTwo = (RadioButton)findViewById(R.id.radio1);
optionThree = (RadioButton)findViewById(R.id.radio2);
// optionFour = (RadioButton)findViewById(R.id.radio3);
final String rad= String.valueOf(radioGroup.getCheckedRadioButtonId());
pgcount = (TextView) findViewById(R.id.countpage);
// Button previousButton = (Button)findViewById(R.id.previousquiz);
Button nextButton = (Button)findViewById(R.id.nextquiz);
here i am calling the asynch class
AsyncJsonObject asyncObject = new AsyncJsonObject();
asyncObject.execute("");
**here is my next button for next question load..**
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int radioSelected = radioGroup.getCheckedRadioButtonId();
final int userSelection = getSelectedAnswer(radioSelected);
final int correctAnswerForQuestion = firstQuestion.getCorrectAnswer();
if(userSelection == correctAnswerForQuestion){
// correct answer
// Toast.makeText(QuizActivity.this, "You got the answer correct", Toast.LENGTH_LONG).show();
score++;
}
**here i am checking the whether it is button clicked or not**
if (radioGroup.getCheckedRadioButtonId()==-1) {
Toast.makeText(QuizActivity.this, "Please Select Answer", Toast.LENGTH_SHORT).show();
}else {
currentQuizQuestion++;
pagecount++;
}
**and here is my asynctask class for loading questions...**
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost("http://learningcastles.com/chiesi/api/get_question");
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " +
jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
here is preexecute function
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(QuizActivity.this, "Setting Up Quiz","Please Wait....", true);
}
**here is first time questions to be set**
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
System.out.println("Resulted Value: " + result);
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
quizQuestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
pgcount.setText(String.valueOf(pagecount) + "/5");
}
here is string builder
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
**List of array to return object**
private List<QuizWrapper> returnParsedJsonObject(String result){
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
jsonArray = resultObject.optJSONArray("quiz_questions");
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonArray != null) {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("id");
String question = jsonChildNode.getString("question");
String answerOptions = jsonChildNode.getString("possible_answers");
int correctAnswer = jsonChildNode.getInt("correct_answer");
int is_delete = jsonChildNode.getInt("is_delete");
newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer,is_delete);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return jsonObject;
}
**selecting the correct answer id**
private int getSelectedAnswer(int radioSelected){
int answerSelected = 0;
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
// if(radioSelected == R.id.radio3){
// answerSelected = 4;
// }
return answerSelected;
}
unchecking the button for next question
private void uncheckedRadioButton(){
optionOne.setChecked(false);
optionTwo.setChecked(false);
optionThree.setChecked(false);
// optionFour.setChecked(false);
}
***problem is here in oncreate where i am calling on radiogroupcheckedchangelistner..where i am taking static id and set it when radio button is checked and comparing it with my correct answer for question..***
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radGroup, int i) {
***setting button to be disabled after one check***
optionOne.setEnabled(false);
optionTwo.setEnabled(false);
optionThree.setEnabled(false);
checking user selection
final int radioSelected = radioGroup.getCheckedRadioButtonId();
final int userSelection = getSelectedAnswer(radioSelected);
final int correctAnswerForQuestion =
getting correct answers
firstQuestion.getCorrectAnswer();
setting up ids when user check the button
if (optionOne.isChecked()){
id=1;
}
if (optionTwo.isChecked()){
id=2;
}
if (optionThree.isChecked()){
id=3;
}
// Toast.makeText(QuizActivity.this, ""+correctAnswerForQuestion+"="+""+id, Toast.LENGTH_LONG).show();
***here i am comparing the id that checked and correct answer of question then setting the color but for second question the id remain 1 why??***
if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.GREEN);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.GREEN);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion){
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.GREEN);
}
// else {
// optionOne.setTextColor(Color.RED);
// optionOne.setTextColor(Color.RED);
// optionOne.setTextColor(Color.RED);
// }
}
});
**but it is not setting the color for correct answer correctly what i am doing wrong any help would be appreciated..**
Just looked in your Code and I found this:
if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.GREEN);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion) {
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.GREEN);
optionThree.setTextColor(Color.RED);
}
else if (id==correctAnswerForQuestion){
optionOne.setTextColor(Color.RED);
optionTwo.setTextColor(Color.RED);
optionThree.setTextColor(Color.GREEN);
}
All the conditions in the IF statements are the same!!
(id==correctAnswerForQuestion).
Change the Conditions to appropriate Logic because otherwise the other else if statements are useless.
I have an activity which searches for a query (using async task and server side PHP) and gives out a list in recycler view, Now i want to implement endless/infinite scrolling when user reaches bottom. I have tried to do that using EndlessScrollListener. There are two problems i need help with.
first, the new list recreates itself instead of appending to the old list.
second, the current_page int variable keeps its value from the previous search and scroll, means when running AsyncTask for second time, the current_page int variable still retains the value from the first time and does not reset.
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private LinearLayoutManager mLayoutManager;
private String searchQuery;
SearchView searchView = null;
private String query;
private EndlessRecyclerOnScrollListener mScrollListener = null;
private SwipeRefreshLayout mSwipeRefreshLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRVFish.setLayoutManager(mLayoutManager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
int startrow =0;
String type="";
String filetype="";
AsyncFetch myTask = new AsyncFetch(query, startrow, type, filetype);
myTask.execute();
mScrollListener = new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int current_page) {
int startrow=current_page;
String type="";
String filetype="";
AsyncFetch myTask = new AsyncFetch(query, startrow, type, filetype);
myTask.execute();
}
};
mRVFish.addOnScrollListener(mScrollListener);
// enable pull down to refresh
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
int startrow =0;
String type="";
String filetype="";
AsyncFetch myTask = new AsyncFetch(query, startrow, type, filetype);
myTask.execute();
// after refresh is done, remember to call the following code
if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false); // This hides the spinner
}
}
});
}
}
// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
int startrow;
String type;
String filetype;
public AsyncFetch(String searchQuery, int startrow, String type, String filetype){
this.searchQuery=searchQuery;
this.startrow = startrow;
this.type = type;
this.filetype=filetype;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://someurl/json/search.php");
} 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("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery).appendQueryParameter("startrow", String.valueOf(startrow));
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} 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("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
try {
fishData.fileName = URLDecoder.decode(json_data.getString("file"), "UTF-8");
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
fishData.fileName=json_data.getString("file");
}
fishData.linkName = json_data.getString("link");
fishData.reg_date = json_data.getString("reg_date");
fishData.fileSize = json_data.getString("filesize");
data.add(fishData);
}
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFish.setAdapter(mAdapter);
if(jArray.length()>19)
mScrollListener.setLoading(false);
else
mScrollListener.setLoading(true);
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
EndlessRecyclerOnScrollListener.java
public abstract class EndlessRecyclerOnScrollListener extends
RecyclerView.OnScrollListener {
public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = false; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 0; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;
private int current_page = 20;
private LinearLayoutManager mLayoutManager;
public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
this.mLayoutManager = linearLayoutManager;
}
#Override
public void onScrolled(RecyclerView mRVFish, int dx, int dy) {
super.onScrolled(mRVFish, dx, dy);
if(dy < 0) {
return;
}
// check for scroll down only
visibleItemCount = mRVFish.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
// to make sure only one onLoadMore is triggered
synchronized (this) {
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// End has been reached, Do something
current_page=current_page+20;
onLoadMore(current_page);
loading = true;
}
}
}
public void setLoading(boolean loading) {
this.loading = loading;
}
public abstract void onLoadMore(int current_page);
}
first, the new list recreates itself instead of appending to the old list.
If you set a new adapter you swap the content of the recycler view. I think you do it in the following code
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFish.setAdapter(mAdapter);
To append the data you need to add new elements to the adapter's dataset (dataset where you get data to bind views in your adapter) and then call adapter.notifyDataSetChanged() or better adapter.notifyItemRangeInserted(int positionStart, int itemCount)
There are also a number of tools to optimize adding the elements, like DiffUtil
second, the current_page int variable keeps its value from the previous search and scroll, means when running AsyncTask for second time
Not sure what was library developer's idea here, but the easiest way would be to just create a method in the EndlessRecyclerOnScrollListener similar to:
public void resetPage() {
current_page = 20;
}
And call it before invoking new search.
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.