I get data in JSON from API, and there are id and url. Now, i need to create a button "Add to favorites" for each image that i display. When i try to set adapter.setListener(this);, i get an error, because i can't use string format.
How can i resolve this problem? I spend 5 hours on this, and can't resolve it :(
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listItem);
favorites = findViewById(R.id.buttonFav);
catDetailsArrayList = new ArrayList<>();
myAdapter = new MyAdapter(MainActivity.this ,catDetailsArrayList);
searchbtn = findViewById(R.id.buttonSearch);
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
catDetailsArrayList.clear();
myAdapter.notifyDataSetChanged();
displayCats();
}
});
});
}
private void displayCats() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String jsonCatUrl2 = jsonObject1.getString("url");
String jsonCatId2 = jsonObject1.getString("id");
CatDetails catDetails = new CatDetails();
catDetails.setUrl(jsonCatUrl2);
catDetails.setId(jsonCatId2);
catDetailsArrayList.add(catDetails);
}
listView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
MyAdapter:
public class MyAdapter extends BaseAdapter {
public Activity activity;
public ArrayList<CatDetails> catDetailsArrayList;
public LayoutInflater inflater;
Button btn;
TextView idnr;
public MyAdapter(Activity activity, ArrayList<CatDetails> catDetailsArrayList) {
this.activity = activity;
this.catDetailsArrayList = catDetailsArrayList;
}
#Override
public Object getItem(int position) {
return catDetailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (inflater == null) {
inflater = this.activity.getLayoutInflater();
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
}
ImageView imageView = convertView.findViewById(R.id.ImageView);
final CatDetails catDetails = this.catDetailsArrayList.get(position);
Picasso.get().load(catDetails.getUrl()).into(imageView);
idnr =convertView.findViewById(R.id.textView);
btn = convertView.findViewById(R.id.buttonFav);
final String id = catDetails.getId();
idnr.setText(catDetails.getId());
return convertView;
}
#Override
public int getCount() {
return this.catDetailsArrayList.size();
}
I display the id that i receive from server for each item, it's ok, but i don't know how to set the button "add to favorites" to works fine. It must receive item id (that i received from server) as a param, but id is in string format.
final String id = catDetails.getId();
change it to
final String id = Integer.toString(catDetails.getId());
Related
The array "ary" receives the data from the server and the Adapter, but doesn't show the data in the ListView. Is there a problem with receiving the data after the onCreate() method?
Does anyone have an idea/solution?
public class ScheduleActivity extends AppCompatActivity {
public ListView list;
public ScheduleViewAdapter mSVAdapter;
public JSONArray ary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
buildList();
}
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter.notifyDataSetChanged();
}
private void buildList() {
final RequestQueue requestQueue = Volley.newRequestQueue(this);
// String URL1 = "http://10.0.2.2:3000/users/:userId/offers/";
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// vorläufiger hardcode
String userID = "5b2f9f3cd56ff67974d2f58e";
/* userID = settings.getString("userID", "");*/
String URL1 = "http://10.0.2.2:3000/orders/?buyerID=".concat(userID).concat("/userorder");
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("ConsoleText", response);
try {
JSONArray ary2 = new JSONArray(response);
setListView(ary2);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ConsoleText", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
requestQueue.add(stringRequest);
}
}
Okay, so this is an edit.
That's the adapter. maybe you can find the error here. Thanks:
public class ScheduleViewAdapter extends BaseAdapter{
private Context mContext;
private JSONArray orders;
public ScheduleViewAdapter() {
}
public ScheduleViewAdapter(Context mContext, JSONArray orders) {
this.mContext = mContext;
this.orders = orders;
}
#Override
public int getCount() {
if(orders == null){
return 0;
}else{
return orders.length();
}
}
#Override
public JSONObject getItem(int position) {
if(orders == null){
return null;
}else{
return orders.optJSONObject(position);
}
}
#Override
public long getItemId(int position) {
JSONObject object = getItem(position);
return object.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
//Only creates new view when recycling isn't possible
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_schedule, parent, false);
}
TextView tvItem =(TextView)convertView.findViewById(R.id.tvItem);
// TextView tvUserName =(TextView)convertView.findViewById(R.id.tvUserName);
// TextView tvAddress =(TextView)convertView.findViewById(R.id.tvAddress);
JSONObject json_data = getItem(position);
if(json_data != null){
try {
String type = json_data.getString("title");
// tvItem.append("" + json_data.getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
return convertView;
}
}
Change your method to this,
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
}
and onCreate to this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
buildList();
}
I want to make a List View from a JSON Array from a database,but i cant implement the method to put the array in a list,i got some idea about the method from this tutorial: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView
and this video:https://www.youtube.com/watch?v=u8iyFEZaHLU
this is my main code:
public class ViewDosen extends AppCompatActivity {
TextView tvWelcome;
ListView listView;
List<Publikasi> lstPublikasi;
JSONArray jsonArray;
String namaDosen,kodeDosen;
PublikasiAdapter publikasiAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_dosen);
SharedPreferences DataDosen = getSharedPreferences("Dosen", Context.MODE_PRIVATE);
kodeDosen = DataDosen.getString("kodeDosen","");
namaDosen = DataDosen.getString("namaDosen","");
tvWelcome = (TextView) findViewById(R.id.tvWelcome);
tvWelcome.setText("Welcome "+namaDosen+"("+kodeDosen+")");
listView = (ListView) findViewById(R.id.lstPublikasi);
lstPublikasi = new ArrayList<Publikasi>();
publikasiAdapter = new PublikasiAdapter(lstPublikasi,getApplicationContext());
listView.setAdapter(publikasiAdapter);
}
String uri = String.format(Utils.viewURL,kodeDosen);
private void showList(){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//this is where i will put the JSON Array
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
this is my model:
public class Publikasi {
public String namaJurnal,tipePublikasi,status,periode;
public Publikasi(JSONObject object) {
try{
this.namaJurnal =object.getString("namaJurnal");
this.tipePublikasi = object.getString("tipePublikasi");;
this.status = object.getString("status");;
this.periode = object.getString("periode");;
}catch (JSONException e){
e.printStackTrace();
}
public static ArrayList<Publikasi> fromJSON(JSONArray jsonObjects){
ArrayList<Publikasi> publikasi = new ArrayList<Publikasi>();
for(int i = 0;i<jsonObjects.length();i++){
try{
}catch (){
}
}
return publikasi;
}
}
}
this is my adapter:
public class PublikasiAdapter extends ArrayAdapter<Publikasi>{
private List<Publikasi> lstPublikasi;
private Context mCtx;
public PublikasiAdapter(List<Publikasi> P,Context c){
super(c, R.layout.list_publikasi,P);
this.lstPublikasi = P;
this.mCtx = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_publikasi, parent, false);
}
TextView textNama = (TextView) convertView.findViewById(R.id.textNama);
TextView textDetail = (TextView) convertView.findViewById(R.id.textDetail);
TextView textStatus = (TextView) convertView.findViewById(R.id.textStatus);
TextView textPeriode = (TextView) convertView.findViewById(R.id.textPeriode);
Publikasi publikasi = lstPublikasi.get(position);
textNama.setText(publikasi.namaJurnal);
textDetail.setText(publikasi.tipePublikasi);
textStatus.setText(publikasi.status);
textPeriode.setText(publikasi.periode);
return convertView;
}
}
this is the JSON format:
[{"idPublikasi":"62","kodeDosen":"D0001","gambar":"uploaddosen/D0001_0.50622400
1523420013.jpg","namaJurnal":"pizza","tipePublikasi":"Scopus","status":"Submit","periode":"Genap
2018"},{"idPublikasi":"64","kodeDosen":"D0001","gambar":"uploaddosen/D0001_0.94649000
1523432053.jpg","namaJurnal":"SPAS 12","tipePublikasi":"Scopus","status":"On Review","periode":"Sebelum
2015"}]
You are creating an empty list and you're giving it to the adapter. So, there is not a list to display.
listView = (ListView) findViewById(R.id.lstPublikasi);
lstPublikasi = new ArrayList<Publikasi>();
publikasiAdapter = new PublikasiAdapter(lstPublikasi,getApplicationContext());
You must fill the list when the response come successfully. After that you must give the list to the adapter's method such as "updateList();"
Here is the sample:
private void showList() {
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null, new Response.Listener < JSONArray > () {#
Override
public void onResponse(JSONArray response) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
lstPublikasi.add(new Publikasi(jsonArray.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
publikasiAdapter.updateList(lstPublikasi);
}
}, new Response.ErrorListener() {#
Override
public void onErrorResponse(VolleyError error) {}
});
}
public class PublikasiAdapter extends ArrayAdapter < Publikasi > {
private List < Publikasi > lstPublikasi;
private Context mCtx;
public PublikasiAdapter(List < Publikasi > P, Context c) {
super(c, R.layout.list_publikasi, P);
this.lstPublikasi = P;
this.mCtx = c;
}#
Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_publikasi, parent, false);
}
TextView textNama = (TextView) convertView.findViewById(R.id.textNama);
TextView textDetail = (TextView) convertView.findViewById(R.id.textDetail);
TextView textStatus = (TextView) convertView.findViewById(R.id.textStatus);
TextView textPeriode = (TextView) convertView.findViewById(R.id.textPeriode);
Publikasi publikasi = lstPublikasi.get(position);
textNama.setText(publikasi.namaJurnal);
textDetail.setText(publikasi.tipePublikasi);
textStatus.setText(publikasi.status);
textPeriode.setText(publikasi.periode);
return convertView;
}
public void updateList(List < Publikasi > mlstPublikasi) {
lstPublikasi = mlstPublikasi;
notifyDataSetChanged();
}
}
Try this code for showList()
private void showList(){
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ArrayList<Publikasi> publikasis=new ArrayList<>();
for(int i=0;i<response.length();i++){
try {
publikasis.add(new Publikasi(response.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
publikasiAdapter = new PublikasiAdapter(publikasis,getApplicationContext());
listView.setAdapter(publikasiAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonArrayRequest);
}
I have code to show listview from my server, but when I update the data from server and refresh it in my app, the listview still getting the old data, and after several minutes when I open the app again, it updated the new data that I updated before.
My Main Fragment
public class DosenFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
}
I have tried to do something with itemList.clear(); and adapter.notifyDataSetChanged(); but nothing change.
My Main Adapter
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
I'm sorry for my bad english.
Please help.
try this , add this method in your adatper
public void updateList(List<Dosen> newlist) {
items.clear();
items.addAll(newlist);
this.notifyDataSetChanged();
}
and in callVolley() method , replace this
adapter.notifyDataSetChanged();
with
adapter.updateList();
Hope this helps
Use the below Code...
/* Within the RecyclerView.Adapter class */
// Clean all elements of the recycler
public void clear() {
items.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Dosen> newlist) {
items.addAll(newlist);
notifyDataSetChanged();
}
callvolly() method inside.
adapter.clear();
adapter.addAll(item);
public void onRefresh() {
callVolley();
}
please try this code i have changed something it will work fine
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
public void setData(List<Dosen> items){
this.items = items
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
public class DosenFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout)
v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
//itemList.clear();
//adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
itemList .clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj =
response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.setData(itemList );
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
I have a fragment for a tab which displays JSON parsed results in GridView. The results are not displayed when scrolled to that tab for first time. But after switching tabs, results are displayed in second visit.
public class StoresFragment extends Fragment {
private ProgressBar loading;
private ArrayList<String> storenamefinal = new ArrayList<String>();
private ArrayList<Integer> imagelinksfinal = new ArrayList<Integer>();
private GridView gridview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.stores_layout,null);
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridview = (GridView) getActivity().findViewById(R.id.grid_stores);
loading = (ProgressBar) getActivity().findViewById(R.id.proStores);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
new getData(getActivity()).execute();
}
}
private class getData extends AsyncTask<Void, Void, Void> {
private Context context;
public getData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
String url = Config1.DATA_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return null;
}
private void showJSON(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
int i = result.length();
Log.i("Result", result.toString());
for (int j = 0; j < i; j++) {
storenamefinal.add(null);
imagelinksfinal.add(null);
}
String temp;
for (int j = 0; j < i; j++) {
JSONObject Data = result.getJSONObject(j);
Log.i("Data", Data.toString());
temp = (Data.getString("mainpriority"));
Log.i("temp", temp.toString());
storenamefinal.set(Integer.parseInt(temp) - 1, Data.getString("storename"));
Log.i("Result Length", storenamefinal.toString());
imagelinksfinal.add(R.drawable.sg1);
}
Log.i("Result Length", storenamefinal.toString());
Toast.makeText(getActivity(), storenamefinal.get(0), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result)
{
loading.setVisibility(View.GONE);
gridview.setVisibility(View.VISIBLE);
if (storenamefinal != null) {
final GridAdapterStores gridadapter = new GridAdapterStores(getActivity(), storenamefinal, imagelinksfinal);
gridview.setAdapter(gridadapter);
}
}
}
}
Adapter.
public class GridAdapterStores extends BaseAdapter {
private Context context;
private ArrayList<String> storename = new ArrayList<String>();
private ArrayList<Integer> imagelinks = new ArrayList<Integer>();
public GridAdapterStores(Context c, ArrayList<String> storename, ArrayList<Integer> imagelinks) {
context = c;
this.imagelinks = imagelinks;
this.storename = storename;
}
#Override
public int getCount() {
return storename.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
if (convertView == null) {
grid = new View(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.grid_stores, parent, false);
} else {
grid = (View) convertView;
}
TextView textViewStoreName = (TextView) grid.findViewById(R.id.store_name);
// ImageView imageViewStoreImage = (ImageView) grid.findViewById(R.id.store_image);
textViewStoreName.setText(storename.get(position));
// Integer x=imagelinks.get(position);
// imageViewStoreImage.setImageResource(x);
return grid;
}
}
And also, everytime tab is switched, gridview gets added, but data is displayed in only one gridview.
I am using listview to populate data coming from the server. This listview will show that data in a fragmentTab. Now the data is parsing fine and logcat is also showing the data. But the data is not being populated by listview. I tried to see the error through debugging but there is no problem. Even the Holder in adapter catches the data but it's not displayed. I don't know what the problem is. I tried the following questions but didn't got the answer.
Android - ListView in Fragment does not showing up
Android - ListView in Fragment does not show
ListView in Fragment Not Displayed
Below is my fragment and the adapter.
Tastemaker Fragment:
public class TasteMakersFragment extends Fragment
{
CommonClass commonTasteMakers;
String tasteMaker_url = CommonClass.url+ URLConstants.Host.URL_ALL_SUGGESTED_TASTEMAKERS;
String user_token = "8aa0dcd5aaf54c8a5aaef1aa242f342f";
ListView suggested_list;
List<SuggestedUserModel> suggestedUsers_list = new ArrayList<>();
SuggestedUsersAdapter mAdapter;
int selectedPosition = 0;
public TasteMakersFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.from(getActivity()).inflate(R.layout.suggested_users_tastemakers, null);
commonTasteMakers = new CommonClass(getActivity().getApplicationContext());
suggested_list = (ListView)v.findViewById(R.id.lst_suggestedUsers);
new GetSuggestedUsers().execute(tasteMaker_url);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
private class GetSuggestedUsers extends AsyncTask< String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
if (suggestedUsers_list.isEmpty())
{
Dialog = ProgressDialog.show(getActivity(),"Please be patient!","Fetching for first time...");
}
}
#Override
protected Void doInBackground(String... params)
{
if (suggestedUsers_list.isEmpty())
{
getSuggestedUsers();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
else{
Log.d("---- Already Fetched --", "---- Already Fetched ----");
return null;
}
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
mAdapter = new SuggestedUsersAdapter(getActivity(), suggestedUsers_list);
suggested_list.setAdapter(mAdapter);
suggested_list.setSelection(selectedPosition);
mAdapter.notifyDataSetChanged();
//startMainActivity();
}
}
private List<SuggestedUserModel> getSuggestedUsers()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, tasteMaker_url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try {
//JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
JSONObject jsonResponse = new JSONObject(response);
if (jsonResponse.has("data"))
{
JSONObject data = jsonResponse.getJSONObject("data");
String code = jsonResponse.getString("code");
if(code.equals("200"))
{
if(data.has("tasteMakers"))
{
JSONArray tastemakers = data.getJSONArray("tasteMakers");
for (int i =0; i<tastemakers.length(); i++)
{
JSONObject jsnObj = tastemakers.getJSONObject(i);
String id = jsnObj.getString("userId");
String name = jsnObj.getString("name");
String profilePic = jsnObj.getString("imgUrl");
Boolean isFollowed = jsnObj.getBoolean("isFollowed");
suggestedUsers_list.add(new SuggestedUserModel(id,
name,
profilePic,
isFollowed));
Log.d("Names are ----", "size is=" + name +" and their id are: "+id);
}
// Log.d("Adapter list ----", "size is=" + suggestedUsers_list.size());
}
}
else {
Log.d("Error0 Error Error", "response------:" + jsonResponse);
}
}
// Log.d("response222---------","response22222------:"+jsonResponse);
} catch (JSONException e) {
Log.d("-----Stop------", "!!!");
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("sessionToken", user_token);
return params;
} };
postRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getActivity().getApplicationContext()).add(postRequest);
return suggestedUsers_list;
}
}
Adapter Class:
public class SuggestedUsersAdapter extends BaseAdapter {
Context context;
int count = 1;
private List<SuggestedUserModel> allUsers;
public SuggestedUsersAdapter(FragmentActivity activity, List<SuggestedUserModel> suggestUserModel)
{
Log.d("Custom Adapter called", "" + suggestUserModel.size());
context = activity;
allUsers = suggestUserModel;
//FragmentActivity mActivity = activity;
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return allUsers.size();
// return imageId.length;
}
#Override
public Object getItem(int position) {
return allUsers.get(position);
// return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint({"ViewHolder", "InflateParams", "CutPasteId"})
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final mHolder holder;
// int type = getItemViewType(position);
LayoutInflater layoutInflater;
getItemViewType(position);
if (convertView == null)
{
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.suggested_users_tastemaker_cell, null);
holder = new mHolder();
// convertView.setTag(mFeedsListItemViewHolder);
holder.txt_suggestUserName = (TextView) convertView.findViewById(R.id.tv_tasteMakerName);
holder.imgV_userProfile = (ImageView) convertView.findViewById(R.id.imgBtn_tasteMaker_pic);
holder.btnFollow = (Button) convertView.findViewById(R.id.btnFollow_tasteMaker);
holder.btnFollowing = (Button) convertView.findViewById(R.id.btnFollowing);
convertView.setTag(holder);
} else {
holder = (mHolder) convertView.getTag();
}
final SuggestedUserModel suggestUser = allUsers.get(position);
holder.txt_suggestUserName.setText(allUsers.get(position).getSuggested_UserName());
/*if(suggestUser.getSuggested_UserImage().equals(""))
{
Picasso
.with(context)
.load(R.mipmap.ic_launcher)
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}
else {
Picasso
.with(context)
.load(suggestUser.getSuggested_UserImage())
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}*/
holder.pos = position;
//mFeedsListItemViewHolder.setData(allPersons.get(position));
return convertView;
}
private class mHolder {
TextView txt_suggestUserName;
ImageView imgV_userProfile;
Button btnFollow;
Button btnFollowing;
int pos;
}
}
Note: I already tried declaring listview and assigning adapter in onActivityCreated() method of fragment but no effect.
Any Help will be appreciated.