I am trying to remove a list item from the list view using a delete Menu in the list. The delete is must for my application.
I need to delete item from fragment.
The problem in item list, I don't know how to define this List<Item> listtache.
I use this, I can launch the app and everything loads correctly. Help me please.
public class Tachefragment extends Fragment implements AdapterView.OnItemClickListener {
String supprimertache = "http://192.168.1.15/projet/supprimertache.php";
private static final int CODE_GET_REQUEST = 1024;
Httppars ht = new Httppars();
TextView txtmen;
ProgressBar progressBar;
ListView listview;
Typeface type;
ImageView img;
HashMap<String,String> hashMap = new HashMap<>();
ItemAdapter adapter ;
String listviewid;
List<Item> listtache;
List<String> idlist = new ArrayList<>();
public Tachefragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tachefragment, container, false);
txtmen = (TextView) rootView.findViewById(R.id.textmenu);
img = (ImageView) rootView.findViewById(R.id.imgmenu);
progressBar = (ProgressBar) rootView.findViewById(R.id.ProgressBar1);
listview = (ListView) rootView.findViewById(R.id.listtask);
type = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
txtmen.setTypeface(type);
listview.setOnItemClickListener(this);
listtache = new ArrayList<Item>();
new ParseJSonDataClass(container.getContext()).execute();
return rootView;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listviewid = idlist.get(i).toString();
Toast.makeText(getContext() , listviewid.toString() , Toast.LENGTH_SHORT).show();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
List<Item> item;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
httpwebservice htp = new httpwebservice(Link.affichertache);
try {
htp.ExecutePostRequest();
if (htp.getResponseCode() == 200) {
FinalJSonResult = htp.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Item itm;
item = new ArrayList<Item>();
for (int i = 0; i < jsonArray.length(); i++) {
itm = new Item();
jsonObject = jsonArray.getJSONObject(i);
idlist.add(jsonObject.getString("idt").toString());
itm.setNomt(jsonObject.getString("nomt"));
itm.setDatet(jsonObject.getString("datet"));
itm.setHeuredebut(jsonObject.getString("heuredebut"));
itm.setTempstotal(jsonObject.getString("tempstotal"));
itm.setDescription(jsonObject.getString("description"));
item.add(itm);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, htp.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (item != null) {
progressBar.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
adapter = new ItemAdapter(item, context);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(listview);
} else {
progressBar.setVisibility(View.GONE);
txtmen.setVisibility(View.VISIBLE);
img.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater minfalter = getActivity().getMenuInflater();
minfalter.inflate(R.menu.menucontext , menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Item selectitem = (Item) adapter.getItem(info.position);
switch (item.getItemId()){
case R.id.supprimer:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Voulez vous supprimer cette tache" + " " + selectitem.getNomt()+" !")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
listtache.remove(selectitem);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
In your code listtache in initialization but it is empty list .you cannot remove item if it is empty.if you want remove item from listview than you should be use item which are use in adapter.
In below example listtache replace to mListItem.
For example:
String listviewid;
List<Item> mListItem;
HashMap<String,String> hashMap = new HashMap<>();
List<String> idlist = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tachefragment, container, false);
txtmen = (TextView) rootView.findViewById(R.id.textmenu);
img = (ImageView) rootView.findViewById(R.id.imgmenu);
progressBar = (ProgressBar) rootView.findViewById(R.id.ProgressBar1);
listview = (ListView) rootView.findViewById(R.id.listtask);
type = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
txtmen.setTypeface(type);
listview.setOnItemClickListener(this);
mListItem = new ArrayList<Item>();
ht= new Httppars();
new ParseJSonDataClass(container.getContext()).execute();
return rootView;
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
httpwebservice htp = new httpwebservice(Link.affichertache);
try {
htp.ExecutePostRequest();
if (htp.getResponseCode() == 200) {
FinalJSonResult = htp.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Item itm;
for (int i = 0; i < jsonArray.length(); i++) {
itm = new Item();
jsonObject = jsonArray.getJSONObject(i);
idlist.add(jsonObject.getString("idt").toString());
itm.setNomt(jsonObject.getString("nomt"));
itm.setDatet(jsonObject.getString("datet"));
itm.setHeuredebut(jsonObject.getString("heuredebut"));
itm.setTempstotal(jsonObject.getString("tempstotal"));
itm.setDescription(jsonObject.getString("description"));
mListItem.add(itm);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, htp.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mListItem != null) {
progressBar.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
adapter = new ItemAdapter(mListItem, context);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(listview);
} else {
progressBar.setVisibility(View.GONE);
txtmen.setVisibility(View.VISIBLE);
img.setVisibility(View.VISIBLE);
}
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Item selectitem = (Item) adapter.getItem(info.position);
switch (item.getItemId()){
case R.id.supprimer:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Voulez vous supprimer cette tache" + " " + selectitem.getNomt()+" !")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListItem.remove(selectitem);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
Related
I am creating a RecyclerView with Card view
my json data contains movie name,year,rating
my card view contains three text fields moviename,rating,year
when i click on rating field it should get the data from the json and display rating beside the rating text field, but the problem here is when i click on text field the data of my card view is displayed on other positions of the card view also.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = findViewById(R.id.recylcerview);
movieList = new ArrayList<>();
builder = new AlertDialog.Builder(this);
adapter = new MovieAdapter(this, movieList);
linearLayoutManager = new LinearLayoutManager(this);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.addItemDecoration(dividerItemDecoration);
mList.setAdapter(adapter);
if ((isNetworkConnected() == true)) {
getData();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
#Override
protected void onResume() {
super.onResume();
if ((isNetworkConnected() == true)) {
getData();
adapter.notifyDataSetChanged();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getData() {
builder = new AlertDialog.Builder(this);
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
JSONArray jArray = reader.getJSONArray("rootnode");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject jsonObject = jArray.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("title"));
movie.setRating(jsonObject.getDouble("rating"));
movie.setYear(jsonObject.getInt("releaseYear"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
There should not be any duplicate data in my recycler view
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private Context context;
Movie movie;
public MovieAdapter(Context context, ArrayList<Movie> list) {
this.context = context;
this.list = list;
}
private ArrayList<Movie> list;
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_item, parent, false);
final ViewHolder viewHolder = new ViewHolder(v);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent i=new Intent(context,Main2Activity.class);
// String a=list.get(viewHolder.getAdapterPosition()).getTitle();
// Double b=list.get(viewHolder.getAdapterPosition()).getRating();
// int c=list.get(viewHolder.getAdapterPosition()).getYear();
// String g =String.valueOf(c);
// viewHolder.textYear.setText(g);
// i.putExtra("movie",a);
// i.putExtra("rating",b);
// i.putExtra("year",c);
// context.startActivity(i);
}
});
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
movie = list.get(position);
holder.textTitle.setText(movie.getTitle());
holder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c = list.get(holder.getAdapterPosition()).getYear();
String g = String.valueOf(c);
holder.textYear.setText(g);
}
});
// holder.textRating.setText(String.valueOf(movie.getRating()));
// holder.textYear.setText(String.valueOf(movie.getYear()));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView view_container;
TextView something;
public TextView textTitle, textRating, textYear;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.textView5);
something = itemView.findViewById(R.id.Rating);
textTitle = itemView.findViewById(R.id.title);
textRating = itemView.findViewById(R.id.textView2);
textYear = itemView.findViewById(R.id.main_year);
}
}
}
Never bind data with view inside onCreateViewHolder method as you have done this on click of something' ,holder.textYear.setText(g);`
So instead of managing it like this, I suggest you to manage your rating textview with visibility.
Just move your click action inside onBindViewHolder(), and do below changes with it.
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
viewHolder.textRating.setVisibility(View.INVISIBLE);
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});
To maintain the review state:
First create one booelan variable inside your model class and generate getter-setter for that.
i.e.
private boolean isReviewedVisible = false;
public boolean isReviewedVisible() {
return isReviewedVisible;
}
public void setIsReviewedVisible(boolean isVisible) {
this.isReviewedVisible = isVisible;
}
Than add below checks in onBindViewHolder() method.
if(movie.isReviewedVisible()){
viewHolder.textRating.setVisibility(View.VISIBLE);
} else {
viewHolder.textRating.setVisibility(View.INVISIBLE);
}
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
movie.setReviewedVisible(true);
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});
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()
I'm in learning about add view programmatically. But, I'm in confusing now.
I have data, there are idpatient, idheader. Patient can have more than one ID header. When I input idpatient, it will add listview (with custom adapter) programmatically. The number of listview is same with the number of ID header.
I want to set in each listview with data patient group by ID header..
So far, I add search view when loop adding listview, but when I input one ID header to seacrh view, all of listview will view the same data according to ID header in search view..
I'm sorry for the long explanation. Can anybody help me to solve this problem?
Thanks in advance
This is My Adapter :
/**
* Created by RKI on 11/9/2016.
*/
public class AdapterHistory extends BaseAdapter implements Filterable, View.OnClickListener {
private Activity activity;
LayoutInflater inflater;
HistoryHeaderActivity main;
public int count = 0;
Context context;
public ModelHistory product;
ArrayList<ModelHistory> mStringFilterList;
ModelHistory tempValues = null;
ValueFilter valueFilter;
public Cart cart;
public AdapterHistory(HistoryHeaderActivity main, ArrayList<ModelHistory> arraylist) {
this.main = main;
this.main.historyModel = arraylist;
mStringFilterList = arraylist;
}
#Override
public int getCount() {
return main.historyModel.size();
}
#Override
public Object getItem(int position) {
return main.historyModel.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
int pos = position;
final Cart carts = CartHelper.getCart();
View vi = convertView;
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_history, null);
holder.h_id = (TextView) vi.findViewById(R.id.id_header_);
holder.h_type = (TextView) vi.findViewById(R.id.servicetype_);
holder.h_qty = (TextView) vi.findViewById(R.id.qty_);
holder.h_ps_id = (TextView) vi.findViewById(R.id.patient_id);
holder.h_ps_name = (TextView) vi.findViewById(R.id.patient_);
holder.h_dokid = (TextView) vi.findViewById(R.id.doctor_id_);
holder.h_dokname = (TextView) vi.findViewById(R.id.doctor_);
holder.h_item = (TextView) vi.findViewById(R.id.item_);
holder.h_date = (TextView) vi.findViewById(R.id.date_);
holder.checkToCart = (CheckBox) vi.findViewById(R.id.checkBox);
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
tempValues.setSelected(isChecked);
}
});
vi.setTag(holder);
vi.setTag(R.id.checkBox, holder.checkToCart);
} else {
holder = (ViewHolderItem) vi.getTag();
}
if (main.historyModel.size() <= 0) {
holder.h_date.setText("No Data");
} else {
/*** Get each Model object from Arraylist ****/
tempValues = null;
tempValues = (ModelHistory) main.historyModel.get(position);
holder.h_id.setText(tempValues.getH_id());
holder.h_type.setText(tempValues.getH_service());
holder.h_qty.setText(tempValues.getH_qty());
holder.h_ps_name.setText(tempValues.getH_p_name());
holder.h_ps_id.setText(tempValues.getH_p_id());
holder.h_dokid.setText(tempValues.getH_d_id());
holder.h_dokname.setText(tempValues.getH_d_name());
holder.h_item.setText(tempValues.getH_item());
holder.h_date.setText(tempValues.getH_date());
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
main.historyModel.get(position).setSelected(buttonView.isChecked());
}
});
holder.checkToCart.setChecked(main.historyModel.get(position).isSelected());
for (pos = 1; pos <= 1; pos++) {
main.u_pname = tempValues.getH_p_name();
main.u_pid = tempValues.getH_p_id();
main.u_service = tempValues.getH_service();
main.up_iddetail = tempValues.getH_id();
}
}
return vi;
}
#Override
public void onClick(View v) {
}
public static class ViewHolderItem {
TextView h_id, h_type, h_ps_id, h_ps_name, h_dokid, h_dokname, h_item, h_qty, h_date;
CheckBox checkToCart;
}
private List<TransactionsItem> getCartItems(Cart cart) {
List<TransactionsItem> cartItems = new ArrayList<>();
Map<Saleable, Integer> itemMap = cart.getItemWithQuantity();
for (Map.Entry<Saleable, Integer> entry : itemMap.entrySet()) {
TransactionsItem cartItem = new TransactionsItem();
cartItem.setProduct((ModelInventory) entry.getKey());
cartItem.setQuantity(entry.getValue());
cartItems.add(cartItem);
}
return cartItems;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<ModelHistory> filterList = new ArrayList<ModelHistory>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getH_id().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ModelHistory country = new ModelHistory(
mStringFilterList.get(i).getH_id(),
mStringFilterList.get(i).getH_p_id(),
mStringFilterList.get(i).getH_date(),
mStringFilterList.get(i).getH_p_name(),
mStringFilterList.get(i).getH_d_id(),
mStringFilterList.get(i).getH_d_name(),
mStringFilterList.get(i).getH_item(),
mStringFilterList.get(i).getH_qty(),
mStringFilterList.get(i).getH_service());
filterList.add(country);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
main.historyModel = (ArrayList<ModelHistory>) results.values;
notifyDataSetChanged();
}
}
}
This is My Activity :
import com.mobileproject.rki.mobile_his_receipt.view.adapter.AdapterHistory;
import org.w3c.dom.*;
import java.io.Serializable;
import java.util.*;
public class HistoryHeaderActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
static final String URL = "http://.../GetDataInv";
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_REG_ID = "Sales_Aptk_ID", KEY_DATE = "Sales_Aptk_Date",
KEY_PATIENT_ID = "Sales_Aptk_Patient_ID", KEY_SERVICE_ID = "Sales_Aptk_Type",
KEY_PATIENT_NAME = "Sales_Aptk_Patient_Name",
KEY_DOCTOR_ID = "Sales_Aptk_Doctor_ID", KEY_DOCTOR_NAME = "Sales_Aptk_Doctor_Name",
KEY_ITEM_ID = "Sales_Aptk_Detail_Item_ID", KEY_DETAIL_UNIT = "Sales_Aptk_Detail_Unit",
KEY_ITEM_QTY = "Sales_Aptk_Detail_Qty";
static final String KEY_ID_HEADER = "Sales_Aptk_ID";
static final String KEY_TABLE_INV = "Table"; // parent node
static final String KEY_ITEM_ID_INV = "Item_ID", KEY_ITEM_NAME = "Item_Name",
KEY_MAX_STOCK = "Item_Max_Stock";
public static final int DIALOG_DOWNLOAD_DATA_PROGRESS = 0, DIALOG_NO_DATA = 1,
DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 2;
Element e;
final Context context = this;
public List<ModelInventory> invModels;
private ProgressDialog mProgressDialog;
public static String id, up_iddetail, up_user, u_pid, u_pname, u_service, xml;
public ArrayList<ModelInventory> invModel = new ArrayList<ModelInventory>();
public ArrayList<ModelHistory> historyModel = new ArrayList<ModelHistory>();
public ArrayList<ModelIDHeader> headerModel = new ArrayList<ModelIDHeader>();
public Cart cart;
private Menu menu;
AdapterHistory hstAdpt, idhstAdpt;
private ProgressDialog progressDialog;
public ModelInventory productInv;
int mPosition, invPosition;
EditText p_id;
ListView listHistory;
XMLParser parser;
LinearLayout lm;
LinearLayout.LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_header);
lm = (LinearLayout) findViewById(R.id.linearMain);
params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
p_id = (EditText) findViewById(R.id.patientID);
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mPosition = position;
invPosition = position;
}
});
SharedPreferences login2 = getSharedPreferences("USERLOGIN", 0);
String doktername = login2.getString("userlogin", "0");
up_user = doktername;
p_id.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
onGetHistory();
}
});
}
/**
* Check Form Input
*
* #return
*/
private boolean isFormValid() {
String aTemp = p_id.getText().toString();
if (aTemp.isEmpty()) {
Toast.makeText(this, "Please Input Patient ID..", Toast.LENGTH_SHORT).show();
return false;
} else {
id = aTemp.toString();
}
return true;
}
protected void dismissDialogWait() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
public void onGetHistory() {
listHistory.setAdapter(null);
if (isFormValid()) {
GetDataHistoryTask syncTask = new GetDataHistoryTask();
syncTask.execute(new IntroductingMethod());
GetDataHeaderTask syncTaskHeader = new GetDataHeaderTask();
syncTaskHeader.execute(new IntroductingMethod());
}
}
private class GetDataHistoryTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelHistory add = new ModelHistory();
add.setH_id(parser.getValue(e, KEY_REG_ID));
add.setH_p_name(parser.getValue(e, KEY_PATIENT_NAME));
add.setH_p_id(parser.getValue(e, KEY_PATIENT_ID));
add.setH_service(parser.getValue(e, KEY_SERVICE_ID));
add.setH_date(parser.getValue(e, KEY_DATE));
add.setH_detail_unit(parser.getValue(e, KEY_DETAIL_UNIT));
add.setH_d_id(parser.getValue(e, KEY_DOCTOR_ID));
add.setH_d_name(parser.getValue(e, KEY_DOCTOR_NAME));
add.setH_item(parser.getValue(e, KEY_ITEM_ID));
add.setH_qty(parser.getValue(e, KEY_ITEM_QTY));
historyModel.add(add);
}
ShowAllContentHistory();
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
private class GetDataHeaderTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryHeaderData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelIDHeader add = new ModelIDHeader();
add.setIdSalesHeader(parser.getValue(e, KEY_ID_HEADER));
headerModel.add(add);
}
if(result.contains("<Sales_Aptk_Patient_ID>"+id+"</Sales_Aptk_Patient_ID>")){
Log.d("NilaiID ", id);
AddNewList();
}
else{
Log.d("Kenapayahh", id);
}
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
public void AskUpdate(View v) {
if (hstAdpt.getCount() == 0) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Tidak ada rekaman pasien.", Toast.LENGTH_LONG).show();
} else {
SharedPreferences id_header = getSharedPreferences("IDSALESAPTK", 0);
SharedPreferences.Editor editorID = id_header.edit();
editorID.putString("idsalesaptk", up_iddetail);
editorID.commit();
SharedPreferences sendPref2 = getSharedPreferences("DATAPATIENTNAME", 0);
SharedPreferences.Editor editor2 = sendPref2.edit();
editor2.putString("datapatientname", u_pname);
editor2.commit();
editor2.clear();
SharedPreferences sendPref3 = getSharedPreferences("DATAPATIENTID", 0);
SharedPreferences.Editor editor3 = sendPref3.edit();
editor3.putString("datapatientid", u_pid);
editor3.commit();
editor3.clear();
SharedPreferences regID = getSharedPreferences("DATAREGID", 0);
String reg_ID = regID.getString("dataregid", "0");
SharedPreferences sendPref4 = getSharedPreferences("DATAREGID", 0);
SharedPreferences.Editor editor4 = sendPref4.edit();
editor4.putString("dataregid", reg_ID);
editor4.commit();
editor4.clear();
SharedPreferences sendPref1 = getSharedPreferences("DATASERVICE", 0);
SharedPreferences.Editor editor1 = sendPref1.edit();
editor1.putString("dataservice", u_service);
editor1.commit();
editor1.clear();
new LoadingDataAsync().execute();
}
}
public class LoadingDataAsync extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
updateDetail();
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
}
public void updateDetail() {
ArrayList<ModelHistory> candidateModelArrayList = new ArrayList<ModelHistory>();
for (ModelHistory model : historyModel) {
if (model.isSelected()) {
candidateModelArrayList.add(model);
}
}
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_TABLE_INV);
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
ModelInventory add = new ModelInventory();
add.setItem_ID(parser.getValue(e, KEY_ITEM_ID_INV));
add.setItem_Name(parser.getValue(e, KEY_ITEM_NAME));
add.setItem_Max_Stock(parser.getValue(e, KEY_MAX_STOCK));
invModel.add(add);
}
invModels = new ArrayList<ModelInventory>();
invModels = invModel;
ArrayAdapter<ModelInventory> adptInv = new ArrayAdapter<ModelInventory>(context, android.R.layout.simple_spinner_dropdown_item, invModels);
ArrayAdapter<ModelHistory> adptChkItem = new ArrayAdapter<ModelHistory>(context, android.R.layout.simple_spinner_dropdown_item, candidateModelArrayList);
if (adptInv.isEmpty()) {
Toast.makeText(HistoryHeaderActivity.this, "Empty Patient", Toast.LENGTH_SHORT).show();
}
cart = CartHelper.getCart();
for (mPosition = 0; mPosition < adptChkItem.getCount(); mPosition++) {
ModelHistory historyItem = (ModelHistory) adptChkItem.getItem(mPosition);
for (int j = mPosition; j < adptInv.getCount(); j++) {
ModelInventory inventoryItem = (ModelInventory) adptInv.getItem(j);
if (candidateModelArrayList.get(mPosition).getH_item().equals(inventoryItem.getItem_ID())) {
if (cart.getProducts().toString().contains(inventoryItem.getItem_Name())) {
} else {
productInv = (ModelInventory) (Serializable) adptInv.getItem(j);
int qty = Integer.parseInt(historyItem.getH_qty());
cart.add(productInv, qty);
}
} else {
}
}
}
Intent i = new Intent(getBaseContext(), CartActivity.class);
i.putExtra("PersonID", "try");
startActivity(i);
}
#Override
protected Dialog onCreateDialog(int id) {
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
hstAdpt.getFilter().filter(newText);
idhstAdpt.getFilter().filter(newText);
return false;
}
public void AddNewList(){
ArrayAdapter<ModelIDHeader> adptIDHeader = new ArrayAdapter<ModelIDHeader>(context, android.R.layout.simple_spinner_dropdown_item, headerModel);
for(int count =0; count< adptIDHeader.getCount(); count++){
idhstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
ModelIDHeader idHeader = (ModelIDHeader) adptIDHeader.getItem(count);
Button btn = new Button(this);
btn.setId(count);
btn.setText(idHeader.getIdSalesHeader());
lm.addView(btn);
SearchView search = new SearchView(this);
search.setQuery(idHeader.getIdSalesHeader(), false);
search.setOnQueryTextListener(this);
lm.addView(search);
ListView tv = new ListView(this);
tv.setId(count);
tv.setLayoutParams(params);
tv.setDividerHeight(2);
tv.setAdapter(idhstAdpt);
lm.addView(tv);
}
}
public void ShowAllContentHistory() {
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_history_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ClearPrefs();
logout();
Intent intent = new Intent(HistoryHeaderActivity.this, LoginActivity.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
}
if (id == R.id.action_home) {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
}
public void ClearPrefs() {
}
public void logout() {
SharedPreferences preferences5 = getSharedPreferences("IDLOGIN", Context.MODE_PRIVATE);
SharedPreferences.Editor editor5 = preferences5.edit();
editor5.clear();
editor5.commit();
}
}
I would like to pass the selected item "id" from listview to popupMenu , the mainActivity:
public class ListChildrenActivity extends AppCompatActivity implements Config, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "ListChildrenActivity";
ProgressDialog progressDialog;
Toolbar toolbar;
ChildrenAdapter adapter;
ListView listView;
int idConnexion, id;
private SwipeRefreshLayout refreshLayout;
Intent intent;
Child childObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_child);
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Listes des enfants");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), MainMedecinActivity.class);
startActivity(intent);
}
});
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
showChildren();
}
});
showChildren();
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View view, int itemInt, long lng) {
//String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
//Toast.makeText(ListChildrenActivity.this, selectedFromList, Toast.LENGTH_SHORT).show();
//TextView v = (TextView)view.findViewById(R.id.tv);
//String itemId = v.getText().toString();
childObj = (Child) listView.getItemAtPosition(itemInt);
id = childObj.getIdEnfant();
Toast.makeText(ListChildrenActivity.this, ""+id, Toast.LENGTH_SHORT).show();
}
});
}
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
}
private ArrayList<Child> generateData(String content) {
ArrayList<Child> children = new ArrayList<Child>();
JSONObject jObj = null;
JSONArray ja = null;
try {
ja = new JSONArray(content);
for (int i = 0; i < ja.length(); i++) {
jObj = ja.getJSONObject(i);
children.add(new Child(jObj.getInt("idEnfant"), jObj.getString("nomEnfant"), jObj.getString("prenomEnfant")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return children;
}
public void showChildren() {
if (!validate()) {
failed();
return;
}
SharedPreferences prefs = getSharedPreferences("Info_Connexion", Context.MODE_PRIVATE);
idConnexion = prefs.getInt("idConnexion", 0);
progressDialog = new ProgressDialog(ListChildrenActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("La liste des enfants ...");
progressDialog.show();
if (isOnline()) {
requestData(SERVER_URL + "enfant/read/", idConnexion);
} else {
Toast.makeText(ListChildrenActivity.this, "Eroor network", Toast.LENGTH_SHORT).show();
}
}
private void requestData(String url, int id) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
RequestPackage p = new RequestPackage();
p.setMethod("POST");
p.setUri(url);
p.setParam("idMedecin", String.valueOf(id));
MessagesTask task = new MessagesTask();
task.execute(p);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public void success(final int id, final ProgressDialog progressDialog, String content, SwipeRefreshLayout refreshLayout) {
// 1. pass context and data to the custom adapter
adapter = new ChildrenAdapter(this, generateData(content));
// 2. Get ListView from activity_main.xml
// 3. setListAdapter
listView.setAdapter(adapter);
if (id != 0) {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
} else {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
Toast.makeText(ListChildrenActivity.this, "Eroor server or input", Toast.LENGTH_SHORT).show();
}
}
public boolean validate() {
boolean valid = true;
return valid;
}
public void failed() {
Toast.makeText(getBaseContext(), "List Children failed", Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
TextView scoreView = (TextView) findViewById(R.id.score);
switch (item.getItemId()) {
case R.id.infos:
intent = new Intent(getBaseContext(), ChildInformationsActivity.class);
intent.putExtra("idEnfant", id );
startActivity(intent);
return true;
case R.id.signes_diagnostic:
intent = new Intent(getBaseContext(), ChildSignesDiagnosticActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.bilan_bio:
intent = new Intent(getBaseContext(), ChildBilanBioActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.traitement_medical:
intent = new Intent(getBaseContext(), ChildTraitementMedicalActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.imagerie:
intent = new Intent(getBaseContext(), ChildImagerieActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
default:
return false;
}
}
private class MessagesTask extends AsyncTask<RequestPackage, String, String> {
#Override
protected String doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return content;
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
#Override
protected void onPostExecute(String content) {
Log.i(TAG, "------------------------" + content);
success(idConnexion, progressDialog, content, refreshLayout);
}
}
}
enter image description here
class adapter:
public class ChildrenAdapter extends ArrayAdapter<Child> {
private final Context context;
private final ArrayList<Child> childrenArrayList;
public ChildrenAdapter(Context context, ArrayList<Child> childrenArrayList) {
super(context, R.layout.row_child, childrenArrayList);
this.context = context;
this.childrenArrayList = childrenArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowChildView = inflater.inflate(R.layout.row_child, parent, false);
// 3. Get the two text view from the rowView
TextView nameView = (TextView) rowChildView.findViewById(R.id.name);
TextView dateView = (TextView) rowChildView.findViewById(R.id.date);
TextView scoreView = (TextView) rowChildView.findViewById(R.id.score);
// 4. Set the text for textView
//String text = childrenArrayList.get(position).getNomEnfant())+" "+childrenArrayList.get(position).getNomEnfant();
nameView.setText(childrenArrayList.get(position).getNomEnfant()+" "+childrenArrayList.get(position).getPrenomEnfant());
dateView.setText("22/12/2012");
scoreView.setText(String.valueOf(childrenArrayList.get(position).getIdEnfant()));
scoreView.setBackgroundResource(R.drawable.circular_textview);
// 5. retrn rowView
return rowChildView;
}
}
Whene i click to the row of listview i get the "id" but how i can pass it to the popupMenu.
The solution: it just add settag(position) to imageview in getview, then :
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
listView.performItemClick(v, (Integer) v.getTag(),listView.getItemIdAtPosition((Integer) v.getTag()));
}
You can use interface to communicate between them
In your adapter class, initialize
private OnItemSelectedListener mListener;
and add these methods
public void setOnItemClickLister(OnItemSelectedListener mListener) {
this.mListener = mListener;
}
//Creating an interface
public interface OnItemSelectedListener {
public void onItemSelected(String s);
}
in onClick function in adapter
use this
mListener.onItemSelected(id);
//id is your string
you can call it in MainActivity,
adapter.setOnItemClickLister(new OnItemSelectedListener() {
#Override
public void onItemSelected(String s) {
//you will get the string here, you can pass it as an argument in popup menu
}
});
On the adapter Side:
view.findViewById(R.id.menu_btn).setTag(id);
On the ListActivity Side:
public void showPopUp(View v){
currentId = v.getTag().toString();
PopupMenu popupMenu=new PopupMenu(this,v);
popupMenu.setOnMenuItemClickListener(ListActivity.this);
MenuInflater inflater=popupMenu.getMenuInflater();
inflater.inflate(R.menu.my_pop_up,popupMenu.getMenu());
popupMenu.show();
}
On XML side:
<ImageButton android:id="#+id/menu_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_overflow"
android:layout_marginStart="10dp"
android:layout_marginEnd="20dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:onClick="showPopUp"/>
Note: onClick="showPopUp" is very critical here.
This should be helpful. Thank you.
This ListView class where i bring different element from my server with help of php and JSON calls to my listview. The problem is i would like to send the ID of element to another view when i click of specific element on listview. and in another View i would like to publish the detail information about the element that i clicked. Any wan have idea about that?
public class Forestillinger extends AppCompatActivity {
ListView dagensaktivitet;
TextView txt;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
JSONParser jsonParser = new JSONParser();
JSONObject hc = null;
JSONArray fstilling;
public String hk = "";
int success;
String msg;
final Context c = this;
StableArrayAdapter adb;
private static final String url_Forestillinger = "http://barnestasjonen.no/test/db_get_forestillinger.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestillinger);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dagensaktivitet = (ListView) findViewById(R.id.forestillinglist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems) {
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView txt = (TextView) view.findViewById(android.R.id.text1);
txt.setTextColor(Color.WHITE);
return view;
}
};
dagensaktivitet.setAdapter(adapter);
Log.d("i oncreate", adapter.toString());
//if(!fromLocalDB())
try {
new getShows().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//JSONObject tickets = task.getJSon();
adapter.notifyDataSetChanged();
dagensaktivitet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Forestilling.class);
i.putExtra("selectedItem", listItems.get(position));
startActivity(i);
}
});
}
public void fromExtDB() throws JSONException {
fstilling = hc.getJSONArray("forestillinger");
for (int i = 0; i < fstilling.length(); i++) {
listItems.add(fstilling.getJSONObject(i).getString("tittel")+fstilling.getJSONObject(i).getString("id"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_forestillinger, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void forestillingResult(){
new AlertDialog.Builder(Forestillinger.this)
.setTitle("OBS!!!")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
hk = "";
finish();
}
})
.show();
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
List<Integer> trialId;
public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects, List<Integer> objectId) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); i++)
mIdMap.put(objects.get(i), i);
trialId = objectId;
}
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
public int getActualId(int position)
{
return trialId.get(position);
}
}
class getShows extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
Log.d("TEST", "jeg er her");
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("id", "adam#gmail.com"));
//params.add(new BasicNameValuePair("type", "android"));
JSONObject json = jsonParser.makeHttpRequest(url_Forestillinger, "POST", params);
try {
if (json != null) {
success = Integer.parseInt(json.getString("success"));
msg = json.toString();
System.out.println("Vi er her:" + msg + " " + success);
}
if (success == 1) {
hc = json;
System.out.println("jojo"+json.toString());
}
else
{
msg=json.getString("message");
System.out.println(msg);
msg= Html.fromHtml(msg).toString();
hk = msg;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//run code
try {
Log.d("TAG23", "vi er in onpostExecute");
if(success == 1) {
fromExtDB();
}else{
forestillingResult();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and here is the second view.
public class Forestilling extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestilling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*Bundle extras = getIntent().getExtras();
Log.d("TAG:", "" + extras.getInt("TryThis"));*/
Bundle extras = getIntent().getExtras();
String s = extras.getString("selectedItem");
Log.d("TAG:", "" + s);
TextView tit = (TextView)findViewById(R.id.tittel);
TextView dato = (TextView)findViewById(R.id.dato);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_forestilling, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm not allowed to flag at this moment, but this might be a duplicate of how can i use the number from textfield of each row in listview and make a call on this number?
Anyway, my answer given there might solve your problem:
Here is what I do:
private class MyAdapter extends BaseAdapter {
private ListView listView;
...
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
this.listView = (ListView) viewGroup;
and then in each View.OnClickListener I can get the position of the clicked item by
#Override
public void onClick(View view) {
...
MyAdapter.this.listView.getPositionForView((View) view.getParent()));