I have 2 fragments, one contains List class and other is Favorites class That shares List from List.
How can i open correct Activity from Favorites fragment
Favorite class
public class FavoriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
ListView favoriteList;
SharedPreference sharedPreference;
List<Station> favorites;
Activity activity;
ListAdapter listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_station_list, container,
false);
// Get favorite items from SharedPreferences.
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(activity);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
favoriteList = (ListView) view.findViewById(R.id.list_product);
if (favorites != null) {
listAdapter = new ListAdapter(activity, favorites);
favoriteList.setAdapter(listAdapter);
favoriteList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,int position, long arg3) {
Intent i;
switch (position)
{
case 0:
i = new Intent(getActivity(), Citizen.class);
startActivity(i);
break;
case 1:
i = new Intent(getActivity(), Ntv.class);
startActivity(i);
break;
}
}
});
favoriteList
.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity,
favorites.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_fill);
} else {
sharedPreference.removeFavorite(activity,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.star_blank);
listAdapter.remove(favorites
.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
return view;
}
public void showAlert(String title, String message) {
if (activity != null && !activity.isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(activity)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void onResume() {
getActivity().setTitle(R.string.favorites);
getActivity().getActionBar().setTitle(R.string.favorites);
super.onResume();
}
}
List class
public class ListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "product_list";
Activity activity;
ListView stationListView;
List<Station> stations;
ListAdapter listAdapter;
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_station_list, container,
false);
findViewsById(view);
setStations();
listAdapter = new ListAdapter(activity, stations);
stationListView.setAdapter(listAdapter);
stationListView.setOnItemClickListener(this);
stationListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
stationListView = (ListView) view.findViewById(R.id.list_product);
}
private void setStations() {
Station station1 = new Station(1, R.drawable.ic_launcher, "Ntv", "Programme",1);
Station station2 = new Station(2, R.drawable.albania_tave, "Ntv", "Programme",2);
Station station3 = new Station(3, R.drawable.albania_tave,"Kiss tv", "Programme",3);
Station station4 = new Station(4, R.drawable.albania_tave, "Ntv", "Programme",4);
Station station5 = new Station(5, R.drawable.ic_launcher, "Ntv", "Citizen",5);
Station station6 = new Station(6, R.drawable.ic_launcher, "Citizen", "Citizen",6);
Station station7 = new Station(7, R.drawable.ic_launcher, "Ntv", "Programme",7);
Station station8 = new Station(8,R.drawable.ic_launcher, "Ntv", "Programme",8);
Station station9 = new Station(9,R.drawable.ic_launcher, "Ntv", "Programme",9);
Station station10 = new Station(10,R.drawable.ic_launcher,"Ntv", "Programme",10);
stations = new ArrayList<Station>();
stations.add(station1);
stations.add(station2);
stations.add(station3);
stations.add(station4);
stations.add(station5);
stations.add(station6);
stations.add(station7);
stations.add(station8);
stations.add(station9);
stations.add(station10);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i;
switch (position)
{
case 0:
i = new Intent(getActivity(), Citizen.class);
startActivity(i);
break;
case 1:
i = new Intent(getActivity(), Ntv.class);
startActivity(i);
break;
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, stations.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_fill);
} else {
sharedPreference.removeFavorite(activity, stations.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.star_blank);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
Related
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 have worked with the concept of filter that have to filter the job from job list based on skills and some list or there.
https://postimg.org/image/g3p1z6lbd/ - DashBoard Fragment.
About DashBoardFragment:
Contains job list view.
Dash Filter Button. - which redirect to the Filter screen.
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("onItemClick", "onItemClick <---- ");
Intent toPositionDetail = new Intent(getActivity(), PositionDetailScreenRefactor.class);
toPositionDetail.putExtra("id", dashRowList1.get(position).getDashId());
startActivity(toPositionDetail);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
}
});
final int totalJobCount = SessionStores.gettotalJobList(getActivity());
Log.e("totalJobCount", "totalJobCount----" + totalJobCount);
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Please Wait. It is Loading..job orders....");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
// progress.dismiss();
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}}
DashBoardTask:
public class DashBoardTask {
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
//Getting Response and Assign into model Class
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
DashListAdapter:
________________
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
Log.e("get pos", "get pooooossss---->" + dashRowList.get(position));
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
//Assign the value into screen
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
}
the above code for displaying dashboard fragment list.
https://postimg.org/image/nqvp1dud9/ - This link is FilterScreen
By using this image if i filter the job based on the designed UI detail. That should replace into the DashboadFragment list The result should display into the DashBoard Fragment. How can I add pagination on Filter screen the same which have in DashBoardFragment.
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.
I have a fragment (ItemFragment) with a bunch of EditText, a spinner and datepicker. The user input will be saved in SQL database. The user input then displayed in a list fragment (ListFragment) using RecyclerView. When a user click on the item in the list, it will go to ItemFragment and restore the user input. I added onSaveInstanceState in ItemFragment. I'm pretty new to Android so please bear with me. So how do I restore ItemFragment state during RecylerView's onTouchEvent?
ItemFragment.java (not sure if this is the correct way to do this?)
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("unit", unit);
outState.putString("date", date);
outState.putString("note", Note);
}
ListFragment.java
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildLayoutPosition(child);
Item selectedItem = mItems.get(position);
//How do I restore ItemFragment here???
return true;
}
return false;
}
Edited added Item.java and full code of ItemFragment.java
Item.java
public class Item {
private Long id;
private String title;
private String quantity;
private String unit;
private String date;
private String Note;
public String getNote() {
return Note;
}
public void setNote(String Note) {
this.Note = Note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public static Item getItemfromCursor(Cursor cursor){
Item item = new Item();
item.setId(cursor.getLong(cursor.getColumnIndex(Constants.COLUMN_ID)));
item.setTitle(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_TITLE)));
item.setQuantity(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_QUANTITY)));
item.setUnit(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_UNIT)));
item.setNote(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_NOTE)));
item.setDate(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_DATE)));
return item;
}
}
ItemFragment.java
public class ItemFragment extends DialogFragment {
private View mRootView;
private Item currentItem = null;
private Toolbar mToolbar;
private String date;
private String Note;
private String title;
private String quantity;
private TextView dateText;
private TextView unitError;
private EditText itemEditText;
private EditText quantityEditText;
private EditText noteEditText;
private Spinner remSpinner;
private Spinner spinner;
private String unit;
private String reminder;
private int spinnerCount=0;
private int spinnerInitializedCount=0;
private int remSpinnerCount=0;
private int remSpinnerInitializedCount=0;
public ItemFragment() {
}
//create an instance of the fragment
public static ItemFragment newInstance(long id) {
ItemFragment fragment = new ItemFragment();
if (id > 0) {
Bundle bundle = new Bundle();
bundle.putLong("id", id);
fragment.setArguments(bundle);
}
return fragment;
}
//get id of an item
public void getCurrentItem() {
Bundle args = getArguments();
if (args != null && args.containsKey("id")) {
long id = args.getLong("id", 0);
if (id > 0) {
currentItem = ItemManager.newInstance(getActivity()).getItem(id);
}
}
}
//notify Activity that the fragment wants to place an item in the menu
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getCurrentItem();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add_item, container, false);
itemEditText=(EditText)mRootView.findViewById((R.id.add_item));
quantityEditText=(EditText)mRootView.findViewById(R.id.amount);
unitError = (TextView)mRootView.findViewById(R.id.unit_error);
noteEditText = (EditText)mRootView.findViewById(R.id.add_notes);
dateText = (TextView)mRootView.findViewById(R.id.date_selected);
//unit spinner code here
//reminder spinner here
spinner.setOnItemSelectedListener(spinnerListener);
remSpinner.setOnItemSelectedListener(spinnerListener);
spinnerCount=1;
remSpinnerCount=1;
return mRootView;
}
//spinner listener
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
if(spinnerInitializedCount<spinnerCount){
spinnerInitializedCount++;
} else {
//get selected unit
unit = parent.getItemAtPosition(position).toString();
}
break;
case R.id.reminder_list:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
//get selected reminder
reminder = parent.getItemAtPosition(position).toString();
break;
}
}}
public void onNothingSelected(AdapterView<?> parent) {
}
};
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_item, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.delete:
if(currentItem != null){
promptForDelete();
}
else{
makeToast("Cannot delete item that has not been saved");
}
break;
case R.id.save:
if(saveItem()){
makeToast(currentItem != null ? "Item updated" : "Item saved");
}
break;
}
return super.onOptionsItemSelected(item);
}
private void makeToast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private boolean saveItem(){
Note = noteEditText.getText().toString();
date = dateText.getText().toString();
title = itemEditText.getText().toString();
if(TextUtils.isEmpty(title)){
itemEditText.setError("Item is required");
return false;
}
quantity = quantityEditText.getText().toString();
if(TextUtils.isEmpty(quantity)){
quantityEditText.setError("Quantity is required");
return false;
}
if(unit.equals("None")){
unitError = (TextView)spinner.getSelectedView();
unitError.setError("");
unitError.setTextColor(Color.RED);
unitError.setTextSize(R.dimen.text_size_normal);
unitError.setText("Select a unit!");
return false;
}
if(currentItem != null){
currentItem.setTitle(title);
currentItem.setQuantity(quantity);
currentItem.setUnit(unit);
currentItem.setDate(date);
currentItem.setNote(Note);
ItemManager.newInstance(getActivity()).update(currentItem);
}
else {
Item item = new Item();
item.setTitle(title);
item.setQuantity(quantity);
item.setUnit(unit);
item.setDate(date);
item.setNote(Note);
ItemManager.newInstance(getActivity()).create(item);
}
return true;
}
private void populateFields(){
itemEditText.setText(currentItem.getTitle());
quantityEditText.setText(currentItem.getQuantity());
noteEditText.setText(currentItem.getNote());
dateText.setText(currentItem.getDate());
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("selunit", unit);
outState.putString("seldate", date);
outState.putString("note", Note);
}
public void promptForDelete(){
final String itemToBeDeleted = currentItem.getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete" + itemToBeDeleted + "?");
alertDialog.setMessage("Are you sure you want to delete " + itemToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ItemManager.newInstance(getActivity()).delete(currentItem);
makeToast(itemToBeDeleted + "deleted");
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
EDITED - added ItemListAdapter.java & ItemManager.java
ItemListAdapter.java
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder> {
private List<Item> mItems;
private Context mContext;
public ItemListAdapter(List<Item> items, Context context){
mItems = items;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(rowView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemx.setText(mItems.get(position).getTitle());
holder.quantity.setText(String.valueOf(mItems.get(position).getQuantity()));
holder.unit.setText(mItems.get(position).getUnit());
holder.note.setText(mItems.get(position).getNote());
holder.expDate.setText(mItems.get(position).getDate());
}
#Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView itemx;
public final TextView quantity;
public final TextView unit;
public final TextView note;
public final TextView expDate;
public ViewHolder(View itemView) {
super(itemView);
itemx = (TextView)itemView.findViewById(R.id.tv_item);
quantity = (TextView)itemView.findViewById(R.id.tv_quantity);
unit = (TextView)itemView.findViewById(R.id.tv_unit);
note = (TextView)itemView.findViewById(R.id.tv_note);
expDate = (TextView)itemView.findViewById(R.id.tv_exp_date);
}
}
public void promptForDelete(final int position){
String fieldToBeDeleted = mItems.get(position).getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Delete " + fieldToBeDeleted + " ?");
alertDialog.setMessage("Are you sure you want to delete the item " + fieldToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mItems.remove(position);
notifyItemRemoved(position);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
ItemManager.java
public class ItemManager{
private Context mContext;
private static ItemManager itemManagerInstance = null;
public static ItemManager newInstance(Context context){
if (itemManagerInstance == null){
itemManagerInstance = new ItemManager(context.getApplicationContext());
}
return itemManagerInstance;
}
private ItemManager(Context context){
this.mContext = context.getApplicationContext();
}
public long create(Item item){
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_TITLE, item.getTitle());
values.put(Constants.COLUMN_QUANTITY, item.getQuantity());
values.put(Constants.COLUMN_UNIT, item.getUnit());
values.put(Constants.COLUMN_EXPIRY_DATE, item.getDate());
values.put(Constants.COLUMN_NOTE, item.getNote());
Uri result = mContext.getContentResolver().insert(XContentProvider.ITEM_URI, values);
long id = Long.parseLong(result.getLastPathSegment());
return id;
}
public void update(Item item){
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_TITLE, item.getTitle());
values.put(Constants.COLUMN_QUANTITY, item.getQuantity());
values.put(Constants.COLUMN_UNIT, item.getUnit());
values.put(Constants.COLUMN_EXPIRY_DATE, item.getDate());
values.put(Constants.COLUMN_NOTE, item.getNote());
mContext.getContentResolver().update(XContentProvider.ITEM_URI, values, Constants.COLUMN_ID + " = " + item.getId(), null);
}
public void delete(Item item){
mContext.getContentResolver().delete(XContentProvider.ITEM_URI, Constants.COLUMN_ID + " = " + item.getId(), null);
}
public List<Item> getAllItems(){
List<Item> items = new ArrayList<Item>();
Cursor cursor = mContext.getContentResolver().query(XContentProvider.ITEM_URI, Constants.COLUMNS, null, null, null);
if (cursor != null){
cursor.moveToFirst();
while (!cursor.isAfterLast()){
items.add(Item.getItemfromCursor(cursor));
cursor.moveToNext();
}
cursor.close();
}
return items;
}
public Item getItem(Long id){
Item item;
Cursor cursor = mContext.getContentResolver().query(XContentProvider.ITEM_URI, Constants.COLUMNS, Constants.COLUMN_ID + " = " + id, null, null);
if (cursor != null){
cursor.moveToFirst();
item = Item.getItemfromCursor(cursor);
return item;
}
return null;
}
}
You probably need to use SharedPreferences or SQL database to save data .onSaveInstanceState is used for save state when fragment is possible to be destroyed.
Just pass id of item to ItemFragment and display data in it.
openFragment(new ItemFragment(item.getId()), "Add Item")
package com.airi.vcare;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class ItemFragment extends DialogFragment {
private View mRootView;
private Item currentItem = null;
private Toolbar mToolbar;
private String date;
private String Note;
private String title;
private String quantity;
private TextView dateText;
private TextView unitError;
private EditText itemEditText;
private EditText quantityEditText;
private EditText noteEditText;
private Spinner remSpinner;
private Spinner spinner;
private String unit;
private String reminder;
private int spinnerCount=0;
private int spinnerInitializedCount=0;
private int remSpinnerCount=0;
private int remSpinnerInitializedCount=0;
public ItemFragment() {
}
//create an instance of the fragment
public static ItemFragment newInstance(long id) {
ItemFragment fragment = new ItemFragment();
if (id > 0) {
Bundle bundle = new Bundle();
bundle.putLong("id", id);
fragment.setArguments(bundle);
}
return fragment;
}
//get id of an item
public void getCurrentItem() {
Bundle args = getArguments();
if (args != null && args.containsKey("id")) {
long id = args.getLong("id", 0);
if (id > 0) {
currentItem = ItemManager.newInstance(getActivity()).getItem(id);
}
}
}
//notify Activity that the fragment wants to place an item in the menu
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getCurrentItem();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add_item, container, false);
itemEditText=(EditText)mRootView.findViewById((R.id.add_item));
quantityEditText=(EditText)mRootView.findViewById(R.id.amount);
unitError = (TextView)mRootView.findViewById(R.id.unit_error);
noteEditText = (EditText)mRootView.findViewById(R.id.add_notes);
dateText = (TextView)mRootView.findViewById(R.id.date_selected);
//unit spinner code here
//reminder spinner here
spinner.setOnItemSelectedListener(spinnerListener);
remSpinner.setOnItemSelectedListener(spinnerListener);
spinnerCount=1;
remSpinnerCount=1;
//just display fields .
populateFields();
return mRootView;
}
//spinner listener
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
if(spinnerInitializedCount<spinnerCount){
spinnerInitializedCount++;
} else {
//get selected unit
unit = parent.getItemAtPosition(position).toString();
}
break;
case R.id.reminder_list:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
//get selected reminder
reminder = parent.getItemAtPosition(position).toString();
break;
}
}}
public void onNothingSelected(AdapterView<?> parent) {
}
};
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_item, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.delete:
if(currentItem != null){
promptForDelete();
}
else{
makeToast("Cannot delete item that has not been saved");
}
break;
case R.id.save:
if(saveItem()){
makeToast(currentItem != null ? "Item updated" : "Item saved");
}
break;
}
return super.onOptionsItemSelected(item);
}
private void makeToast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private boolean saveItem(){
Note = noteEditText.getText().toString();
date = dateText.getText().toString();
title = itemEditText.getText().toString();
if(TextUtils.isEmpty(title)){
itemEditText.setError("Item is required");
return false;
}
quantity = quantityEditText.getText().toString();
if(TextUtils.isEmpty(quantity)){
quantityEditText.setError("Quantity is required");
return false;
}
if(unit.equals("None")){
unitError = (TextView)spinner.getSelectedView();
unitError.setError("");
unitError.setTextColor(Color.RED);
unitError.setTextSize(R.dimen.text_size_normal);
unitError.setText("Select a unit!");
return false;
}
if(currentItem != null){
currentItem.setTitle(title);
currentItem.setQuantity(quantity);
currentItem.setUnit(unit);
currentItem.setDate(date);
currentItem.setNote(Note);
ItemManager.newInstance(getActivity()).update(currentItem);
}
else {
Item item = new Item();
item.setTitle(title);
item.setQuantity(quantity);
item.setUnit(unit);
item.setDate(date);
item.setNote(Note);
ItemManager.newInstance(getActivity()).create(item);
}
return true;
}
private void populateFields(){
itemEditText.setText(currentItem.getTitle());
quantityEditText.setText(currentItem.getQuantity());
noteEditText.setText(currentItem.getNote());
dateText.setText(currentItem.getDate());
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("selunit", unit);
outState.putString("seldate", date);
outState.putString("note", Note);
}
public void promptForDelete(){
final String itemToBeDeleted = currentItem.getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete" + itemToBeDeleted + "?");
alertDialog.setMessage("Are you sure you want to delete " + itemToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ItemManager.newInstance(getActivity()).delete(currentItem);
makeToast(itemToBeDeleted + "deleted");
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder> {
private List<Item> mItems;
private Context mContext;
public ItemListAdapter(List<Item> items, Context context){
mItems = items;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(rowView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemx.setText(mItems.get(position).getTitle());
holder.quantity.setText(String.valueOf(mItems.get(position).getQuantity()));
holder.unit.setText(mItems.get(position).getUnit());
holder.note.setText(mItems.get(position).getNote());
holder.expDate.setText(mItems.get(position).getDate());
holder.item.getParent().setOnClick(new OnClickListener(){
onclick(View view){
//todo here
openFragment(new ItemFragment(item.getId()), "Add Item")
}
})
}
#Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView itemx;
public final TextView quantity;
public final TextView unit;
public final TextView note;
public final TextView expDate;
public ViewHolder(View itemView) {
super(itemView);
itemx = (TextView)itemView.findViewById(R.id.tv_item);
quantity = (TextView)itemView.findViewById(R.id.tv_quantity);
unit = (TextView)itemView.findViewById(R.id.tv_unit);
note = (TextView)itemView.findViewById(R.id.tv_note);
expDate = (TextView)itemView.findViewById(R.id.tv_exp_date);
}
}
public void promptForDelete(final int position){
String fieldToBeDeleted = mItems.get(position).getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Delete " + fieldToBeDeleted + " ?");
alertDialog.setMessage("Are you sure you want to delete the item " + fieldToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mItems.remove(position);
notifyItemRemoved(position);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
i hope you guys can help me. it`s drivin me crazy find the solution...
i already read some question that similar with my problems, but none solved mine.
here`s the problems
1 have 2 activity...
first --> i have activity that contain a view pager which hold 3 tab fragment.
in this first activity i extends with fragmentActivity
and here the code
public class A_BonRokok_Add_Main_Paged extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Header", "Item", "Info"};
MainActivity main = new MainActivity();
FragmentManager manager;
FragmentTransaction transaction;
Dialog alert;
LayoutInflater li;
LinearLayout someLayout;
Button btnSave_dialog;
Button btnCancel_dialog;
public EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_bon_rokok_add_main_paged);
FragmentPagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
getActionBar().setDisplayHomeAsUpEnabled(true);
pager.setOffscreenPageLimit(3);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_print) {
Toast.makeText(this, "print", Toast.LENGTH_SHORT).show();
}
else if (item.getItemId() == R.id.edit_save) {
Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();
}
else{
createDialogConfirm();
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
public void onBackPressed(){
createDialogConfirm();
}
public void createDialogConfirm(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert.show();
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt(ChildFragmentPaged.POSITION_KEY, position);
return ChildFragmentPaged.newInstance(args);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
}
public static A_BonRokok_Add_Main_Paged newInstance() {
return new A_BonRokok_Add_Main_Paged();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.save_print, menu);
return super.onCreateOptionsMenu(menu);
}
}
the first activity manage the tab fragment using class which extends fragment...
here the code
public class ChildFragmentPaged extends Fragment {
public static final String POSITION_KEY = "FragmentPositionKey";
private int position;
View root;
static EditText txtDate, txtGudang;
static RadioGroup btnGroupGudang;
static RadioButton btnGudang1, btnGudang2;
static Button btnNewItem, btnNewItem_Cancel;
private database mySQLiteAdapter;
private A_BonRokok_Item_View view = new A_BonRokok_Item_View();
public ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
AdapterView<?> tempAdt;
int tempPos;
public EditText search;
public ArrayList<bonRokokPagedEntity> list;
public ListViewAdapter adapter;
private databasePaged databasePaged;
public static ChildFragmentPaged newInstance(Bundle args) {
ChildFragmentPaged fragment = new ChildFragmentPaged();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
position = getArguments().getInt(POSITION_KEY);
if(position == 0){
root = inflater.inflate(R.layout.t_bon_rokok_header_paged, container,false);
}if (position == 1) {
root = inflater.inflate(R.layout.t_bon_rokok_item_paged, container, false);
settingTabItem();
} else if (position == 2)
root = inflater.inflate(R.layout.t_bon_rokok_info_paged, container, false);
return root;
}
public void settingTabItem() {
listContent = (ListView) root.findViewById(R.id.vl_tab_paged);
btnNewItem = (Button) root.findViewById(R.id.btnNewItem_paged);
search = (EditText)root.findViewById(R.id.search_paged);
try{
databasePaged = new databasePaged(getActivity());
databasePaged.createDataBase();
}catch(IOException ioe){
throw new Error("Unable to craete database");
}
try{
databasePaged.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
btnNewItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(),A_BonRokok_Item_New_Paged.class);
startActivity(intent);
getActivity().finish();
}
});
list = databasePaged.Getvalue();
adapter = new ListViewAdapter(getActivity(), list);
listContent.setAdapter(adapter);
}
private void updateList() {
cursor.requery();
}
public void createMenu(){
final Cursor cursor = (Cursor) tempAdt.getItemAtPosition(tempPos);
final String header = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.d_global_edit_delete,null, false);
ListView lv = (ListView)contentView.findViewById(R.id.d_globalEditDelete_lvEditDelete);
TextView txtHeader = (TextView)contentView.findViewById(R.id.d_globalEditDelete_lblHeader);
Button btnCancel = (Button)contentView.findViewById(R.id.d_globalEditDelete_btnCancel);
txtHeader.setText(header);
ArrayList<String> tempData = new ArrayList<String>();
tempData.add("Edit");
tempData.add("Delete");
int layoutID = android.R.layout.simple_list_item_1;
ArrayAdapter tempAdapter = new ArrayAdapter<String>(getActivity(), layoutID, tempData);
lv.setAdapter(tempAdapter);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(contentView);
final AlertDialog alert = builder.create();
alert.show();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
if (position == 0){ //Edit Data
passStringValue();
updateList();
Intent intent = new Intent(getActivity(),A_BonRokok_Item_View.class);
intent.putExtra("status", true);
startActivity(intent);
getActivity().finish();
}
else if (position == 1){ //Delete Data
final int item_id = cursor.getInt(cursor.getColumnIndex(database.KEY_ID));
mySQLiteAdapter.delete_byID(item_id);
updateList();
alert.cancel();
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
}
public void passStringValue(){
final String nama_Rokok = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
final String kode_Rokok = "102030";
final String pita_Cukai = cursor.getString(cursor.getColumnIndex(database.SPITACUKAI));
final String jumlah = cursor.getString(cursor.getColumnIndex(database.SJUMLAH));
view.Detail(nama_Rokok, kode_Rokok, pita_Cukai, jumlah);
}
}
and the second --> i have activity that contain an edittext.
here the code
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(contentView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
});
// txtSelop.setOnFocusChangeListener(focusSelopChange);
// txtBungkus.setOnFocusChangeListener(focusBungkusChange);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_save) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
} else {
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save_print, menu);
MenuItem item = menu.findItem(R.id.edit_print);
item.setVisible(false);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
OnClickListener searchClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
createDialogSearch();
}
};
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> hm = (HashMap<String, String>)arg0.getAdapter().getItem(position);
autoCompleteBonRokok.setText(hm.get("kdRokok"));
txtNamaRokok.setText(hm.get("namaRokok"));
}
};
public void onBackPressed(){
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
OnFocusChangeListener focusBalChange = new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean isFocused) {
if(!isFocused){
if(txtBal.length()==0)
bal = 0;
else
bal = Integer.parseInt(txtBal.getText().toString());
splitValue();
}
}
};
public void saveToDatabase() {
}
private void updateList() {
cursor.requery();
}
public void createDialogSearch(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout)li.inflate(R.layout.d_bon_rokok_search_new_item, null);
DialogDummyAutoComplete[] modelItemsDialog;
final ListView lvDialog = (ListView)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_lvSearch);
modelItemsDialog = new DialogDummyAutoComplete[3];
modelItemsDialog [0] = new DialogDummyAutoComplete("1051200", "Supra need 12");
modelItemsDialog [1] = new DialogDummyAutoComplete("1051600", "Supra need 16");
modelItemsDialog [2] = new DialogDummyAutoComplete("1001200", "NY");
DialogAutoCompleteSearchRokok dialogAdapter = new DialogAutoCompleteSearchRokok(this, modelItemsDialog);
lvDialog.setAdapter(dialogAdapter);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.getWindow().getAttributes().height = LayoutParams.WRAP_CONTENT;
alert.show();
btnCancel = (Button)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
String selectedKdRokok = ((TextView)arg1.findViewById(R.id.kdRokok_dialog)).getText().toString();
String selectedNamaRokok = ((TextView)arg1.findViewById(R.id.namaRokok_dialog)).getText().toString();
autoCompleteBonRokok.setText(selectedKdRokok);
txtNamaRokok.setText(selectedNamaRokok);
alert.cancel();
}
});
}
public void splitValue(){
if (txtJumlah.length()==0)
txtJumlah.setText("0,000");
separated = txtJumlah.getText().toString().split(",");
first = separated[0];
second = separated[1];
first = Integer.toString(bal);
txtJumlah.setText(first + "," + second);
txtJumlah.clearFocus();
}
public void createDialogConfirm(){
LayoutInflater li = LayoutInflater.from(this);
LinearLayout someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
Button btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
Button btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.show();
}
}
My question is
how can i pass a value from second activity (contain edittext) to fragment in view pager, because everytime i try to insert using many way, java lang null pointer always become my nightmare...
please help me... thx you so much
Intent.putExtra("YourValueKey", datatobepassed);
on the other activity
Bundle extras = getIntent().getExtras();
if ( extras != null ){
extras.get("YourValueKey")
}