Fragment, Volley and RecyclerView - android

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();
}
...
}

Related

Setup Viewpager with recyclerview and Asynctask

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")){......}

Error in Adding data into Recycleview which are fetched from server

I am trying to get strings(usernames) from Server wanna put it into Recycle.For that, I am using JSON to fetch data and Asynctask to generate a new thread.I successfully getting usernames from the server but failed to put them in recycleview.
This is my Mainactivity.java
public class MainActivity extends AppCompatActivity {
BufferedReader reader;
private String content;
RecyclerView recyclerView;
Adapter madapter;
List<String> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ApiAsyncTask().execute();
}
private class ApiAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
getData();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
recyclerView=(RecyclerView)findViewById(R.id.rv123);
recyclerView.setLayoutManager(new LinearLayoutManager());
data.add("name");
Dataadapter madapter = new Dataadapter(data);
recyclerView.setAdapter(madapter);
}
}
private void getData(){
try {
URL url = new URL("https://jsonplaceholder.typicode.com/comments");
URLConnection conn = url.openConnection();
conn.setDoOutput(false);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
content = sb.toString();
Log.e("TAG", "Response is -> " + content);
JSONArray jsonArray = new JSONArray(content);
for(int i=0;i<=4;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
Log.e("TAG", "Username is -> " + name);}
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is my Adapter
public class Dataadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public TextView textView;
private List<String> data;
public Dataadapter(List<String> data) {
this.data = data;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv);
}}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View dataView = layoutInflater.inflate(R.layout.container, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(dataView);
return myViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
textView.setText(data.get(position));
}
#Override
public int getItemCount() {
return data.size();
}
}
Using 2 XML files.One is Mainactivity.xml and other is Container.xml.Please help me on how to show usernames (which I fetched from the server)into recycleview.For now, when I run the app, it just showing the layout only.Not getting any username in that layout.But in my log, I can see the usernames.Thank u
Just add the objects to your list
for(int i=0;i<=4;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
data.add(jsonObject.getString("name"));
}
And the LinearLayoutManager constructor takes one parameter, a Context.
In your onPostExecute, do this -
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
Try this code, I tested it and it's working.
Here's MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
BufferedReader reader;
RecyclerView recyclerView;
Dataadapter madapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv123);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
madapter = new Dataadapter();
recyclerView.setAdapter(madapter);
new ApiAsyncTask().execute();
}
private class ApiAsyncTask extends AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... voids) {
return getData();
}
#Override
protected void onPostExecute(List<String> names) {
madapter.updateData(names);
}
}
private List<String> getData() {
List<String> data = new ArrayList<>();
try {
URL url = new URL("https://jsonplaceholder.typicode.com/comments");
URLConnection conn = url.openConnection();
conn.setDoOutput(false);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line);
}
// Append Server Response To Content String
String content = sb.toString();
Log.e("TAG", "Response is -> " + content);
JSONArray jsonArray = new JSONArray(content);
for (int i = 0; i < 50; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
Log.e("TAG", "Username is -> " + name);
data.add(name);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "getData: " + data.size());
return data;
}
}
and here's Dataadapter.java
public class Dataadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public TextView textView;
private List<String> data;
public Dataadapter() {
data = new ArrayList<>();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View dataView = layoutInflater.inflate(R.layout.container, parent, false);
return new MyViewHolder(dataView);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
textView.setText(data.get(position));
}
#Override
public int getItemCount() {
return data.size();
}
public void updateData(List<String> data) {
this.data = data;
notifyDataSetChanged();
}
}
The data returned from the API endpoint contains 500 items, I used 50 instead to load faster.
You should not make holder's textView as adapter's local variable and assign value on holder's constructor. Since ViewHolder may be reused and parsed to Adapter.onBindViewHolder() and then the textView used in onBindViewHolder() method is not the textView in holder( the ViewHolder constructor not called). You can make textView as MyViewHolder's variable and use holder.getTextView().setText(item) to set text.

Retrieve JSON recycler image gallery data and display in manner like instagram - click image gallery open in Recyclerview with image name

I want to retrieve json recycler image gallery data and display in RecyclerView manner, anyone help me
like Instagram click image gallery open in RecyclerView with image name
Currently I am displaying in a grid manner I don't no how to pass from this recycler to another recycler :
ProfilActivity:
public class ProfilActivity extends AppCompatActivity {
private RecyclerView recyclerView;
ArtistAdapterGallary artistAdapterGallary;
ArrayList < DataArtist > data = new ArrayList < > (); //its in progress dialog arraylist to retrieve array data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask < String, String, String > {
ProgressDialog pdLoading = new ProgressDialog(ProfilActivity.this);
HttpURLConnection conn;
URL url = null;
#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 {
url = new URL("http://exxxxxxxxxxxxxx");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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) {
//this method will be running on UI thread
pdLoading.dismiss();
pdLoading.dismiss();
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);
DataArtist artistPic = new DataArtist();
artistPic.artistName = json_data.getString("name");
artistPic.artistImage = json_data.getString("profile_image");
data.add(artistPic);
}
// Setup and Handover data to recyclerview
recyclerView = (RecyclerView) findViewById(R.id.profileGride);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 3);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
artistAdapterGallary = new ArtistAdapterGallary(ProfilActivity.this, data);
// recyclerView.setLayoutManager(new LinearLayoutManager(ProfileGrideActivity.this));
recyclerView.setAdapter(artistAdapterGallary);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Custom Adatpter
public class ArtistAdapterGallary extends RecyclerView.Adapter < ArtistAdapterGallary.MyViewHolder > {
private Context context;
private LayoutInflater inflater;
List < DataArtist > data = new ArrayList < > ();
public ArtistAdapterGallary(ProfilActivity context, List < DataArtist > data1) {
this.context = context;
this.data = data1;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gallary_layout, parent, false);
return new ArtistAdapterGallary.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ArtistAdapterGallary.MyViewHolder holder, int position) {
final DataArtist current = data.get(position);
holder.artistname.setText(current.artistName);
Glide.with(context).load(data.get(position).getArtistImage()).into(holder.artistImage);
holder.artistImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Main2Activity.class);
intent.putExtra("link", current.getArtistImage());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView artistImage;
TextView artistname;
private View view;
public MyViewHolder(View itemView) {
super(itemView);
artistImage = (ImageView) itemView.findViewById(R.id.imageGride);
artistname = (TextView) itemView.findViewById(R.id.artistName);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Main2Activity.class);
DataArtist artistData = (DataArtist) view.getTag();
String strUrl = artistData.getArtistImage();
String product1 = artistData.getArtistName();
intent.putExtra("ARTIST_IMG", strUrl);
intent.putExtra("ARTIST_NAME", product1);
// intent.putExtra("Your string key",product1);
context.startActivity(intent);
}
}
}
DataArtist :
public class DataArtist {
public String artistImage;
public String artistName;
public String artistId;
private boolean isSelected = false;
public DataArtist() {
this.artistImage = artistImage;
this.artistName = artistName;
}
public String getArtistId() {
return artistId;
}
public void setArtistId(String artistId) {
this.artistId = artistId;
}
public String getArtistImage() {
return artistImage;
}
public void setArtistImage(String artistImage) {
this.artistImage = artistImage;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getArtistName() {
return artistName;
}
public void setSelected(boolean selected) {
boolean isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
and I want to know how I can call this data into another recycler

how to send and receive data to server?

hi guys i want to sent location name and some other string values to the server...i am new in android so i dont know much about it....i pass the location and other values with url...url hits but the values are not receive by the server..help please me out...
public class SearchResult extends AppCompatActivity {
private ListView lvSearch;
private ProgressDialog dialog;
private final String URL_TO_HIT = "http://www.abcd.com/mobile_search.php";
private String location = "bathinda";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
setContentView(R.layout.activity_search_result);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Search Result");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading. Please wait...");
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvSearch = (ListView)findViewById(R.id.lvSearch);
Bundle bundle = getIntent().getExtras();
String bar = bundle.getString("bar");
String nights = bundle.getString("nights");
String nearby = bundle.getString("nearby");
String deals = bundle.getString("deals");
// To start fetching the data when app start, uncomment below line to start the async task.
new JSONTask().execute(URL_TO_HIT, location, bar, nights, nearby, deals );
}
public class JSONTask extends AsyncTask<String,String, List<SearchData> >{
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<SearchData> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("search");
List<SearchData> searchDataList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
SearchData searchData = gson.fromJson(finalObject.toString(), SearchData.class);
searchDataList.add(searchData);
}
return searchDataList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final List<SearchData> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result != null) {
SearchAdapter adapter = new SearchAdapter(getApplicationContext(), R.layout.searchresultrow, result);
lvSearch.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Not able to fetch data from server, please check internet", Toast.LENGTH_SHORT).show();
}
}
}
public class SearchAdapter extends ArrayAdapter{
private List<SearchData> searchDataList;
private int resource;
private LayoutInflater inflater;
public SearchAdapter(Context context, int resource, List<SearchData> objects) {
super(context, resource, objects);
searchDataList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.searchimg11 = (ImageView)convertView.findViewById(R.id.searchimg1);
holder.barname1 = (TextView)convertView.findViewById(R.id.barname);
holder.address1 = (TextView)convertView.findViewById(R.id.address);
holder.offer1 = (TextView)convertView.findViewById(R.id.offer);
holder.hourtext1 = (TextView)convertView.findViewById(R.id.hourtext);
holder.coststext1 = (TextView)convertView.findViewById(R.id.coststext);
holder.textv11 = (TextView)convertView.findViewById(R.id.textv1);
holder.featuredtext1 = (TextView)convertView.findViewById(R.id.featuredtext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar);
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(searchDataList.get(position).getBar_image(), holder.searchimg11, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
// progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
// progressBar.setVisibility(View.GONE);
}
});
holder.barname1.setText(searchDataList.get(position).getBarname());
holder.address1.setText(searchDataList.get(position).getLocation());
holder.offer1.setText( searchDataList.get(position).getOffers());
holder.hourtext1.setText( searchDataList.get(position).getOpen_hours());
holder.coststext1.setText(searchDataList.get(position).getCost_for_two());
holder.textv11.setText(searchDataList.get(position).getFreebe());
holder.featuredtext1.setText(searchDataList.get(position).getFeaured());
return convertView;
}
class ViewHolder{
private ImageView searchimg11;
private TextView address1;
private TextView offer1;
private TextView hourtext1;
private TextView coststext1;
private TextView textv11;
private TextView barname1;
private TextView featuredtext1;
}
}
}
You are not passing any parameters to the server there . You are calling URL without any parameters
Read this solution to know how to pass parameters to HttpURLConnection using POST
How to add parameters to HttpURLConnection using POST
I did not go through your code. I suggest you to use the library to do much of the work instead of you developing on top of HTTP stack.
Use Retrofit(http://square.github.io/retrofit/) or Volley(https://developer.android.com/training/volley/index.html).
Retrofit is easy to use and manage but volley give you lot of control. Since you are new to programming on the client side, I suggest you use the Retrofit. You can't go wrong with sending JSON data, and few post using this libraries.

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.

Categories

Resources