OnCickListener not working on EditText - android

On click listener not working on edit text in android
<EditText
android:id="#+id/state_search_UPFET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15sp"
android:clickable="true"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_below="#id/textView1"
android:hint="#string/hintState"
android:inputType="none"
android:padding="12sp" />

public class DoctorSearchFragment extends BaseFragment implements AbstractView, View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
private EditText SEARCH_STATE, SEARCH_CITY, DEPARTMENT;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static DoctorSearchFragment doctorSearchFragment;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private Button getDoctorButton;
public DoctorSearchFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static DoctorSearchFragment newInstance(String param1, String param2) {
DoctorSearchFragment fragment = new DoctorSearchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
doctorSearchFragment=this;
setHasOptionsMenu(false);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
AppController.getInstance().getMainActivity().getSupportActionBar().setTitle(getString(R.string.search_doctor_by));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_book_appointment, container, false);
initializeComponents(view);
return view;
}
private void initializeComponents(View view) {
SEARCH_CITY = (EditText) view.findViewById(R.id.city_search_UPFET);
SEARCH_STATE = (EditText) view.findViewById(R.id.state_search_UPFET);
DEPARTMENT = (EditText) view.findViewById(R.id.dept_search_UPFET);
getDoctorButton = (Button) view.findViewById(R.id.getDoctor) ;
SEARCH_STATE.setOnClickListener(this);
SEARCH_CITY.setOnClickListener(this);
DEPARTMENT.setOnClickListener(this);
getDoctorButton.setOnClickListener(this);
//progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.state_search_UPFET:
SEARCH_STATE.setError(null);
SEARCH_STATE.setText("");
StateListDialog stateListDialog = new StateListDialog();
stateListDialog.setAppCompatActivity((AppCompatActivity) getActivity());
stateListDialog.loadData();
break;
case R.id.city_search_UPFET:
SEARCH_CITY.setError(null);
SEARCH_CITY.setText("");
CityListDialog cityListDialog = new CityListDialog();
cityListDialog.setAppCompatActivity((AppCompatActivity) getActivity());
cityListDialog.loadData(SEARCH_STATE.getText().toString());
break;
case R.id.getDoctor:
AppController.getInstance().handleEvent(AppDefines.EVENT_ID_DOCTORSLIST);
break;
}
}
public void setState(String state) {
Log.d("TAG", "FRAGMENT STATE " + state + " IS STATE NULL " + (SEARCH_STATE == null));
if (SEARCH_STATE != null) SEARCH_STATE.setText(state);
if (SEARCH_CITY != null) SEARCH_CITY.setText("");
}
public void setCity(String city) {
Log.d("TAG", "FRAGMENT STATE " + city + " IS STATE NULL " + (SEARCH_CITY == null));
if (SEARCH_CITY != null) SEARCH_CITY.setText(city);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void update() {
}
#Override
public void onFragmentResume() {
AppController.getInstance().getMainActivity().getSupportActionBar().setTitle(getString(R.string.search_doctor_by));
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public static DoctorSearchFragment getInstance() {
return doctorSearchFragment;
}
}

Related

How to handle back button in tab's fragment?

I have an activity,and have 2 fragments thats name is AddressFragment and ProfileFragment thats extend from BaseFragment.
How i can handle back button in tab fragment.
if a info_ll(a linearlayout) is show,when back button is pressed gone and a recyclerview is show
and if recyclerview is showing,when back press button clicked finish activity
public class ProfileActivity extends AppCompatActivity{
TabLayout tabLayout;
ViewPager viewPager;
public void setTv_name(String tv_name) {
ProfileActivity.tv_name.setText(tv_name);
}
public void setTv_email(String tv_email) {
ProfileActivity.tv_email.setText(tv_email);
}
public void setTv_phone(String tv_phone) {
ProfileActivity.tv_phone.setText(tv_phone);
}
public static MyTextView tv_name;
public static MyTextView tv_email;
public static MyTextView tv_phone;
CircularImageView iv_profile;
ImageButton btn_back;
BaseFragment currentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
TabLayout tabhost = (TabLayout) this.findViewById(R.id.tabs);
tabhost.getTabAt(getIntent().getIntExtra("go_to",0)).select();
tv_name= (MyTextView) findViewById(R.id.tv_name);
tv_email= (MyTextView)findViewById(R.id.tv_email);
tv_phone= (MyTextView)findViewById(R.id.tv_phone);
iv_profile= (CircularImageView) findViewById(R.id.profile);
btn_back= (ImageButton) findViewById(R.id.btn_Back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ProfileFragment(), "ویرایش اطلاعات");
adapter.addFragment(new AddressFragment(), "آدرس های منتخب");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
currentFragment = null;
switch (position) {
case 0:
currentFragment = new ProfileFragment();
break;
case 1:
currentFragment = new AddressFragment();
break;
}
return currentFragment;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setImage(){
if(!DataContainer.getObject().getProfileImagePath().equals("None"))
Glide.with(this).load(DataContainer.getObject().getProfileImagePath()).into(iv_profile);
}
#Override
public void onBackPressed() {
if(currentFragment == null || !currentFragment.onBackPressed())
super.onBackPressed();
}
}
AddressFragment
public class AddressFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
ProgressDialog pDialog;
int pDilog_Counter=0;
private View rootView;
private RecyclerView recyclerView;
MyEditText et_title;
MyEditText et_address;
LinearLayout info_ll;
Button btn_edit;
ImageButton btn_location;
FloatingActionButton fab;
double latitude;
double longitude;
public static final int RESULT_OK = -1;
int status=0;
int profileID=0;
public AddressFragment() {
}
public static AddressFragment newInstance(String param1, String param2) {
AddressFragment fragment = new AddressFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_address, container, false);
info_ll= (LinearLayout) rootView.findViewById(R.id.info_ll);
et_title= (MyEditText) rootView.findViewById(R.id.et_title);
et_address= (MyEditText) rootView.findViewById(R.id.et_address);
btn_edit= (Button) rootView.findViewById(R.id.btn_edit);
btn_location= (ImageButton) rootView.findViewById(R.id.btn_location);
fab= (FloatingActionButton) rootView.findViewById(R.id.fab);
recyclerView= (RecyclerView) rootView.findViewById(R.id.Address_recycler);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setVisibility(View.GONE);
fab.setVisibility(View.GONE);
info_ll.setVisibility(View.VISIBLE);
status=0;
btn_edit.setText("ثبت");
//PAProfileAddressAdd();
}
});
private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private JSONArray Addresses;
AddressFragment addressFragment;
public SimpleAdapter(AddressFragment addressFragment, JSONArray AddressArray) {
this.addressFragment=addressFragment;
this.Addresses=AddressArray;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.address_recyclerview_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
return Addresses.length();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private MyTextView title;
private int position;
public ViewHolder(View itemView) {
super(itemView);
title = (MyTextView) itemView.findViewById(R.id.address_txt);
itemView.setOnClickListener(this);
}
public void bind(int position) {
this.position = position;
try {
title.setText(Addresses.getJSONObject(position).getString("Title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
addressFragment.status=1;
addressFragment.rootView.findViewById(R.id.Address_recycler).setVisibility(View.GONE);
addressFragment.rootView.findViewById(R.id.fab).setVisibility(View.GONE);
addressFragment.rootView.findViewById(R.id.info_ll).setVisibility(View.VISIBLE);
addressFragment.et_title.setEnabled(false);
addressFragment.et_address.setEnabled(false);
try {
addressFragment.et_title.setText(Addresses.getJSONObject(position).getString("Title"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
addressFragment.et_address.setText(Addresses.getJSONObject(position).getString("Address"));
} catch (JSONException e) {
e.printStackTrace();
}
addressFragment.status=1;
try {
addressFragment.profileID=Integer.parseInt(Addresses.getJSONObject(position).getString("ProfileAddressID"));
} catch (JSONException e) {
e.printStackTrace();
}
//TODO open edit dialog for Addresses.getJSONObject(position)
}
}
}
#Override
public boolean onBackPressed() {
if(info_ll.getVisibility()==View.VISIBLE){
fab.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
info_ll.setVisibility(View.GONE);
return true;
}else {
return false;
}
}
}
ProfileFragment
public class ProfileFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
Button btn_edit;
EditText et_name;
EditText et_phone;
EditText et_email;
ProgressDialog pDialog;
int pDilog_Counter=0;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_profile, container, false);
btn_edit=(Button) v.findViewById(R.id.btn_edit);
et_name= (EditText) v.findViewById(R.id.et_name);
et_email= (EditText) v.findViewById(R.id.et_email);
et_phone= (EditText) v.findViewById(R.id.et_phone);
PAProfileInfo();
btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PAProfileEdit();
}
});
((ProfileActivity)getActivity()).setImage();
return v;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
private void PAProfileInfo() {
String url="http://RO.nirasoftware.com:8888/WS/WSPAProfileInfo.aspx?"+
"CustomerCode="+ DataContainer.getObject().getCustomerCode() +
"&TokenID="+ DataContainer.getObject().getTokenID() +
"&Type=JSON&VS="+DataContainer.getObject().getVersion();
showProgress();
StringRequest request = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject NRS=(new JSONObject(response)).getJSONObject("NRS");
if(NRS.getJSONObject("Error").getInt("ErrCode")==0){
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
try {
et_name.setText(NRS.getJSONObject("Customer").getString("CustomerFullName"));
et_email.setText(NRS.getJSONObject("Customer").getString("EMail"));
et_phone.setText(NRS.getJSONObject("Customer").getString("MobileNo"));
((ProfileActivity)getActivity()).setTv_name(NRS.getJSONObject("Customer").getString("CustomerFullName"));
((ProfileActivity)getActivity()).setTv_email(NRS.getJSONObject("Customer").getString("EMail"));
((ProfileActivity)getActivity()).setTv_phone(NRS.getJSONObject("Customer").getString("MobileNo"));
}catch (JSONException e){
}
hideProgress();
}else{
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
hideProgress();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Error in json received", Toast.LENGTH_LONG).show();
hideProgress();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.MyDialogTheme);
// 2. Chain together various setter methods to set the dialog characteristics
String s=error.getMessage();
if(error.networkResponse==null)
s="سرعت کم اتصال";
else
s+="\nResponse:\n\t"+error.networkResponse.toString();
builder.setMessage(s).setTitle("خطا:");
// 3. Get the AlertDialog from create()
AlertDialog dg = builder.create();
dg.setButton(AlertDialog.BUTTON_POSITIVE, "تلاش مجدد", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ProfileFragment.this.PAProfileInfo();
} });
dg.setButton(AlertDialog.BUTTON_NEGATIVE, "انصراف", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
} });
dg.show();
hideProgress();
//getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
DataContainer.getObject().getRequestQueue().add(request);
}
private void PAProfileEdit() {
String url="http://RO.nirasoftware.com:8888/WS/WSPAProfileEdit.aspx?"+
"CustomerCode="+ DataContainer.getObject().getCustomerCode() +
"&TokenID="+ DataContainer.getObject().getTokenID() +
"&Type=JSON&VS="+DataContainer.getObject().getVersion()+
"&FullName="+et_name.getText().toString()+
"&Email=" + et_email.getText().toString()+
"&Phone="+et_phone.getText().toString();
showProgress();
StringRequest request = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject NRS=(new JSONObject(response)).getJSONObject("NRS");
if(NRS.getJSONObject("Error").getInt("ErrCode")==0){
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
((ProfileActivity)getActivity()).setTv_name(et_name.getText().toString());
DataContainer.getObject().setName(et_name.getText().toString());
((ProfileActivity)getActivity()).setTv_email(et_email.getText().toString());
DataContainer.getObject().setEMail(et_email.getText().toString());
((ProfileActivity)getActivity()).setTv_phone(et_phone.getText().toString());
DataContainer.getObject().setPhoneNo(et_phone.getText().toString());
hideProgress();
}else{
Toast.makeText(getActivity(),NRS.getJSONObject("Error").getString("ErrFa"), Toast.LENGTH_SHORT).show();
hideProgress();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Error in json received", Toast.LENGTH_LONG).show();
hideProgress();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.MyDialogTheme);
// 2. Chain together various setter methods to set the dialog characteristics
String s=error.getMessage();
/* if(error.networkResponse!=null)
//TODO #$# s+="\nResponse:\n\t"+error.networkResponse.toString();
else*/
s="سرعت کم اتصال";
builder.setMessage(s).setTitle("خطا:");
// 3. Get the AlertDialog from create()
AlertDialog dg = builder.create();
dg.setButton(AlertDialog.BUTTON_POSITIVE, "تلاش مجدد", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PAProfileEdit();
} });
dg.show();
hideProgress();
//getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
DataContainer.getObject().getRequestQueue().add(request);
}
private void showProgress() {
pDilog_Counter++;
if(pDilog_Counter>1)
return;
pDialog = new ProgressDialog(getActivity(),R.style.AppCompatAlertDialogStyle);
pDialog.setMessage("لطفا منتظر بمانید....");
pDialog.show();
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
private void hideProgress() {
pDilog_Counter--;
if(pDilog_Counter>0)
return;
pDialog.hide();
pDialog.dismiss();
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
#Override
public boolean onBackPressed() {
return false;
}
}
BaseFragment
public abstract class BaseFragment extends Fragment {
public abstract boolean onBackPressed();
}
You have to give each fragment a unique TAG it will help you to easily retrieve
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, new PlaceholderFragment(), "First Fragment")
.commit();
Retrieve(e.g. in on back pressed)
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FirstFragment");
if (fragment == null) {
fragment = new PlaceholderFragment();
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment, "FirstFragment")
.commit();
Fainally i found solution I find the current fragment's tag which show in viepager and compare whit AddressFragment class
#Override
public void onBackPressed() {
BaseFragment fragment =
(BaseFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:"+R.id.viewpager+":"+viewPager.getCurrentItem());
if(fragment instanceof AddressFragment) // could be null if not instantiated yet
{
if(!fragment.onBackPressed())
super.onBackPressed();
}else
super.onBackPressed();

android adding fragment programatically doesn't accept parameter

I am trying to add a fragment programatically to my layout in the MainActivity, to be more specific in its onCreate method. I keep getting an error Cannot resolve method add(), and that really shouldnt happen because I've copied the code from the official site. Somebody please help. Here is the code:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FooterVertical fragment = new FooterVertical();
fragmentTransaction.add(R.id.activity_main, fragment);
fragmentTransaction.commit();
public class FooterVertical extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FooterVertical() {
// Required empty public constructor
}
public static FooterVertical newInstance(String param1, String param2) {
FooterVertical fragment = new FooterVertical();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_footer_vertical, container, false);
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
If you are importing android.app.Fragment; change it to android.support.v4.app.Fragment;
I use this:
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new HomeFragment()).commit();

Butter Knife #bind in Fragment error

I follow the instructions on the website : http://jakewharton.github.io/butterknife/
error : java.lang.RuntimeException: Unable to start activity ComponentInfo. java.lang.RuntimeException: Unable to bind views for com.project.myapp.OneFragment.
I try to remove #Bind(R.id.btnNext) Button btnNext; and run no error.
public class OneFragment extends Fragment {
#Bind(R.id.btnNext) Button btnNext;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public OneFragment() {
// Required empty public constructor
}
public static OneFragment newInstance(String param1, String param2) {
OneFragment fragment = new OneFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
ButterKnife.bind(this, view);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Replace this:
ButterKnife.bind(this, view);
with
ButterKnife.bind(getActivity(), view);

Android Studio Shared Preferences

Thanks a lot for looking here, I'm working on an app for school and I've run into another problem. The main idea of the app is to track your calories and I would like it to save the calories so when the app is closed it will still remember them. I've been busy for a while now trying it with SavedPreferences but I keep getting errors. I was hoping someone could help me with this.
public class CaloriesEaten extends Fragment {
private Context mContext;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static EditText caleaten;
private static EditText calalready;
private static TextView caltotal;
private static Button btnClick;
private EditText editText;
//private String calalreadystring = calalready.getText().toString();
//int CalCount = Integer.parseInt(calalreadystring);
Context context = getActivity();
SharedPreferences pref = context.getSharedPreferences("MyCalories", Context.MODE_PRIVATE);
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CaloriesEaten() {
// Required empty public constructor
}
public static CaloriesEaten newInstance(String param1, String param2) {
CaloriesEaten fragment = new CaloriesEaten();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
String keki = pref.getString("CalorieCounter", "");
editText.setText(keki);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_calories_eaten,
container, false);
caleaten = (EditText) view.findViewById(R.id.CalorieInput);
calalready = (EditText) view.findViewById(R.id.Cals);
caltotal = (TextView) view.findViewById(R.id.CalNumber);
btnClick = (Button)view.findViewById(R.id.addcalories);
btnClick.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
public void buttonClicked (View view) {
int x = Integer.parseInt(caleaten.getText().toString());
int y = Integer.parseInt(calalready.getText().toString());
int total = x + y;
caltotal.setText(Integer.toString(total));
calalready.setText(Integer.toString(total));
caleaten.setText("");
SharedPreferences.Editor edit = pref.edit();
String calalreadystring = calalready.getText().toString();
int CalCount = Integer.parseInt(calalreadystring);
edit.putInt("CalorieCounter", CalCount);
edit.commit();
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I'm probably doing a lot of obvious dumb stuff but I really can't figure it out.
Thanks a lot!
declare SharedPreferences globally and initialize inside onCreateView methode,
eg:
Context context;
SharedPreferences pref;
.......
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_calories_eaten,
container, false);
context = getActivity();
pref = context.getSharedPreferences("MyCalories", Context.MODE_PRIVATE);
.............
....
}

Buttons with fragments

I am working on an app for my school project in android studio that works with a navigation drawer and multiple fragments, I have got all the fragments setup and working but now I am stuck. I have no clue how to make working buttons in fragments.
Fragments activity
public class CaloriesEaten extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static EditText caleaten;
private static EditText calalready;
private static TextView caltotal;
private static Button btnadd;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CaloriesEaten() {
// Required empty public constructor
}
public static CaloriesEaten newInstance(String param1, String param2) {
CaloriesEaten fragment = new CaloriesEaten();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_calories_eaten,
container, false);
caleaten = (EditText) view.findViewById(R.id.CalorieInput);
calalready = (EditText) view.findViewById(R.id.Cals);
caltotal = (TextView) view.findViewById(R.id.CalNumber);
btnadd = (Button) view.findViewById(R.id.addcalories);
// Inflate the layout for this fragment
btnadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
}
public void buttonClicked (View view) {
int x = Integer.parseInt(caleaten.getText().toString());
int y = Integer.parseInt(calalready.getText().toString());
int total = x + y;
caltotal.setText(Integer.toString(total));
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This is my first time asking a question here so if i'm missing anything please let me know.
Thanks!
View override by inflating at end of onCreateView() method
Replace
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
to
return view;
in onCreateView() method
Funny reason: You are inflating a View, using it to get it's children and finally returning different inflated view instance. You should return the same instance you are inflating initially and using to get it's children.
Just change
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
to
return view;
in onCreateView() method
Replace
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
to
view = inflater.inflate(R.layout.fragment_calories_eaten, container, false);
return view;
Now using this view instance you can find you other views inflating on it as button.
btnClickMe = (Button)view.findViewById(R.id.btn);
use above code in onCreateView method before returning view.

Categories

Resources