In onAttach() method communicator =(Communicator) activity returns null. When i click on the Image View it shows the value of communicatior is null.
I have check but not able to resolve the problem. Here in the fragment when click on the image view some data should transfer to the activity. But the reference variable of Interface Commnunicator communicator gets the null value in onAttch()
public class SendFragment extends Fragment {
ImageView imgContact;
TextView tvContactName;
String username;
Communicator communicator;
public interface Communicator {
public void sendDataToActivity(String s);
}
public static final String TAG = SendFragment.class.getSimpleName();
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Communicator) {
communicator = (Communicator) context;
} else {
throw new IllegalArgumentException(
"Must implement " + TAG + ".Communicator on caller Activity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_send, container, false);
imgContact = (ImageView) view.findViewById(R.id.contactbook);
tvContactName = (TextView) view.findViewById(R.id.tvcontactname);
if(!TextUtils.isEmpty(username)) {
username = getArguments().getString("username").toString();
tvContactName.setText(username);
}
listeners();
return view;
}
private void listeners() {
imgContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
communicator.sendDataToActivity(Constants.selectUserName);
Intent intent = new Intent(getActivity(), AllContactsListActivity.class);
startActivity(intent);
}
});
}
}
Now the below is my Code of the activity..
public class AllContactsListActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SendFragment.Communicator,RecyclerViewAdapter.OnItemClick {
Context context;
RecyclerView recyclerView;
RecyclerView.Adapter recyclerViewAdapter;
RecyclerView.LayoutManager recylerViewLayoutManager;
ImageButton btnSliding_common;
DrawerLayout drawer;
NavigationView navigationView;
String sendFragmentStringFlag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_contacts_list);
setIds();
listeners();
}
private void listeners() {
recyclerViewAdapter = new RecyclerViewAdapter(AllContactsListActivity.this, subjects, emails, address,this);
recyclerView.setAdapter(recyclerViewAdapter);
RecyclerView.ItemDecoration itemDecoration =
new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
recyclerView.addItemDecoration(itemDecoration);
btnSliding_common.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawer.openDrawer(GravityCompat.END);
}
});
}
private void setIds() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
btnSliding_common = (ImageButton) findViewById(R.id.btnSliding_contact);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout_contact);
navigationView = (NavigationView) findViewById(R.id.nav_view_contact);
recylerViewLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(recylerViewLayoutManager);
}
#Override
public void sendDataToActivity(String sendMoneyflag) {
sendFragmentStringFlag=sendMoneyflag;
}
#Override
public void onClick(String username) {
if(!TextUtils.isEmpty(sendFragmentStringFlag)) {
if (sendFragmentStringFlag.equals(Constants.selectUserName)) {
Toast.makeText(this, "You clicked " + username, Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("username", username);
SendFragment sendFragment = new SendFragment();
sendFragment.setArguments(bundle);
finish();
}
}else{
Toast.makeText(this, "USER NAME" + username, Toast.LENGTH_SHORT).show();
}
}
}
The problem probably because the host activity didn't implement the Fragment interface.
You're trying to attach the interface with the following method:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
communicator = (Communicator) activity;
} catch (Exception e){}
}
But you didn't handle the Exception correctly. So, you don't know when the interface is set correctly. And you also override onAttach(Activity activity) which is now deprecated.
You need to change the code as following:
public static final String TAG = YourFragment.class.getSimpleName();
...
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Communicator) {
communicator = (Communicator) context;
} else {
throw new IllegalArgumentException(
"Must implement " + TAG + ".Communicator on caller Activity");
}
}
It will throw error if your host activity didn't implement the interface.
You also need to attach the fragment to your activity by using FragmentTransaction. Something like this:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SendFragment sendFragment = new SendFragment();
fragmentTransaction.add(R.id.fragment_container, sendFragment);
fragmentTransaction.commit();
Related
i have already got all things ready set-up my fragment communication, but my only problem is how can i make the recycler view itemVitem.setOnClickListener call the overridden interface method in the main activity so i can get that data and create an intent with to go to detail activity or update detail fragment for dual-pane layout, more explanation is provided with comments on code below.
MainActivity
public class MainActivity extends AppCompatActivity implements ListFragment.Listener {
// the method to be called when an item in recycler view is clicked
// so i can pass this data to DetailFragment
#Override
public void listener(String firstName, String lastName) {
DetailFragment detailFragment = new DetailFragment();
detailFragment.updateText(firstName, lastName);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
RecyclerViewAdapter
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvFirstName;
public TextView tvLastName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvFirstName = itemView.findViewById(R.id.row_first_name);
tvLastName = itemView.findViewById(R.id.row_last_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// how to call the "listener()" method in main activity
}
});
}
the fragment containing the recycler view
public class ListFragment extends Fragment {
private static final String TAG = "ListFragment";
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
// fragment communication interface
public interface Listener {
void listener(String firstName, String lastName);
}
private Listener listener;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
this.listener = (Listener) context;
} catch (ClassCastException e) {
Log.d(TAG, "onAttach: "+ e.getMessage());
}
}
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = getView().findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// some dummy data to fill the recycler view
ArrayList<User> users = new ArrayList<>();
users.add(new User("hiwa", "jalal"));
users.add(new User("mohammed", "abdullah"));
recyclerViewAdapter = new RecyclerViewAdapter(users, getActivity());
recyclerView.setAdapter(recyclerViewAdapter);
}
}
DetailFragment
public class DetailFragment extends Fragment {
private TextView tvFirstName;
private TextView tvLastName;
public DetailFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvFirstName = view.findViewById(R.id.detail_frag_first_name);
tvLastName = view.findViewById(R.id.detail_frag_last_name);
}
// update the details fragment views
public void updateText(String firstName, String lastName) {
tvFirstName.setText(firstName);
tvLastName.setText(lastName);
}
}
Pass listener to your RecyclerViewAdapter and use this to call the callback
recyclerViewAdapter = new RecyclerViewAdapter(users, getActivity(), listener);
Update RecyclerViewAdapter like below
class RecyclerViewAdapter {
private Listener mListener;
....
public RecyclerViewAdapter(ArrayList<User> users, Context context, Listener listener) {
....
mListener = listener;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
....
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.listener(first_name. last_name);
}
});
....
}
....
}
Create Method in adapter class.
private Listener mListener;
public void setListener(Listener listener){
mListener = listener
}
public void removeListener(){
mListener = null;
}
Inside Fragment class, set listener like below.
recyclerViewAdapter = new RecyclerViewAdapter(users, getActivity());
recyclerViewAdapter.setListener(listener);
In ViewHolder
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.listener(first_name. last_name);
}
});
Also in OnDestroy or OnDestroyView() of fragment, call
removeListener() to avoid memory leak.
I want to send the String data in LibraryFragment to LibrarySongFragment.
LibraryFragment :
public class LibraryFragment extends Fragment {
private FirebaseRecyclerAdapter mAdapter;
#Nullable
#Override
public New onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
...
mAdapter = new LibraryAdapter(options, context);
recyclerView.setAdapter(mAdapter);
}
}
LibraryAdapter :
public class LibraryAdapter extends FirebaseRecyclerAdapter<MyModel, LibraryAdapter.MyViewHolder> {
...
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = getItem(getAdapterPosition()).getTitle();
((FragmentActivity) context).getSupportFragmentManager().beginTransaction()
.addToBackStack(null).replace(R.id.library_coordinator, new LibrarySongFragment()).commit();
}
});
}
}
}
I want to send the title that in MyViewHolder in LibraryAdapter. You can see the "String title = getItem(getAdpaterPosition()).getTitle();". Just send to LibrarySongFragment and post it in fragment_song_library.xml TextView.
You need to just create bundle of your data and set arguments in fragment object. i have modified your code. please refer
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = getItem(getAdapterPosition()).getTitle();
FragmentManager fragmentManager = ((Activity)context).getSupportFragmentManager();
Fragment fragment;
LibrarySongFragment librarySongFragment = new LibrarySongFragment();
Bundle bundle = new Bundle();
bundle.putString("KeyTitle",title);
librarySongFragment.setArguments(bundle);
fragmentManager.beginTransaction()
.addToBackStack(null).replace(R.id.library_coordinator, librarySongFragment).commit();
}
});
}
}
create inteface
in fragment from where you are going to send the data
SendMessage SM;
public interface SendMessage{
void Senddata(String message,Boolean sent);
}
override this method to same fragment
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
implement this fragment to the activity which hold these fragment
public class Activity extends AppCompatActivity implements sendfragment.SendMessage
override the message to the activity
#Override
public void Senddata(String message,Boolean sent) {
fragtwo f = (fragtwo) getSupportFragmentManager().findFragmentByTag(tag);
if(sent==true){
Toast.makeText(this, "data transfered", Toast.LENGTH_SHORT).show();
f.displaydata(message);
}
}
Create public method for sent data
public void displaydata(String massage){
String massageformat="received data is "+massage;
}
this is way to communicate between fragments in android
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();
I am having trouble implementing view.OnClickListener in my RecyclerView.Adapter. I am trying to implement multi-pane layout (landscape tablet layout version with RecyclerView and detail side by side). I have so far created this Activity:
public class MovieListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MovieListFragment movieListFragment = new MovieListFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recycler_view_fragment, movieListFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
which starts a Fragment:
public class MovieListFragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MoviesAdapter(getContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movie_list, container, false);
ButterKnife.bind(this,view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onStart() {
super.onStart();
getPopularMovies();
}
private void getPopularMovies() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movie.MovieResult>() {
#Override
public void success(Movie.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) { error.printStackTrace(); }
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
which calls the RecyclerView.Adapter:
public class MoviesAdapter extends RecyclerView.Adapter<MovieViewHolder> {
private List<Movie> mMovieList;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context) {
this.mContext = context;
this.mInflater = LayoutInflater.from(context); //
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = mInflater.inflate(R.layout.movie_row_item, parent, false);
final MovieViewHolder viewHolder = new MovieViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = viewHolder.getAdapterPosition();
Intent intent = new Intent(mContext, MovieDetailActivity.class);
intent.putExtra(MovieDetailActivity.MOVIE_EXTRA, mMovieList.get(position));
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movie movie = mMovieList.get(position);
Picasso.with(mContext)
.load(movie.getPoster())
.placeholder(R.color.colorAccent)
.into(holder.thumbnail);
holder.movieTitle.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
}
#Override
public int getItemCount() {
return (mMovieList == null) ? 0 : mMovieList.size();
}
public void setMovieList(List<Movie> movieList) {
this.mMovieList = new ArrayList<>();
this.mMovieList.addAll(movieList);
notifyDataSetChanged();
}
}
Here in onClick I need to decide whether to start a new Activity (like in my code) or update content of detail Fragment (in my tablet landscape layout).
According to this link, you should decide based on fact if your DetailFragment is != null in activity like this:
public void onItemSelected(int position) {
DisplayFragment displayFrag = (DisplayFragment) getFragmentManager()
.findFragmentById(R.id.display_frag);
if (displayFrag == null) {
// DisplayFragment (Fragment B) is not in the layout (handset layout),
// so start DisplayActivity (Activity B)
// and pass it the info about the selected item
Intent intent = new Intent(this, DisplayActivity.class);
intent.putExtra("position", position);
startActivity(intent);
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
displayFrag.updateContent(position);
}
}
But I'm not able to check this in Adapter. Any help would be highly appreciated!
Thank you.
Created the custom interface click action to get the control in fragment class
i hope it will works for you
public class MoviesAdapter extends RecyclerView.Adapter {
MoviesAdapterCallback moviesAdapterCallback;
private List<Movie> mMovieList;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context,MoviesAdapterCallback moviesAdapterCallback) {
this.mContext = context;
this.moviesAdapterCallback =moviesAdapterCallback;
this.mInflater = LayoutInflater.from(context); //
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = mInflater.inflate(R.layout.movie_row_item, parent, false);
final MovieViewHolder viewHolder = new MovieViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* int position = viewHolder.getAdapterPosition();
Intent intent = new Intent(mContext, MovieDetailActivity.class);
intent.putExtra(MovieDetailActivity.MOVIE_EXTRA, mMovieList.get(position));
mContext.startActivity(intent);
*/ moviesAdapterCallback.MovieClicked(view);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movie movie = mMovieList.get(position);
Picasso.with(mContext)
.load(movie.getPoster())
.placeholder(R.color.colorAccent)
.into(holder.thumbnail);
holder.movieTitle.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
}
#Override
public int getItemCount() {
return (mMovieList == null) ? 0 : mMovieList.size();
}
public void setMovieList(List<Movie> movieList) {
this.mMovieList = new ArrayList<>();
this.mMovieList.addAll(movieList);
notifyDataSetChanged();
}
public interface MoviesAdapterCallback {
void MovieClicked(View view);
}
}
in Fragment Class
public class MovieListFragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movie_list, container, false);
ButterKnife.bind(this,view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAdapter = new MoviesAdapter(getContext(), new MoviesAdapter.MoviesAdapterCallback(){
#Override
public void MovieClicked(View view) {
DisplayFragment displayFrag = (DisplayFragment) getFragmentManager()
.findFragmentById(R.id.display_frag);
if (displayFrag == null) {
// DisplayFragment (Fragment B) is not in the layout (handset layout),
// so start DisplayActivity (Activity B)
// and pass it the info about the selected item
Intent intent = new Intent(this, DisplayActivity.class);
intent.putExtra("position", position);
startActivity(intent);
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
displayFrag.updateContent(position);
}
}
});
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onStart() {
super.onStart();
getPopularMovies();
}
private void getPopularMovies() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movie.MovieResult>() {
#Override
public void success(Movie.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) { error.printStackTrace(); }
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.
So:
I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.
I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.
The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.
My code:
MainPagerAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
case 1: return TasksFragment.newInstance();
default: return TaskGroupFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
TaskGroupActivity (sending fragment):
public class TaskGroupFragment extends ListFragment {
private DoItDataSource dataSource;
private List<TaskGroups> groups;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_group, container, false);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
JSONContainer jsonContainer = dataSource.sqliteToContainer();
dataSource.close();
groups = jsonContainer.getTask_groups();
TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
setListAdapter(adapter);
return view;
}
public static TaskGroupFragment newInstance() {
TaskGroupFragment tgf = new TaskGroupFragment();
return tgf;
}
public interface OnTaskGroupSelectedListener {
public void onTaskGroupSelected(String taskGroupId);
}
OnTaskGroupSelectedListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTaskGroupSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " Interface not implemented in activity");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity)getActivity()).setCurrentItem(1, true);
mListener.onTaskGroupSelected(groups.get(position).getId());
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
pager = (ViewPager) findViewById(R.id.activity_main_pager);
pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// getting lists
//
}
private void resultHandling(String json, String day) {
if (day.equals("today")) {
Gson gson = new Gson();
containerToday = gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerToday, "Today");
} else if (day.equals("tomorrow")) {
Gson gson = new Gson();
containerTomorrow= gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerTomorrow, "Tomorrow");
}
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// Enter missing link here?
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment
implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button)
view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
public static TasksFragment newInstance() {
TasksFragment tif = new TasksFragment();
return tif;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Solution
Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!
MainPageAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// ADDED
private String taskGroupId;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
// MODIFIED
case 1:
Bundle args = new Bundle();
logcat("before setBundle " + taskGroupId);
args.putString("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
default: return TaskGroupFragment.newInstance();
}
}
// ADDED
public void setTaskGroupId(String id){
this.taskGroupId = id;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
// ADDED
private MainPagerAdapter adapter;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
// ADDED
adapter = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.activity_main_pager);
// MODIFIED
pager.setAdapter(adapter);
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// Getting lists
//
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// ADDED
adapter.setTaskGroupId(taskGroupId);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
private String taskGroupId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
// ADDED
Bundle bundle = getArguments();
taskGroupId = bundle.getString("taskGroupId");
// MODIFIED
dataSource.open();
tasks = dataSource.getTasks(taskGroupId);
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
// CAN BE REMOVED?
//public static TasksFragment newInstance() {
// TasksFragment tif = new TasksFragment();
// return tif;
//}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Please note that I'm using taskGroupId as a String, not an int.
First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;
public void setTaskGroupId(int id){
this.taskGroupId = id;
}
}
then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment.
adapter.setCurrentItem(1); //going to TasksFragment page
}
then you need to put some argumants before starting your fragment.
#Override
public Fragment getItem(int i) {
//this code is only for case 1:
Bundle args = new Bundle();
args.putInt("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
}
and lastly use this data in your TaskFragment to show the right content.