Setup Viewpager with recyclerview and Asynctask - android

I have a ViewPager with 3 Fragment and as per Android documentation ViewPager.setOffscreenPageLimit(1); is 1 minimum. I am facing an issue when I have multiple Fragments in ViewPager and each Fragment has to load some data from a Server so for that I am calling AsyncTask in each Fragment to get data first then load into a Fragment.
I can see in the Log that I am getting the data from the Server but as soon as I call the second Fragment, I can see it also calling next Fragment onCreateView that's why I am having a hard time in setting the RecyclerView. I tried by calling the Adapter at different scenario also by adapter3.notifyDataSetChanged(); but nothing help.
Parent Fragment of ViewPager.
public class ViewUserProfile extends Fragment{
ViewPager ViewPager;
UserProfile_TabAdapter tabAdapter;
TabLayout tabLayout;
View view;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.view_userprofile, container, false);
ViewPager = view.findViewById(R.id.up_Viewpager_ViewPager);
ViewPager.setOffscreenPageLimit(1);
ViewPager.setPageMargin(10);
tabAdapter=new TabAdapter(getFragmentManager(),getActivity(),Uda.getFN());
tabLayout= view.findViewById(R.id.up_Viewpager_Tab);
tabLayout.setupWithViewPager(userInfo_ViewPager);
return view;
}
}
Fragment Which is not loading its data:
public class UseConnectfragment extends Fragment {
RecyclerView FriendsRecycler,FollowingRecylcer,FollowerRecycler;
ArrayList<viewUserProfile_Wrapper> followersList;
ArrayList<viewUserProfile_Wrapper> friendsList;
ArrayList<viewUserProfile_Wrapper> followingList;
UserConnections_Adapter adapter1;
UserConnections_Adapter adapter2;
UserConnections_Adapter adapter3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.userprofile_connections,container,false);
setRetainInstance(true);
FriendsRecycler=view.findViewById(R.id.userConnections_recyclerFriends);
FollowingRecylcer=view.findViewById(R.id.userConnections_recyclerFollowing);
FollowerRecycler=view.findViewById(R.id.userConnections_recyclerFollower);
FriendsRecycler.setHasFixedSize(true);
FollowingRecylcer.setHasFixedSize(true);
FollowerRecycler.setHasFixedSize(true);
FriendsRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 3));
FollowingRecylcer.setLayoutManager(new GridLayoutManager(getActivity(), 3));
FollowerRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 3));
adapter1=new UserConnections_Adapter(friendsList);
adapter2=new UserConnections_Adapter(followingList);
adapter3=new UserConnections_Adapter(followersList);
return view;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.d(TAG,"Set User Visible Running");
if (isVisibleToUser){
Log.d(TAG,"User Connection Tab Is Visible So Call Server Now");
new GetConncetions().execute();
}
}
public class UserConnections_Adapter extends RecyclerView.Adapter<UseConnections_fragment.UserConnections_Adapter.ViewHolder> {
ArrayList<viewUserProfile_Wrapper> connectionList;
public UserConnections_Adapter(ArrayList<viewUserProfile_Wrapper> connectionList) {
this.connectionList = connectionList;
}
#Override
public UserConnections_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.userprofile_connections_singleitem,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(UserConnections_Adapter.ViewHolder holder, int i) {
final viewUserProfile_Wrapper wrapper=connectionList.get(i);
Log.d(TAG,"Wrapper on bind "+wrapper.getUserName()+" "+connectionList.size());
holder.userName.setText(wrapper.getUserName());
Glide.with(getActivity()).load(wrapper.getUserImage()).into(holder.userImage);
holder.userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "User Name "+wrapper.getUserName()+" User ID "+wrapper.getID(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return connectionList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView userImage;
public ViewHolder(View itemView) {
super(itemView);
userName=itemView.findViewById(R.id.userConnection_Name);
userImage=itemView.findViewById(R.id.userConnection_friends);
}
}
}
public class GetConncetions extends AsyncTask<Void,Void,String> {
private static final String All_Connections="http://localhost/test/Android/getallon.php";
BufferedReader reader;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setCancelable(false);
progressDialog.setTitle("Loading...");
progressDialog.show();
}
#Override
protected String doInBackground(Void... voids) {
Log.d(TAG,"Starting Do in background");
// addedInterest=new ArrayList<>();
try {
URL url=new URL(All_Connections);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
connection.setConnectTimeout(5000);
OutputStream outputStream=connection.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
writer.write(data);
writer.flush();
writer.close();
outputStream.close();
//GET INTEREST JSON FROM SERVER
Log.d(TAG,"Response Code "+connection.getResponseCode());
if (connection.getResponseCode()==200) {
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
Log.d(TAG, "Appending JSON into String Buffer");
}
Log.d(TAG,"JSON Received "+stringBuffer);
JSONObject jsonObject=new JSONObject(stringBuffer.toString());
String callResult=jsonObject.getString("status");
Log.d(TAG,"Server Call Result "+callResult);
//Make These String out of the scope so we can access this outside if statement
String ID,Name,Image;
if (callResult.equals("SUCCESS")){
Log.d(TAG,"Server Call Is Success");
followersList=new ArrayList<>();
followingList=new ArrayList<>();
friendsList =new ArrayList<>();
JSONArray followerDataArray=jsonObject.getJSONArray("data1");
for (int i = 0; i <followerDataArray.length() ; i++) {
String image=followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData=new viewUserProfile_Wrapper(image);
followersList.add(followerData);
}
JSONArray followingDataArray=jsonObject.getJSONArray("data2");
for (int i = 0; i <followingDataArray.length() ; i++) {
String image=followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData=new viewUserProfile_Wrapper(image);
followingList.add(followerData);
}
JSONArray friendDataArray=jsonObject.getJSONArray("data3");
for (int i = 0; i <friendDataArray.length() ; i++) {
String image=followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData=new viewUserProfile_Wrapper(image);
friendsList.add(followerData);
}
return null;
}
}
return "Success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String v) {
super.onPostExecute(v);
Log.d(TAG,"On Post running");
progressDialog.dismiss();
if (v!=null){
if (v.equals("Success")){
FriendsRecycler.setAdapter(adapter1);
FollowingRecylcer.setAdapter(adapter2);
FollowerRecycler.setAdapter(adapter3);
}else {
Toast.makeText(getActivity(), "Server Error.Try Again", Toast.LENGTH_SHORT).show();
}
}
}
}
}

Call your asynctask when the fragment is visible add this in your fragments
EDIT
Change your following code
JSONArray followingDataArray = jsonObject.getJSONArray("data2");
for (int i = 0; i < followingDataArray.length(); i++) {
String image = followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
followingList.add(followerData);
}
JSONArray friendDataArray = jsonObject.getJSONArray("data3");
for (int i = 0; i < friendDataArray.length(); i++) {
String image = followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
friendsList.add(followerData);
}
to this
JSONArray followingDataArray = jsonObject.getJSONArray("data2");
for (int i = 0; i < followingDataArray.length(); i++) {
String image = followingDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
followingList.add(followerData);
}
JSONArray friendDataArray = jsonObject.getJSONArray("data3");
for (int i = 0; i < friendDataArray.length(); i++) {
String image = friendDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
friendsList.add(followerData);
}
As commented by I_A_Mok remove return null from
if (callResult.equals("SUCCESS")){......}

Related

Fragment, Volley and RecyclerView

I hope someone out there can help me solve my problem. I have android app that have 3 tabs, i use fragment, first tab is recyclerView list, second tabs is map. the problem is in tabs 1, i need to fetch data with volley to recyclerView on tabs 1, if run fine but i cannot see the data on first app start, but when i change tab and back to tab 1 again it will refresh the data and show the data on recyclerView.
Adapter.java
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Warkop> mWarkop;
private LayoutInflater inflater;
public CustomListAdapterWarkop(Context context, List<Warkop> mWarkop) {
this.context=context;
inflater= LayoutInflater.from(context);
this.mWarkop = mWarkop;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_warkop_row, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder viewHolder = (ItemViewHolder) holder;
Warkop current = mWarkop.get(position);
viewHolder.tvNamaWarkop.setText(current.getNamaWarkop());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage)
.showImageOnLoading(R.drawable.noimage).build();
imageLoader.displayImage(current.getFotoWarkop(), viewHolder.ivFotoWarkop, options);
}
#Override
public int getItemCount() {
return mWarkop.size();
}
}
ItemHolder.java
package com.andylah.warkopedia;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by andylah on 11/3/2017.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public ImageView ivFotoWarkop;
public TextView tvNamaWarkop;
public ItemViewHolder(View itemView) {
super(itemView);
tvNamaWarkop = itemView.findViewById(R.id.nama_warkop);
ivFotoWarkop = itemView.findViewById(R.id.image_warkop);
}
}
Tab 1.java
public class tabSatu extends Fragment {
private static final String TAG = tabDua.class.getSimpleName();
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private boolean isFragmentLoaded = false;
View vTabSatu;
private RecyclerView recyclerView;
public static List<Warkop> warkopList = new ArrayList<Warkop>();
private CustomListAdapterWarkop warkopAdapter;
public tabSatu(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new AsyncFetch().execute();
vTabSatu = inflater.inflate(R.layout.tabsatu_view, container, false);
recyclerView = vTabSatu.findViewById(R.id.warkop_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
Log.d("LOG : ", "onCreatedView Run");
// Inflate the layout for this fragment
return vTabSatu;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
Log.d("LOG : ", "onViewCreated Run");
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded ) {
// Load your data here or do network operations here
isFragmentLoaded = true;
//new AsyncFetch().execute();
}else{
isFragmentLoaded = false;
Log.d("LOG : ", "isFragmentLoaded = false");
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading list warkop ...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL(AppConfig.LOAD_WARKOP);
} 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");
// 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 ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try{
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if(!error){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
warkop.setNamaWarkop(jsonObject.getString("nama_warkop"));
warkop.setAlamatWrkop(jsonObject.getString("alamat_warkop"));
warkop.setKotaWarkop(jsonObject.getString("kota_warkop"));
warkop.setLatWarkop(Double.parseDouble(jsonObject.getString("lat_warkop")));
warkop.setLangWarkop(Double.parseDouble(jsonObject.getString("long_warkop")));
warkop.setIsWifi(Integer.parseInt(jsonObject.getString("is_wifi")));
warkop.setIsToilet(Integer.parseInt(jsonObject.getString("is_toilet")));
warkop.setIsTv(Integer.parseInt(jsonObject.getString("is_tv")));
warkop.setIsColokan(Integer.parseInt(jsonObject.getString("is_colokan")));
warkop.setIsParkir(Integer.parseInt(jsonObject.getString("is_parkir")));
warkop.setFotoWarkop(jsonObject.getString("foto_warkop"));
warkopList.add(warkop);
}
}else{
String errorMsg = object.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Problem: Even you call notifyDataSetChanged() but there are no data in Adapter.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
}
So you need to set and notify warkopList to Adapter after API call. It will help you.
tabSatu:
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try {
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if (!error) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
...
warkopList.add(warkop);
adapter.setItems(warkopList);
}
}
...
}
CustomListAdapterWarkop: add setItem() method to Adapter
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
public void setItems(List<WarkopList> warkopList) {
mWarkop = warkopList;
notifyDataSetChanged();
}
...
}

displaying data from database into cardview list onclick button

I developed a search function and it worked successfully. The class responsible for the search is called from onQueryTextSubmit and there was nothing wrong with it.
Now I wanted to add other thing that is a button in the same activity of the search bar that when it's clicked all data from the database is displayed in cardView. When I added the code the onQueryTextSubmit method is no longer working plus the button isn't displaying the data. I do not know where is the problem. Here is the code for the whole activity.
PS: for some reason it says that showdata() method is never used.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find_skill);
button = (Button) findViewById(R.id.button);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewer);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listView = (ListView) findViewById(R.id.searchList);
searchView = (SearchView) findViewById(R.id.searchView);
noData = (ImageView) findViewById(R.id.nodata);
noNetwork = (ImageView) findViewById(R.id.nonetwork);
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
SenderReceiver sr = new SenderReceiver(FindSkill.this, urlAdress,listView, query,noData,noNetwork);
sr.execute();
return false;
}
#Override
public boolean onQueryTextChange(String query) {
return false;
}});}
private void getData() {
class GetData extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(FindSkill.this, "Fetching Data", "Please wait...", false, false);
}
#Override
protected void onPostExecute(String res) {
super.onPostExecute(res);
progressDialog.dismiss();
parseJSON(res);
}
#Override
protected String doInBackground(Void... params) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(Config.GET_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetData gd = new GetData();
gd.execute();
}
public void showData(){
adapter = new CardAdapter(Config.skills,Config.ids);
recyclerView.setAdapter(adapter);
}
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
Config.skills[i] = getSkill(j);
Config.ids[i] = getId(j);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getSkill(JSONObject j){
String name = null;
try {
name = j.getString(Config.JSON_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
private String getId(JSONObject j){
String id = null;
try {
id = j.getString(Config.JSON_ID);
} catch (JSONException e) {
e.printStackTrace();
}
return id;
}
This is the Config class:
public class Config {
public static String[] skills;
public static String[] ids;
public static final String GET_URL = "http://skillsexchangecyprus.com/SEC/mainList.php";
public static final String JSON_ID = "id";
public static final String JSON_NAME = "skill";
public static final String TAG_JSON_ARRAY="result";
public Config(int i) {
skills = new String[i];
ids = new String[i];
}
}
Card Adapter class:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
List<ListItem> items;
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i =0; i<items.size(); i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem myAdapter = items.get(position);
holder.skillName.setText(myAdapter.getSkill());
holder.skillId.setText(String.valueOf(myAdapter.getId()));
}
#Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView skillId;
public TextView skillName;
public ViewHolder(View itemView) {
super(itemView);
skillId = (TextView) itemView.findViewById(R.id.skillId);
skillName = (TextView) itemView.findViewById(R.id.skillName);
}
}
}
You did't call your showData() method. You need to create an instance of CardAdapter and set this adapter to your recyclerView.
Update OnCreate() method as below:
..............
....................
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
config = new Config(INITIAL_VALUE);
// Adapter
adapter = new CardAdapter(config.skills,config.ids);
recyclerView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
....................
..............................
Use adapter.notifyDataSetChanged() to update recyclerView with new items.
Update parseJson() method as below:
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
config.skills[i] = getSkill(j);
config.ids[i] = getId(j);
// Update
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
In your CardAdapter constructor, use skills.length instead of items.size()
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i = 0; i < skills.length; i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
Hope this will work~

AsyncTask + JSON parsing to Listview only sometimes shows data

Sometimes it shows data, sometimes it shows nothing.
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
arraylist1 = new ArrayList<>();
listOfNews = (ListView) view.findViewById(R.id.listView);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("url");
}
});
return view;
}
public class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... url) {
String st = readURL(url[0]);
Log.d("st", st);
return st;
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
Log.d(i+":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
JSONObject productObject = jsonArray.getJSONObject(i);
JSONObject img = productObject.getJSONObject("image");
JSONObject da = img.getJSONObject("data");
arraylist1.add(new HotNews(
da.getString("filename"),
productObject.getString("title"),
productObject.getString("article_by"),
productObject.getString("date_publish"),
productObject.getString("short_description")
));
}
Log.d("jsonArray news list1", arraylist1.size() + "");
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new ListViewAdapter(view.getContext(), R.layout.list_view_adapter, arraylist1);
listOfNews.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
//create url object
URL url = new URL(theUrl);
//create url connection
URLConnection urlConnection = url.openConnection();
//wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
public class ListViewAdapter extends ArrayAdapter<HotNews> {
public ListViewAdapter(Context context, int resource, ArrayList<HotNews> arrayList) {
super(context, resource,arrayList);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
this.context = context;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = mInflater.inflate(R.layout.list_view_adapter, parent, false);
}
image = (ImageView) v.findViewById(R.id.imagetitle);
title = (TextView) v.findViewById(R.id.txtTitle);
doer = (TextView) v.findViewById(R.id.doer);
date = (TextView) v.findViewById(R.id.txtdate);
text = (TextView) v.findViewById(R.id.text);
final HotNews news = getItem(position);
Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(image);
title.setText(news.getTitle());
doer.setText(news.getDoer());
date.setText(news.getDate());
text.setText(news.getContent());
return v;
}
}
try this code :
public class HomeFragment extends Fragment {
private View view;
private ArrayList<HotNews> arraylist1;
private ListView listOfNews;
private int SUCCESS = 1;
private int FAILS = 0;
private int NO_DATA = 2;
private int ERROR = -1;
private ListViewAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
arraylist1 = new ArrayList<>();
listOfNews = (ListView) view.findViewById(R.id.listView);
adapter = new ListViewAdapter();
listOfNews.setAdapter(adapter);
new ReadJSON().execute("url");
return view;
}
public class ReadJSON extends AsyncTask<String, Integer, Integer> {
#Override
protected Integer doInBackground(String... url) {
String response = readURL(url[0]);
Log.d("response ", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
arraylist1.clear();
if(jsonArray.length()>0) {
for (int i = 0; i < jsonArray.length(); i++) {
Log.d(i + ":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
JSONObject productObject = jsonArray.getJSONObject(i);
JSONObject img = productObject.getJSONObject("image");
JSONObject da = img.getJSONObject("data");
arraylist1.add(new HotNews(
da.getString("filename"),
productObject.getString("title"),
productObject.getString("article_by"),
productObject.getString("date_publish"),
productObject.getString("short_description")
));
}
}else{
return NO_DATA;
}
Log.d("jsonArray news list1", arraylist1.size() + "");
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
Log.d("parseResponse", integer + "");
if(integer==SUCCESS){
adapter.notifyDataSetChanged();
}else if(integer==ERROR){
Toast.makeText(getActivity(),"Server or Exception Error!", Toast.LENGTH_SHORT).show();
}else if(integer==NO_DATA){
Toast.makeText(getActivity(),"No Data!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(),"Some thing went wrong!", Toast.LENGTH_SHORT).show();
}
}
}
class ListViewAdapter extends BaseAdapter{
#Override
public int getCount() {
return arraylist1.size();
}
#Override
public Object getItem(int position) {
return arraylist1.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ListViewHolder holder;
if (v == null) {
v = LayoutInflater.from(getActivity()).inflate(R.layout.list_view_adapter, parent, false);
holder = new ListViewHolder(v);
v.setTag(holder);
}else{
holder = (ListViewHolder)v.getTag();
}
final HotNews news = arraylist1.get(position);
holder.title.setText(news.getTitle());
holder.doer.setText(news.getDoer());
holder.date.setText(news.getDate());
holder.text.setText(news.getContent());
Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(holder.image);
return v;
}
class ListViewHolder {
private ImageView image;
private TextView title,doer,date,text;
public ListViewHolder(View v){
image = (ImageView) v.findViewById(R.id.imagetitle);
title = (TextView) v.findViewById(R.id.txtTitle);
doer = (TextView) v.findViewById(R.id.doer);
date = (TextView) v.findViewById(R.id.txtdate);
text = (TextView) v.findViewById(R.id.text);
}
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
//create url object
URL url = new URL(theUrl);
//create url connection
URLConnection urlConnection = url.openConnection();
//wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
You are seeing this error, which is crashing the entire loop. You may be requesting 10 objects, but at the first object without that image attribute, it is exiting.
W/System.err: org.json.JSONException: No value for image
So, recommendation (other than using Retrofit to manage your JSON API's) would be to use the optType() methods rather than the getType() methods of the JSON objects.
For example,
JSONObject img = productObject.optJSONObject("image");
This will set img to null when the "image" attribute does not exist.
Just be aware of that later in case you have a NullPointerException when trying to use img on this line
JSONObject da = img.getJSONObject("data");

Limiting ListView with AsyncTask Using ArrayAdapter

I am developing app just like YOUTUBE. I am getting data from the server and showing it in listview. Because data is too big so i want to restrict list view to 5 items and then when I scroll down to the bottom of listview it should add 5 more item.
I am calling ASyncTask from fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(R.layout.tab_fragment_2, container, false);
listView = (ListView) view.findViewById(R.id.myList);
New.jsonAsyncTask.execute("my url select_video.php?");
}
Now I have separate JsonAsyncTask Class because I am calling it from 3 fragments just like above mentioned way..
public class JSONAsyncTask extends AsyncTask<String, String, List<SetDatails>> {
ListView listView1;
Context context1;
List<SetDatails> videoLiast1;
private static int tab_id;
public JSONAsyncTask(ListView listView, List<SetDatails> videoLiast,Context context,int id) {
this.listView1 = listView;
this.context1 = context;
this.videoLiast1 = videoLiast;
tab_id=id;
}
#Override
protected List<SetDatails> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader myReader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream myInputStream = connection.getInputStream();
myReader = new BufferedReader(new InputStreamReader(myInputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = myReader.readLine()) != null) {
buffer.append(line);
}
String Json_data = buffer.toString();
videoLiast1 = new ArrayList<>();
JSONObject parentObj = new JSONObject(Json_data);
JSONArray dataArray = parentObj.getJSONArray("data");
JSONObject tabObject = dataArray.getJSONObject(tab_id);
JSONArray videoArray = tabObject.getJSONArray("videos");
for (int i = 0; i < videoArray.length(); i++) {
int len=dataArray.length();
SetDatails setDatails = new SetDatails();
JSONObject arrayChild = videoArray.getJSONObject(i);
String vid_ID = arrayChild.getString("id");
setDatails.setVidID(vid_ID);
String movie_title = arrayChild.getString("name");
setDatails.setTitle(movie_title);
String movie_catagory = arrayChild.getString("category_name");
setDatails.setGenre(movie_catagory);
videoLiast1.add(setDatails);
}
return videoLiast1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (myReader != null) {
myReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(List<SetDatails> videoList) {
super.onPostExecute(videoList);
if(videoList!=null) {
try {
MyListAdapter myListAdapter = new MyListAdapter(context1, videoList);
listView1.setAdapter(myListAdapter);
}catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
I have created an Array adapter to fill list view.
public class MyListAdapter extends ArrayAdapter<SetDatails>{
public static int count =5;
List<SetDatails> videoList;
MyListAdapter(Context context,List<SetDatails> object){
super(context,R.layout.tab2_bookchilds,object);
videoList = object;
}
/**
* {#inheritDoc}
*/
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater=LayoutInflater.from(getContext());
View view = layoutInflater.inflate(R.layout.tab2_bookchilds, parent, false);
TextView title = (TextView)view.findViewById(R.id.txt_title);
title.setText(videoList.get(position).getTitle());
ImageView imgV_Thumbnail = (ImageView) view.findViewById(R.id.imgV_thumbnail);
Picasso.with(getContext())
.load(videoList.get(position).getThumbnail())
.error(R.drawable.icon_white)
.into(imgV_Thumbnail);
return view;
}
}
I have searched a lot and many people suggest getCount() method although I tried a lot to use this method but don't know how to do that.
Please guys help me because my app is ready to upload but I can't solve this one issue.

How to get result on onPostExecute from a separate Asynctask class to another fragment class?

I try it but it not show anything, I thing I don't know how to get result of onPostExecute method from separate AsyncTask class to fragment class.
Please Help me...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager()
.beginTransaction()
.add(R.id.Fragment_Container, new ForecastFragment(),
ForecastTask.class.getSimpleName())
.commit();
}
2- AsyncTask class
public class ForecastTask extends AsyncTask<String, String, `List<MovieModel>> {`
private final String LOG_TAG = ForecastTask.class.getSimpleName();
private List<MovieModel> movieModelList;
public AsyncResponse delegate=null;
public ForecastTask(AsyncResponse listener) {
delegate = listener;
}
#Override
protected List<MovieModel> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(param[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = new JSONObject(buffer.toString());
JSONArray jsonArray = jsonObject.getJSONArray("results");
movieModelList= new ArrayList<>();
//adding JSON Array data into MovieModel Class object
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setId(finalObject.getInt("id"));
movieModel.setTitle(finalObject.getString("title"));
movieModel.setPoster_path(finalObject.getString("poster_path"));
}
return movieModelList;
} catch (JSONException | IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public ForecastTask() {
super();
}
#Override
protected void onPostExecute( List<MovieModel> movieModels) {
delegate.processFinish(movieModels);
}
}
3- Fragment class
public class ForecastFragment extends Fragment implements AsyncResponse {
private String Popular = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxx";
private List<MovieModel> movieModels;
private static final String STATE_MOVIES ="state_movies";
CustomAdapter customAdapter=null;
GridView gridView=null;
View rootView=null;
ForecastTask forecastTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_main, container, false);
gridView=(GridView)rootView.findViewById(R.id.gridView);
movieModels=new ArrayList<MovieModel>();
forecastTask=new ForecastTask(this);
forecastTask.delegate = this;
forecastTask.execute(Popular);
customAdapter = new CustomAdapter(getActivity(), movieModels);
gridView.setAdapter(customAdapter);
return rootView;
}
#Override
public void processFinish(List<MovieModel> movieModels) {
this.movieModels=movieModels;
}
}
4- AsyncResponse Interface
public interface AsyncResponse {
void processFinish(List<MovieModel> movieModels);
}
You are not adding your Movie item in movieModelList. That's why it remains empty. You have to modify like -
movieModelList= new ArrayList<>();
//adding JSON Array data into MovieModel Class object
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setId(finalObject.getInt("id"));
movieModel.setTitle(finalObject.getString("title"));
movieModel.setPoster_path(finalObject.getString("poster_path"));
movieModelList.add(movieModel); //Add this line
}
Also, You have to set or refresh the adapter in your processFinish() callback.
Because ForecastTask will run in different thread and is asynchronous.
#Override
public void processFinish(List<MovieModel> movieModels) {
this.movieModels=movieModels;
customAdapter = new CustomAdapter(getActivity(), movieModels);
gridView.setAdapter(customAdapter);
}

Categories

Resources