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.
Related
I have a fragment with a listView.
The view is populated from a remote received JSON array as follows:
private void callVolley(){
SharedPreferences prefs3 =
getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
final String id_materia= "42";
final String num_examen= "787878";
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando temas de la materia seleccionada...");
showDialog();
JsonArrayRequest jArr = new JsonArrayRequest(url+"?id="+id_materia, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// list.invalidateViews();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
Then I add programmatically a checkbox to each list item.
This is the adapter:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
At start I need all checkboxes to be checked.
Then the user can check/uncheck the desired items.
On the fragment there is a button that reads all items checkbox states.
What should I implement to put all items in status checked so that on button clicked all items are recognized as checked?
This is a screenshot at start with all items unchecked:
EDIT
Code for the button onClickListener in the fragment:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkbox = "";
checkbox_id = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
checkbox_id += hold.getId()+",";
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
String preguntas = checkbox_id;
mPref = getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPref.edit();
editor.putString("preguntas_numero_string",preguntas);
editor.putString("preguntas_string",dipilih);
Log.d("seleccion","seleccion preguntas "+preguntas);
Log.d("seleccion","seleccion dipilih "+dipilih);
editor.apply();
} else {
dipilih = "No has seleccionado ningĂșn tema.";
}
formSubmit(dipilih);
}
});
Do the following changes:
When you are adding Data to the list of Data.
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
item.setCheckbox(true)
itemList.add(item);
This will initially make the checkbox checked.
Edit:
Update your xml layout. in your CheckBox put this attribute.
android:clickable="false"
Update your list setOnItemClickListener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setCheckBox(position);
}
});
Try replacing with the below code
viewHolder.checkBox.setChecked(true);
instead of
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
Use this. It should work. -
Initially this -
viewHolder.checkBox.setChecked(true);
Then
viewHolder.checkBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton
buttonView,boolean isChecked) {
if(isChecked){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
}
}
);
I am following a tutorial about multiple choice listview in android.
When executing the app, the listview shows some items, not all of them. After clicking on the listview, it shows all items.
I want to know where is the reason of that issue.
This is the code for MainActivity class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
ListView list;
TextView txt_menu;
String dipilih;
private static final String TAG = MainActivity.class.getSimpleName();
Adapter adapter;
ProgressDialog pDialog;
List<Data> itemList = new ArrayList<Data>();
// Sesuaikan dengan IP Address PC/LAptop atau ip emulator bawaan android 10.0.2.2
private static String url = "https://.../test/menu.php";
public static final String TAG_NAMA = "nama";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
list = (ListView) findViewById(R.id.list_menu);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
callVolley();
adapter = new Adapter(this, (ArrayList<Data>) itemList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);
txt_menu.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void callVolley(){
itemList.clear();
// menapilkan dialog loading
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
showDialog();
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NAMA));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And this is the Adapter class:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
viewHolder.menu.setText(items.getMenu());
}
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
If you need other code parts to detect the problem, please let me know.
EDIT
First launch
After clicking on the listview
The problem is this bit of your code in your adapter's getView() callback:
if(view == null) {
...
}else {
...
viewHolder.menu.setText(items.getMenu());
}
What's happening here is that you're only caling setText() when the item view is recycled by the ListView. The reason everything shows up after you click a checkbox is that the ListView rebinds everything when you call notifyDataSetChanged().
You should call this method outside of the if/else statement so that it is executed every time.
if(view == null) {
...
}else {
...
}
viewHolder.menu.setText(items.getMenu());
I think the issue you are having is coming from the getView() method in your Adapter class.
Since you are using a ViewHolder to recycle objects you are first checking if the exist first before creating them if(view == null). But, you are only creating them and not assigning the TextView objects a String value. You only do that once the object has already been created. So, when you click on an item, you are calling notifyDataSetChanged causing the list to be updated. Then the values are set in the `TextView.
So try this instead: put the line viewHolder.menu.setText(items.getMenu()); outside the conditional statement:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
try this once
adapter = new Adapter(this, (ArrayList) itemList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
list.setAdapter(adapter);
}
set adapter at the end
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
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.
Hi i'm trying to implement search function on my listview. I download data from server in json and after populate my listview. When i try to search something the listview becomes empty and i can not find anything . i have followed this tutorial http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/ Someone can help me Thanks?
ListaGestisciBigliettiActivity.java
private List<ListBiglietti> listBiglietti;
private CustomListAdapterBiglietti customListAdapterBiglietti;
ProgressDialog progressDialog;
private String idQr;
EditText editSearch;
private ListView listViewBiglietti;
private SharedPreferences sharedPreferences;
private String eliminaBiglietto = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the layout for this fragment
setContentView(R.layout.fragment_list_gestisci_biglietti);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setTitle("Gestisci Biglietti");
// setHasOptionsMenu(true);
listBiglietti = new ArrayList<ListBiglietti>();
listViewBiglietti = (ListView) findViewById(R.id.list_biglietti);
customListAdapterBiglietti = new CustomListAdapterBiglietti(this, listBiglietti);
listViewBiglietti.setAdapter(customListAdapterBiglietti);
editSearch = (EditText) findViewById(R.id.search);
editSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = editSearch.getText().toString().toLowerCase(Locale.getDefault());
customListAdapterBiglietti.filter(text);
}
});
//registro il context menu alla lista
// registerForContextMenu(listViewBiglietti);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http").authority(constant.URLPartyCode).appendPath("app_dev.php").appendPath("app").appendPath("lista-biglietti-evento").appendPath(constant.EventoId);
String ListaBigliettiUrl = builder.build().toString();
Log.d("urleventi", ListaBigliettiUrl.toString());
StringRequest stringRequest = new StringRequest(Request.Method.GET, ListaBigliettiUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.d("urlLista", response);
try {
//MANCA CONTROLLO SE NON CI SONO EVENTI
JSONObject objectResponse = new JSONObject(response);
JSONArray jsonArray = objectResponse.getJSONArray("response");
if (jsonArray == null) {
Log.d("JsosVuoto", "jsonVuoto");
} else {
fillList(jsonArray, listBiglietti);
customListAdapterBiglietti.notifyDataSetChanged();
Log.d("jsonArray", jsonArray.toString());
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(stringRequest);
/* JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ListaPrUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = response.getJSONObject(0);
Log.d("error", "lista");
if (jsonObject.optString("msg").matches("ko")) {
customListAdapterBiglietti = null;
listViewBiglietti = (ListView) view.findViewById(R.id.list_biglietti);
listViewBiglietti.setVisibility(View.INVISIBLE);
} else {
fillList(response, listBiglietti);
customListAdapterBiglietti.notifyDataSetChanged();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
listViewBiglietti.setVisibility(View.INVISIBLE);
Toast.makeText(getActivity(), "Controlla la connessione ", Toast.LENGTH_SHORT).show();
Log.d("errore", "error");
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);*/
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setMessage("Caricamento...");
progressDialog.show();
if (customListAdapterBiglietti == null) {
} else {
// Set OnItemClickListener so we can be notified on item clicks
listViewBiglietti.setOnItemClickListener(this);
}
// Inflate the layout for this fragment
}
this is my custom adapter
public class CustomListAdapterBiglietti extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<ListBiglietti> listBiglietti;
private ArrayList<ListBiglietti> arraylist;
public CustomListAdapterBiglietti(Activity activity, List<ListBiglietti> listBiglietti) {
this.activity = activity;
this.listBiglietti = listBiglietti;
this.arraylist = new ArrayList<ListBiglietti>();
this.arraylist.addAll(listBiglietti);
}
#Override
public int getCount() {
return listBiglietti.size();
}
#Override
public Object getItem(int position) {
return listBiglietti.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
holder = new ViewHolder();
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_biglietti_item, null);
holder.nome = (TextView) convertView.findViewById(R.id.nome_biglietto_cliente);
holder.biglietti = (TextView) convertView.findViewById(R.id.codice_qrcode_cliente);
holder.data = (TextView) convertView.findViewById(R.id.data_biglietto_cliente);
holder.nomePr = (TextView) convertView.findViewById(R.id.nome_pr_biglietto);
}
holder.nome = (TextView) convertView.findViewById(R.id.nome_biglietto_cliente);
holder.biglietti = (TextView) convertView.findViewById(R.id.codice_qrcode_cliente);
holder.data = (TextView) convertView.findViewById(R.id.data_biglietto_cliente);
holder.nomePr = (TextView) convertView.findViewById(R.id.nome_pr_biglietto);
ListBiglietti b = listBiglietti.get(position);
holder.nome.setText(b.getNome());
holder.biglietti.setText(b.getCode());
holder.data.setText(b.getData());
holder.nomePr.setText(b.getNomePr());
return convertView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
listBiglietti.clear();
if (charText.length() == 0) {
listBiglietti.addAll(arraylist);
} else {
for (ListBiglietti wp : arraylist) {
if (wp.getNomePr().toLowerCase(Locale.getDefault())
.contains(charText)) {
listBiglietti.add(wp);
}
}
}
notifyDataSetChanged();
}
public class ViewHolder {
TextView nome;
TextView biglietti;
TextView data;
TextView nomePr;
}
}
This is my fillList function
public void fillList(JSONArray response, List items) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
//creo un oggetto jsonitem e lo metto nella lista
ListBiglietti listBiglietti = new ListBiglietti();
//creo un oggetto nascosti e lo aggiungo al mio array
listBiglietti.setNome(jsonObject.optString("nome"));
listBiglietti.setCode(jsonObject.optString("qr"));
listBiglietti.setId(jsonObject.optString("id"));
listBiglietti.setNomePr(jsonObject.optString("pr"));
listBiglietti.setData(jsonObject.optString("data_creazione"));
Log.d("dato", jsonObject.optString("nome"));
//aggiungo al mio array per array adapter
items.add(listBiglietti);
}
} catch (Exception e) {
Log.d("jsonerror", "errore");
}
}