Android search function in listview from json - android

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");
}
}

Related

ListView JSON Array doesn't work

The array "ary" receives the data from the server and the Adapter, but doesn't show the data in the ListView. Is there a problem with receiving the data after the onCreate() method?
Does anyone have an idea/solution?
public class ScheduleActivity extends AppCompatActivity {
public ListView list;
public ScheduleViewAdapter mSVAdapter;
public JSONArray ary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
buildList();
}
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter.notifyDataSetChanged();
}
private void buildList() {
final RequestQueue requestQueue = Volley.newRequestQueue(this);
// String URL1 = "http://10.0.2.2:3000/users/:userId/offers/";
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// vorläufiger hardcode
String userID = "5b2f9f3cd56ff67974d2f58e";
/* userID = settings.getString("userID", "");*/
String URL1 = "http://10.0.2.2:3000/orders/?buyerID=".concat(userID).concat("/userorder");
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("ConsoleText", response);
try {
JSONArray ary2 = new JSONArray(response);
setListView(ary2);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ConsoleText", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
requestQueue.add(stringRequest);
}
}
Okay, so this is an edit.
That's the adapter. maybe you can find the error here. Thanks:
public class ScheduleViewAdapter extends BaseAdapter{
private Context mContext;
private JSONArray orders;
public ScheduleViewAdapter() {
}
public ScheduleViewAdapter(Context mContext, JSONArray orders) {
this.mContext = mContext;
this.orders = orders;
}
#Override
public int getCount() {
if(orders == null){
return 0;
}else{
return orders.length();
}
}
#Override
public JSONObject getItem(int position) {
if(orders == null){
return null;
}else{
return orders.optJSONObject(position);
}
}
#Override
public long getItemId(int position) {
JSONObject object = getItem(position);
return object.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
//Only creates new view when recycling isn't possible
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_schedule, parent, false);
}
TextView tvItem =(TextView)convertView.findViewById(R.id.tvItem);
// TextView tvUserName =(TextView)convertView.findViewById(R.id.tvUserName);
// TextView tvAddress =(TextView)convertView.findViewById(R.id.tvAddress);
JSONObject json_data = getItem(position);
if(json_data != null){
try {
String type = json_data.getString("title");
// tvItem.append("" + json_data.getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
return convertView;
}
}
Change your method to this,
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
}
and onCreate to this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
buildList();
}

Fragment listview last value is not disappear

I have listview All the values are delete and update properly but only the last value is not delete in the listview.
Added a full fragment code. Take a look
For example
If I have three values in the listview If I delete 1 and 2 its removing and listview refresh properly but the last one is not refreshed in the listview
private SwipeMenuListView mylistview;
String userid;
private EditText txtsearch;
private ArrayList<JobItem> jobitems;
private JobListAdapter adapter;
SwipeMenuCreator creator;
ImageLoader imageLoader;
DisplayImageOptions options;
public Fragment_Employer_MyJobList() {
}
public static float dp2px(Context context, int dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layoutjoblist, container, false);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(1000))
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.img_app_icon)
.showImageOnFail(R.drawable.img_app_icon)
.showImageOnLoading(R.drawable.img_app_icon).build();
mylistview = (SwipeMenuListView) rootView.findViewById(R.id.mylistview);
creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
openItem.setWidth((int) dp2px(getActivity(), 90));
// set item title
openItem.setTitle("DELETE");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
}
};
txtsearch = (EditText) rootView.findViewById(R.id.txtsearch);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
String text = txtsearch.getText().toString().toLowerCase(Locale.getDefault());
if (adapter != null)
adapter.filter(text);
}
});
return rootView;
}
SharedPreferences settings;
#Override
public void onResume() {
super.onResume();
jobitems = new ArrayList<JobItem>();
jobitems.clear();
adapter.notifyDataSetChanged();
settings = getActivity().getSharedPreferences(AppUtils.PREFS_NAME, Context.MODE_PRIVATE);
userid = settings.getString("userid", "");
AuthController.getStaticInstance().
employer_joblist(getActivity(), userid, APIConstants
.POST, new AuthControllerInterface.AuthControllerCallBack()
{
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONArray mainarray = new JSONArray(message);
for (int i = 0; i < mainarray.length(); i++) {
JSONObject json_job = mainarray.getJSONObject(i);
JobItem item = new JobItem();
item.Id = json_job.getString("ID");
item.EMPID = json_job.getString("EMPID");
item.TITLE = json_job.getString("TITLE");
item.DESC = json_job.getString("DESC");
item.CID = json_job.getString("CID");
item.PRICE = json_job.getString("PRICE");
item.LOCAT = json_job.getString("LOCAT");
item.ADATE = json_job.getString("ADATE");
item.FOLLOW = json_job.getString("FOLLOW");
JSONArray array = json_job.getJSONArray("IMAGES");
if (array.length() > 0) {
if (!array.isNull(0))
item.IMG1 = array.getString(0);
if (!array.isNull(1))
item.IMG2 = array.getString(1);
if (!array.isNull(2))
item.IMG3 = array.getString(2);
if (!array.isNull(3))
item.IMG4 = array.getString(3);
if (!array.isNull(4))
item.IMG5 = array.getString(4);
}
jobitems.add(item);
}
adapter = new JobListAdapter(getActivity(), jobitems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobItem item = jobitems.get(position);
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
mylistview.setMenuCreator(creator);
mylistview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
// unfollow
userid = settings.getString("userid", "");
AuthController.getStaticInstance().employer_delete_job(getActivity(), userid, jobitems.get(position).Id, APIConstants.POST, new AuthControllerInterface.AuthControllerCallBack() {
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
// onResume();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
// onResume();
}
//setup
onResume();
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
}
#Override
public void showLoading() {
AppUtils.showProgress(getActivity(), "Please wait...");
// onResume();
}
#Override
public void stopLoading() {
AppUtils.dismissProgress();
// onResume();
}
public class OnItemClickListner implements View.OnClickListener {
int mposition;
JobItem item;
public OnItemClickListner(int position, JobItem item) {
this.mposition = position;
this.item = item;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class JobListAdapter extends BaseAdapter {
LayoutInflater _inflater;
private List<JobItem> worldpopulationlist = null;
private ArrayList<JobItem> arraylist;
public JobListAdapter(Context context, List<JobItem> worldpopulationlist) {
_inflater = LayoutInflater.from(context);
this.worldpopulationlist = worldpopulationlist;
this.arraylist = new ArrayList<JobItem>();
this.arraylist.addAll(worldpopulationlist);
}
public int getCount() {
// TODO Auto-generated method stub
return worldpopulationlist.size();
}
public JobItem getItem(int position) {
// TODO Auto-generated method stub
return worldpopulationlist.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder _holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_job_row, null);
_holder = new ViewHolder();
_holder.txtjobtitle = (TextView) convertView
.findViewById(R.id.txtjobtitle);
_holder.txtjobbudget = (TextView) convertView
.findViewById(R.id.txtjobbudget);
_holder.txtjobdesc = (TextView) convertView
.findViewById(R.id.txtjobdesc);
_holder.imageviewjob = (ImageView) convertView
.findViewById(R.id.imageviewjob);
_holder.txtlocation = (TextView) convertView
.findViewById(R.id.txtlocation);
convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}
_holder.txtjobtitle.setText(worldpopulationlist.get(position).TITLE.trim());
_holder.txtjobbudget.setText(worldpopulationlist.get(position).PRICE.trim());
_holder.txtjobdesc.setVisibility(View.VISIBLE);
_holder.txtjobbudget.setVisibility(View.GONE);
_holder.txtjobdesc.setText(worldpopulationlist.get(position).DESC);
imageLoader.displayImage(worldpopulationlist.get(position).IMG1, _holder.imageviewjob, options);
_holder.txtlocation.setText(worldpopulationlist.get(position).LOCAT.trim());
//convertView.setOnClickListener(new OnItemClickListner(position, worldpopulationlist.get(position)));
return convertView;
}
private class ViewHolder {
ImageView imageviewjob;
TextView txtjobtitle, txtjobdesc;
TextView txtlocation, txtjobbudget;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (JobItem wp : arraylist) {
if (wp.TITLE.toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
you have to tell your ListView that something changed in it's former List by calling notifyDataSetChanged() method of your adapter
Also you should not create a new instance of ArrayList, but only clear the old instance. Don't forget to check for null before clearing.
try calling the adapter again with a null like.
setListAdapter()

how to reload activity on Item click of ListView in android

public class HomeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
new OrderData().execute();
return view;
}
class OrderData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String Response = JSONfunctions.getJSONfromURL(Constant.OrderUL + "2");
JSONObject _jobjec = new JSONObject(Response);
OrderModel _orderModel = new OrderModel();
_orderModel.setJobID(_jobjec.getString("JobID"));
_orderModel.setCustomerName(_jobjec.getString("CustomerName"));
_orderModel.setCustomerAddressName(_jobjec.getString("CustomerAddressName"));
_orderModel.setCustomerPhoneNumber(_jobjec.getString("CustomerPhoneNumber"));
_orderModel.setCustomerHouseNumber(_jobjec.getString("CustomerHouseNumber"));
_orderModel.setCustomerArea(_jobjec.getString("CustomerArea"));
_orderModel.setCustomerLandmark(_jobjec.getString("CustomerLandmark"));
_orderModel.setCustomerCity(_jobjec.getString("CustomerCity"));
_orderModel.setServiceType(_jobjec.getString("ServiceType"));
_orderModel.setQuantity(_jobjec.getString("Quantity"));
_orderModel.setPayementMethod(_jobjec.getString("PayementMethod"));
_orderModel.setJobAmount(_jobjec.getString("JobAmount"));
_orderModel.setJobStatus(_jobjec.getString("JobStatus"));
// JobStatus =_jobjec.getString("JobStatus");
orderList.add(_orderModel);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
order_listview.setAdapter(_adapter);
_adapter = new ListViewAdapter(getActivity(), R.layout.listitem, orderList);
order_listview.setAdapter(_adapter);
}
}
this is my adapter:
public class ListViewAdapter extends ArrayAdapter<OrderModel> {
// Declare Variables
Context mcontext;
LayoutInflater inflater;
List<OrderModel> datamodel;
public ListViewAdapter(Context context, int resourceId,
List<OrderModel> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
this.mcontext = context;
this.datamodel = worldpopulationlist;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
TextView textView4;
TextView status;
}
#Override
public int getCount() {
return super.getCount();
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listitem, null);
//
holder.textView1 = (TextView) view.findViewById(R.id.textView1);
holder.textView2 = (TextView) view.findViewById(R.id.textView3);
holder.textView3 = (TextView) view.findViewById(R.id.textView2);
holder.textView4 = (TextView) view.findViewById(R.id.textView17);
holder.status = (TextView) view.findViewById(R.id.aceeptimageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
holder.textView1.setText(datamodel.get(position).getJobID() + ":" + datamodel.get(position).getCustomerName());
holder.textView2.setText(datamodel.get(position).getCustomerPhoneNumber());
holder.textView3.setText(datamodel.get(position).getCustomerAddressName() + " " +
datamodel.get(position).getCustomerLandmark() + " " +
datamodel.get(position).getCustomerCity()
);
holder.textView4.setText(datamodel.get(position).getServiceType() + " " + datamodel.get(position).getJobAmount());
String Status = datamodel.get(position).getJobStatus();
if (Status.equals("Pending")) {
holder.status.setText("Accept");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
holder.status.setText("Started");
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Accepted");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Accepted")) {
holder.status.setText("Started");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Started", Toast.LENGTH_LONG).show();
holder.status.setText("Closed");
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Started");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Started")) {
holder.status.setText("Closed");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Cloesd", Toast.LENGTH_LONG).show();
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Closed");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
return view;
}
class StatsuBackground extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String Response = PosttoServer.getJSONfromURL(Constant.StatusUrl, params[0]);
return null;
}
}
}
I have applied onItem Click function in adapter each item. What I want when I click on particular item is my activity should reload and hit again api so that I can get updated value from server. How should I apply this so that I can get updated? I even tried notfydatasetchange but its not working.
public class ListViewAdapter extends ArrayAdapter<OrderModel> {
// Declare Variables
Context mcontext;
LayoutInflater inflater;
List<OrderModel> datamodel;
public ListViewAdapter(Context context, int resourceId,
List<OrderModel> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
this.mcontext = context;
this.datamodel = worldpopulationlist;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
TextView textView4;
TextView status;
}
#Override
public int getCount() {
return super.getCount();
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listitem, null);
//
holder.textView1 = (TextView) view.findViewById(R.id.textView1);
holder.textView2 = (TextView) view.findViewById(R.id.textView3);
holder.textView3 = (TextView) view.findViewById(R.id.textView2);
holder.textView4 = (TextView) view.findViewById(R.id.textView17);
holder.status = (TextView) view.findViewById(R.id.aceeptimageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
holder.textView1.setText(datamodel.get(position).getJobID() + ":" + datamodel.get(position).getCustomerName());
holder.textView2.setText(datamodel.get(position).getCustomerPhoneNumber());
holder.textView3.setText(datamodel.get(position).getCustomerAddressName() + " " +
datamodel.get(position).getCustomerLandmark() + " " +
datamodel.get(position).getCustomerCity()
);
holder.textView4.setText(datamodel.get(position).getServiceType() + " " + datamodel.get(position).getJobAmount());
String Status = datamodel.get(position).getJobStatus();
if (Status.equals("Pending")) {
holder.status.setText("Accept");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
holder.status.setText("Started");
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Accepted");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Accepted")) {
holder.status.setText("Started");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Started", Toast.LENGTH_LONG).show();
holder.status.setText("Closed");
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Started");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Started")) {
holder.status.setText("Closed");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Cloesd", Toast.LENGTH_LONG).show();
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Closed");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
return view;
}
class StatsuBackground extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String Response = PosttoServer.getJSONfromURL(Constant.StatusUrl, params[0]);
return null;
}
#Override
protected void onPostExecute(String result) {
//check if success
finish();
startActivity(((Activity)context).getIntent())
}
}
}
Try this

Arraylist become null

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.

ListView not displaying data in fragment

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.

Categories

Resources