I am having ListView and there is a Like button at the bottom of every List item. I am not able to save the state of the button while Scrolling. The state of the button gets reset while i scroll up or down. I think i need to add a pojo class to get and set the state of button But i have no idea how to do it So can anyone help me with the code?
My Adapter class:
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private int lastPosition = -1;
private DatabaseHandler db;
int id = 0;
String email;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
final FeedItem item = feedItems.get(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, parent,false);
holder = new ViewHolder();
//Getting Views from Layout
holder.likebutton =
(LikeButton) convertView.findViewById(R.id.star_button);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
holder.statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
holder.url = (TextView) convertView.findViewById(R.id.txtUrl);
holder.like = (TextView) convertView.findViewById(R.id.like_box_no);
holder.share = (TextView) convertView.findViewById(R.id.share_no);
holder.comment = (TextView) convertView.findViewById(R.id.comment_no);
holder.profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
holder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
//End Getting Views from Layout
convertView.setTag(holder);
}
else{
holder = (ViewHolder)convertView.getTag();
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
//get User Email
db = new DatabaseHandler(activity.getApplication());
HashMap<String, String> user = db.getUserDetails();
email = user.get("email").toString();
// End get User Email ID for sending it to db
holder.name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.timestamp.setText(timeAgo);
if (item.getFav().equals("1")) {
holder.likebutton.setLiked(true);
} else {
// status is empty, remove from view
holder.likebutton.setLiked(false);
}
// Check for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Chcek for empty Like
if (!TextUtils.isEmpty(item.getLike())) {
holder.like.setText(item.getLike());
holder.like.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.like.setText("0");
}
// Chcek for empty Comment
if (!TextUtils.isEmpty(item.getComment())) {
holder.comment.setText(item.getComment());
holder.comment.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.comment.setText("0");
}
// Check for empty Share
if (!TextUtils.isEmpty(item.getShare())) {
holder.share.setText(item.getShare());
holder.share.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.share.setText("0");
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
//Setting preloading Image to profile pic
imageLoader.get(item.getProfilePic(), ImageLoader.getImageListener(holder.profilePic, R.drawable._businessman, R.drawable._businessman));
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
//Animating the List View
Animation animation = AnimationUtils.loadAnimation(activity.getApplication(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
convertView.startAnimation(animation);
lastPosition = position;
//End Animating the List View
//onClick Like Button
//Toast.makeText(activity.getApplication(), "Fav Changed : " + item.getId(), Toast.LENGTH_SHORT).show();
//if Favourite Clicked Do this
holder.likebutton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
id = item.getId();
Log.d("inFavChngeListner", "Clickd" + item.getId());
new send_json().execute();
likeButton.setLiked(true);
}
#Override
public void unLiked(LikeButton likeButton) {
new send_json_unlike().execute();
likeButton.setLiked(false);
}
});
return convertView;
}
public static class ViewHolder {
public LikeButton likebutton;
public TextView name;
public TextView timestamp;
public TextView statusMsg;
public TextView like;
public TextView share;
public TextView comment;
public TextView url;
public NetworkImageView profilePic;
public FeedImageView feedImageView;
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.like_func(email, String.valueOf(id));
Log.d("BG Like, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
}
}
//Sending UnLike Request with email id and feed id to Remote Mysql Db
public class send_json_unlike extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.unlike_func(email, String.valueOf(id));
Log.d("BG UnLike, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
}
}
My Fragment:
public class MainFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private static final String TAG = MainFragment.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
View view;
private CircleRefreshLayout mRefreshLayout;
private boolean count=false;
JSONObject feedObj;
FeedItem item;
public MainFragment() {
}
public static MainFragment newInstance(String text) {
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
fragment.setArguments(bundle);
return fragment;
}
#Override
public void registerForContextMenu(View view) {
super.registerForContextMenu(view);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_main, container, false);
mRefreshLayout = (CircleRefreshLayout) view.findViewById(R.id.refresh_layout);
listView = (ListView) view.findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
view.setFocusableInTouchMode(true);
view.requestFocus();
//Listeneing to Back Button
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().finish();
Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
//Starting start Loader Animation Thread and fetching the feed
mRefreshLayout.post(new Runnable() {
#Override
public void run() {
startAnim();
count=true;
fetch();
}
});
mRefreshLayout.setOnRefreshListener(
new CircleRefreshLayout.OnCircleRefreshListener() {
#Override
public void refreshing() {
// do something when refresh starts
count = true;
fetch();
}
#Override
public void completeRefresh() {
// do something when refresh complete
}
});
listView.setAdapter(listAdapter);
return view;
}
private void fetch()
{
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
feedItems.clear();
parseJsonFeed(response);
}
if (count){
stopAnim();
mRefreshLayout.finishRefreshing();
count=false;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
feedObj = (JSONObject) feedArray.get(i);
item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
item.setLike(feedObj.getString("like"));
item.setComment(feedObj.getString("comment"));
item.setShare(feedObj.getString("share"));
item.setFav(feedObj.getString("fav"));
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onRefresh() {
}
//start Animation on Start
void startAnim(){
view.findViewById(R.id.avloadingIndicatorView).setVisibility(View.VISIBLE);
}
//stop Animation on start
void stopAnim(){
view.findViewById(R.id.avloadingIndicatorView).setVisibility(View.GONE);
}
}
well you fetch your data once only and add the items in 'feedItems'. then on 'userFunction.like_func' you like or dislike using the 'userFunction.unlike_func' which we do not know what they do but probably they do not update 'feedItems' collection and precisely do not call 'setFav' on the clicked item. This is why the likes are not updated. You can:
1) update(call setFav) required fields in the async tasks or even better create volley request for those.
2) in 'holder.likebutton.setOnLikeListener(new OnLikeListener() {'
add:
item.setFav("1") or item.setFav("0")
holder.likebutton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
id = item.getId();
Log.d("inFavChngeListner", "Clickd" + item.getId());
new send_json().execute();
likeButton.setLiked(true);
item.setFav("1")
}
#Override
public void unLiked(LikeButton likeButton) {
new send_json_unlike().execute();
likeButton.setLiked(false);
item.setFav("0")
}
});
this however does not guarantee synchronization with remote data as the request may fail and this is why 1) should be done also
Related
Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});
I am getting id from previous activity,if id is null then i parse data and store it in arraylist,but if it is not null then i dont parse data and trying to set arraylist in listview,but it shows arraylist null
mRecyclerView = (ListView) findViewById(R.id.filter_orderlist);
makeJsonArrayRequestCountry();
}
private void makeJsonArrayRequestCountry() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( filter_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
filterList =new ArrayList<FilterModelClass>();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
String heder=obj.getString("filterName");
System.out.println("Hader"+heder);
JSONArray details=obj.getJSONArray("getParam");
for(int j=0;j<details.length();j++)
{
JSONObject det=details.getJSONObject(j);
FilterModelClass movie = new FilterModelClass();
movie.setFilter_Name(det.getString("paramName"));
String cityid=movie.setFilter_ID(det.getString("paramId"));
filterList.add(movie);
}
mAdapter = new MyCustomBaseAdapter(FilterListActivity.this,filterList);
mRecyclerView.setAdapter(mAdapter);
btnSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = "";
List<FilterModelClass> stList = ((MyCustomBaseAdapter) mAdapter)
.getStudentist();
for (int i = 0; i < stList.size(); i++) {
FilterModelClass singleStudent = stList.get(i);
if (singleStudent.isselected() == true) {
data = data+singleStudent.getFilter_ID().toString()+",";
}
}
Intent intent=new Intent();
intent.putExtra("filterid",data);
setResult(RESULT_OK, intent);
FilterListActivity.this.finish();
Toast.makeText(FilterListActivity.this,
"Selected Students:" + data, Toast.LENGTH_LONG)
.show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
}
}
public class MyCustomBaseAdapter extends BaseAdapter {
private List<FilterModelClass> searchArrayList;
ViewHolder holder;
private LayoutInflater mInflater;
SharedPreferences.Editor editor;
Context context;
public MyCustomBaseAdapter(Context mainActivity, List<FilterModelClass> results) {
context = mainActivity;
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
SharedPreferences sharedPrefs = context.getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.sorting_items, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.tvName);
holder.cB = (CheckBox)convertView.findViewById(R.id.chkSelected);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
editor = sharedPrefs.edit();
holder.txtName.setText(searchArrayList.get(position).getFilter_Name());
holder.cB.setChecked(sharedPrefs.getBoolean("CheckValue" + position, false));
holder.cB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean("CheckValue" + position, isChecked);
editor.commit();
}});
return convertView;
}
class ViewHolder {
TextView txtName;
CheckBox cB;
}
public List<FilterModelClass> getStudentist() {
return searchArrayList;
}
}
}
You have not set a LayoutManager to your RecyclerView:
use this to set LayoutManager to your RecyclerView:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
in oncreate
The problem is this part
if(filtrid!=null)
{
System.out.println("datacat null"+filterList);
mAdapter = new CardViewDataAdapter(filterList);
mRecyclerView.setAdapter(mAdapter);
}
You read the filtrid but you don't initialize your filterList in this case.
EDIT:
Retrieving the filtridfrom the intent extras is not the same as populating the filterList. You could probably pass the filterList as JSON-String in the same way, you passed the filtrid. Then parse the JSON-String as you did already in makeJsonArrayRequestCountry(). A better way would be, to store the list persistent (SharedPreferences, SQL, ...), or don't store it at all. Just load the list from the server, whenever you start that activity.
I am having a problem in my listview. Actually I have implemented Facebook Like Feed from Facebook Like Custom Feed
which is fetching data from MySQL database. At bottom of every list item I am having a Like Button from this library Material Favourite Button. My Problem is that when i click like on 1st List item, The 5th list item gets automatically liked and if i click on 2nd List item 4th list item gets liked and so on. I tried everything i could do but nothing resolved this problem. I tried to add view holder also to my list adapter class as suggested in various answered questions here but it didn't resolve my issue. Kindly Help! Below is my adapter class:
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private int lastPosition = -1;
private DatabaseHandler db;
ViewHolder holder;
int id = 0;
String email;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, parent,false);
holder = new ViewHolder();
holder.materialFavoriteButtonNice =
(MaterialFavoriteButton) convertView.findViewById(R.id.like_anim);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
//get User Email
db = new DatabaseHandler(activity.getApplication());
db = new DatabaseHandler(activity.getApplication());
HashMap<String, String> user = db.getUserDetails();
email = user.get("email").toString();
// End get User Email ID for sending it to db
//Getting Views from Layout
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
final TextView like = (TextView) convertView.findViewById(R.id.like_box_no);
TextView share = (TextView) convertView.findViewById(R.id.share_no);
TextView comment = (TextView) convertView.findViewById(R.id.comment_no);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
//End Getting Views from Layout
final FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Check for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Chcek for empty Like
if (!TextUtils.isEmpty(item.getLike())) {
like.setText(item.getLike());
like.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
like.setText("0");
}
// Chcek for empty Comment
if (!TextUtils.isEmpty(item.getComment())) {
comment.setText(item.getComment());
comment.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
comment.setText("0");
}
// Chcek for empty Share
if (!TextUtils.isEmpty(item.getShare())) {
share.setText(item.getShare());
share.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
share.setText("0");
}
if (item.getFav().equals("1")) {
holder.materialFavoriteButtonNice.setFavorite(true, false);
holder.materialFavoriteButtonNice.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.materialFavoriteButtonNice.setFavorite(false, false);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
imageLoader.get(item.getProfilePic(), ImageLoader.getImageListener(profilePic, R.drawable._businessman, R.drawable._businessman));
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
//Animating the List View
Animation animation = AnimationUtils.loadAnimation(activity.getApplication(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
convertView.startAnimation(animation);
lastPosition = position;
//End Animating the List View
//onClick Like
holder.materialFavoriteButtonNice.setOnFavoriteChangeListener(new MaterialFavoriteButton.OnFavoriteChangeListener() {
#Override
public void onFavoriteChanged(MaterialFavoriteButton buttonView, boolean favorite) {
id = item.getId();
Log.d("inFavChngeListner", "Clickd" + item.getId());
Toast.makeText(activity.getApplication(), "Fav Changed : " + item.getId(), Toast.LENGTH_SHORT).show();
if (favorite) {
new send_json().execute();
} else {
holder.materialFavoriteButtonNice.setFavorite(false, true);
new send_json_unlike().execute();
}
}
});
return convertView;
}
static class ViewHolder {
MaterialFavoriteButton materialFavoriteButtonNice;
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(true, true);
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.like_func(email, String.valueOf(id));
Log.d("BG Like, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(true, true);
}
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json_unlike extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(false, true);
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.unlike_func(email, String.valueOf(id));
Log.d("BG UnLike, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(false, true);
}
}
}
Dont use ViewHolder instance global . Make it inside function scope . And try to change the logic . Only update the model inside the array and just call notifyDataSetChanged() method. I think it will solve your issue.
Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}
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.