Tablayout+viewpager in fragment, need to clear a edittext data in viewpager - android

I have developed a project with Tablayout with 3 viewpager items, getting data in edittext from each viewpager, I need to clear all the data from viewpager and set all us empty, when button click event occurs which was set in last viewpager item.
This is parent fragment, Homefragment.class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = inflater.inflate(R.layout.activity_main, container, false);
super.onCreate(savedInstanceState);
ButterKnife.bind(this, view);
ButterKnife.bind(this, view);
final ViewPager viewPager = ButterKnife.findById(view, R.id.viewpager2);
setupViewPager(viewPager);
TabLayout tabLayout = ButterKnife.findById(view, R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
next = ButterKnife.findById(view, R.id.nxt_btn);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
}
});
return view;
}
private void setupViewPager(final ViewPager viewPager) {
final ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new Customer_details(), "Customer Details");
adapter.addFragment(new Order_details(), "Order Details");
adapter.addFragment(new Payment_details(), "Payment Details");
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (viewPager.getCurrentItem() == 2) {
next.setVisibility(View.INVISIBLE);
} else if (viewPager.getCurrentItem() == 0) {
next.setVisibility(View.VISIBLE);
} else if (viewPager.getCurrentItem() == 1) {
next.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); ++i) {
View innerview = ((ViewGroup) view).getChildAt(i);
setupUI(innerview);
}
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
//unbinder.unbind();
}
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) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void onButtonPressed() {
startActivity(new Intent(null, MainActivity.class));
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
// handle back button
Intent i=new Intent(getActivity(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
getActivity().finish();
return true;
}
return false;
}
});
}
}
Customer.class
public class Customer_details extends Fragment {
public static int selectedid;
public static EditText cname, cnumber, cnumber2, caddress, cpincode, clandmark;
public static Spinner spinner, snum, snum1, sp1, sp2;
public static RadioGroup radioGroup;
public static RadioButton radioButton;
TextView ctype, name, contact1, contact2, dispatch, address, pincode, landmark, source;
private PayOrder_Interface pay;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return
final View view = inflater.inflate(R.layout.activity_cdetails, container, false);
cname = (EditText) view.findViewById(R.id.cname);
cnumber = (EditText) view.findViewById(R.id.cnumber1);
cnumber2 = (EditText) view.findViewById(R.id.cnumber2);
caddress = (EditText) view.findViewById(R.id.caddress);
cpincode = (EditText) view.findViewById(R.id.cpincode);
clandmark = (EditText) view.findViewById(R.id.clandmark);
String[] values = {"Select", "Retail", "Bulk"};
spinner = (Spinner) view.findViewById(R.id.spinner);
final String[] value = {"Select", "+91", "+64", "+355", "+213", "+214", "+54", "+374", "+43", "+994", "+1", "+973", "+880", "+32", "+1-(441)", "+591", "+387", "+267", "+55", "359", "+673"};
snum = (Spinner) view.findViewById(R.id.spinner3);
String[] val = {"Select", "+91", "+64", "+355", "+213", "+214", "+54", "+374", "+43", "+994", "+1", "+973", "+880", "+32", "+1-(441)", "+591", "+387", "+267", "+55", "359", "+673"};
snum1 = (Spinner) view.findViewById(R.id.spinner4);
String[] v = {"Select", "Online", "Existing", "Sales Team", "Store", "Zomato"};
sp1 = (Spinner) view.findViewById(R.id.spinner_2);
String[] b = {"Select", "GaarG Store 1", "PG Tech"};
sp2 = (Spinner) view.findViewById(R.id.spinner_bulk);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
switch (checkedId) {
case R.id.radioButton1:
// switch to fragment 1
break;
case R.id.radioButton2:
// Fragment 2
break;
}
selectedid = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) view.findViewById(selectedid);
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
ArrayAdapter<String> a = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, val);
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, value);
ArrayAdapter<String> adap = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, v);
ArrayAdapter<String> bulk = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, b);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
adapt.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
a.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
adap.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bulk.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
snum1.setAdapter(a);
snum.setAdapter(adapt);
sp1.setAdapter(adap);
sp2.setAdapter(bulk);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
// String txt=(String)spinner.getSelectedItem();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Object item = parentView.getItemAtPosition(position);
/* if(item!=null){
Toast.makeText(getContext(),item.toString() + "Selected",Toast.LENGTH_SHORT).show();
}*/
//EventBus.getDefault().post(value);
switch (parentView.getSelectedItemPosition()) {
case (0): {
sp2.setVisibility(View.GONE);
//Do Nothing
}
break;
case (1): {
contact1.setVisibility(View.VISIBLE);
contact2.setVisibility(View.VISIBLE);
dispatch.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
pincode.setVisibility(View.VISIBLE);
landmark.setVisibility(View.VISIBLE);
source.setVisibility(View.VISIBLE);
cname.setVisibility(View.VISIBLE);
cnumber.setVisibility(View.VISIBLE);
cnumber2.setVisibility(View.VISIBLE);
caddress.setVisibility(View.VISIBLE);
cpincode.setVisibility(View.VISIBLE);
ctype.setVisibility(View.VISIBLE);
clandmark.setVisibility(View.VISIBLE);
spinner.setVisibility(View.VISIBLE);
sp1.setVisibility(View.VISIBLE);
snum.setVisibility(View.VISIBLE);
snum1.setVisibility(View.VISIBLE);
sp2.setVisibility(View.GONE);
radioGroup.setVisibility(View.VISIBLE);
// radioButton_1.setVisibility(View.VISIBLE);
//radioButton_2.setVisibility(View.VISIBLE);
}
break;
case (2): {
contact1.setVisibility(View.GONE);
contact2.setVisibility(View.GONE);
dispatch.setVisibility(View.GONE);
address.setVisibility(View.GONE);
pincode.setVisibility(View.GONE);
landmark.setVisibility(View.GONE);
source.setVisibility(View.GONE);
cname.setVisibility(View.GONE);
cnumber.setVisibility(View.GONE);
cnumber2.setVisibility(View.GONE);
caddress.setVisibility(View.GONE);
cpincode.setVisibility(View.GONE);
clandmark.setVisibility(View.GONE);
ctype.setVisibility(View.VISIBLE);
spinner.setVisibility(View.VISIBLE);
snum.setVisibility(View.GONE);
snum1.setVisibility(View.GONE);
sp1.setVisibility(View.GONE);
sp2.setVisibility(View.VISIBLE);
radioGroup.setVisibility(View.GONE);
// radioButton_1.setVisibility(View.GONE);
// radioButton_2.setVisibility(View.GONE);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
public String getEditetxtValue() {
return cname.getText().toString();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
// handle back button
Intent a = new Intent(getActivity(), MainActivity.class);
startActivity(a);
getActivity().finish();
return true;
}
return false;
}
});
}
Order.class
public class Order_details extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private static final String[] FLAVOURS = new String[]{"Venilla", "Stawberry", "Chocalate", "Mango", "Pineapple"};
public static EditText edittext, edmessage;
public static Spinner spinner, sp, select;
public static AutoCompleteTextView textView;
DatePickerDialog.OnDateSetListener ondate = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
edittext.setText(String.valueOf(dayOfMonth) + "-" + String.valueOf(monthOfYear + 1)
+ "-" + String.valueOf(year));
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate (R.layout.activity_odetails, container, false);
edmessage = (EditText) view.findViewById(R.id.ed_cake);
String[] egg = {"Select", "Egg", "Eggless", "N/A"};
spinner = (Spinner) view.findViewById(R.id.spinner_e);
String[] weight = {"Select", "0.5kg", "1kg", "1.5kg", "2kg", "2.5kg", "3kg", "6kg", "5kg", "4kg", "4.5kg", "3.5kg", "7kg", "8kg,", "7.5kg", "10kg"};
sp = (Spinner) view.findViewById(R.id.spinner_wt);
String[] time = {"Select", "8Am- 9Am", "11.30pm-11.45pm", "9am-10am", "10am-11am", "11AM=12PM", "12PM-1PM", "1PM-2PM", "2PM-3PM", "3PM-4PM", "4PM-5PM", "5PM-6PM", "6PM-7PM", "7PM-8PM", "8PM-9PM"};
select = (Spinner) view.findViewById(R.id.spinner_t);
textView = (AutoCompleteTextView) view.findViewById(R.id.au_flavour);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, egg);
ArrayAdapter<String> p = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, weight);
ArrayAdapter<String> d = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, time);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
ArrayAdapter<String> au = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_dropdown_item_1line, FLAVOURS);
p.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
d.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
sp.setAdapter(p);
textView.setAdapter(au);
select.setAdapter(d);
getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_ADJUST_PAN);
return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
edittext = (EditText) view.findViewById(R.id.ed_date);
edittext.setInputType(InputType.TYPE_NULL);
edittext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker();
}
});
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(getActivity());
return false;
}
});
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); ++i) {
View innerview = ((ViewGroup) view).getChildAt(i);
setupUI(innerview);
}
}
}
private void showDatePicker() {
Bundle bundle=new Bundle();
Calendar calender = Calendar.getInstance();
Bundle args = new Bundle();
args.putInt("year", calender.get(Calendar.YEAR));
args.putInt("month", calender.get(Calendar.MONTH));
args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
date.setArguments(args);
date.setCallBack(ondate);
date.show(getFragmentManager(), "Date Picker");
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
return true;
}
return false;
}
});
}
Payment.class
public class Payment_details extends Fragment {
public static TextView payment, advance, balance, discount, extra, extra_amount, delivery;
public static EditText e_amount, e_advance, e_balance, e_discount, e_extra, e_extra_amount, e_delivery_charges, e_remark;
public static Spinner spinner;
Context context;
Button addextra, reset, save;
private LinearLayout laytype, layamount, laybalance, laydiscount, layexamt, laydelivery, layextra;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_payment_details, container, false);
e_amount = (EditText) view.findViewById(R.id.edtAmount);
e_advance = (EditText) view.findViewById(R.id.edtAdvance);
e_balance = (EditText) view.findViewById(R.id.edtBalance);
e_discount = (EditText) view.findViewById(R.id.e_discount);
e_extra = (EditText) view.findViewById(R.id.e_extra);
e_remark = (EditText) view.findViewById(R.id.e_remarks);
e_extra_amount = (EditText) view.findViewById(R.id.eextra_amount);
e_delivery_charges = (EditText) view.findViewById(R.id.e_delivery);
addextra = (Button) view.findViewById(R.id.add_extra);
reset = (Button) view.findViewById(R.id.btn_reset);
save = (Button) view.findViewById(R.id.save2);
String[] ptype = {"Select", "Cash", "EDC", "Online", "NEFT", "Cheque", "Not Paid"};
spinner = (Spinner) view.findViewById(R.id.spinner_pt);
laydiscount.setVisibility(View.GONE);
layextra.setVisibility(View.GONE);
layexamt.setVisibility(View.GONE);
laydelivery.setVisibility(View.GONE);
if (Customer_details.spinner.getSelectedItem().toString().equalsIgnoreCase("Bulk")) {
payment.setVisibility(View.GONE);
advance.setVisibility(View.GONE);
balance.setVisibility(View.GONE);
e_advance.setVisibility(View.GONE);
e_balance.setVisibility(View.GONE);
spinner.setVisibility(View.GONE);
}
textWatcher(e_advance);
textWatcher(e_discount);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, ptype);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
addextra.setOnClickListener(new View.OnClickListener() {
int click = 0;
//int i=0;
#Override
public void onClick(View v) {
// int count =++_clicks;
if (click == 0) {
click = 1;
laydiscount.setVisibility(View.VISIBLE);
layextra.setVisibility(View.VISIBLE);
layexamt.setVisibility(View.VISIBLE);
laydelivery.setVisibility(View.VISIBLE);
} else {
click = 0;
laydiscount.setVisibility(View.GONE);
layextra.setVisibility(View.GONE);
layexamt.setVisibility(View.GONE);
laydelivery.setVisibility(View.GONE);
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
clear();
Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
private void textWatcher(final EditText edit) {
edit.addTextChangedListener(new TextWatcher() {
int result,r=0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
result = 0;
//r=0;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int e = parse(e_amount) - parse(e_advance);
if (edit == e_discount && parse(e_discount) == 0) {
result = e;
}
else{
result = e - parse(e_discount);
}
}
#Override
public void afterTextChanged(Editable s) {
e_balance.setText(String.valueOf(result));
}
});
}
private int parse(EditText edt) {
String s = edt.getText().toString();
if (s.matches(""))s = "0";
return Integer.parseInt(s);
}
public void clear() {
Customer_details.spinner.setSelection(0);
Log.v(Customer_details.cname.getText().toString(), "name");
try {
Customer_details.cname.setText("");
Customer_details.snum.setSelection(0);
Customer_details.cnumber.setText("");
Customer_details.snum1.setSelection(0);
Customer_details.sp2.setSelection(0);
Customer_details.cnumber2.getText().clear();
Customer_details.caddress.getText().clear();
Customer_details.cpincode.getText().clear();
Customer_details.clandmark.getText().clear();
// Customer_details.radioButton.setChecked(false);
Customer_details.sp1.setSelection(0);
Customer_details.spinner.setSelection(0);
Customer_details.cnumber.setText("");
Order_details.spinner.setSelection(0);
Order_details.textView.setText("");
Order_details.sp.setSelection(0);
Order_details.edmessage.setText("");
Order_details.edittext.getText().clear();
Order_details.select.setSelection(0);
e_amount.setText("");
spinner.setSelection(0);
e_advance.setText("");
e_balance.setText("");
e_remark.setText("");
e_discount.setText("");
e_extra.setText("");
e_extra_amount.setText("");
e_delivery_charges.setText("");
spinner.setSelection(0);
e_amount.setText("");
e_advance.setText("");
e_balance.setText("");
e_remark.setText("");
} catch (Exception e) {
Log.i("MYLOG", "Message was not handled " + e.getMessage());
}
Toast.makeText(getActivity(), "Cleared ", Toast.LENGTH_SHORT).show();
}
}
I have tried to clear the items by this method,
edittext.setText(" ");
edittext.getText().clear();
Only Order and Payment class data alone get cleared Customer data couldn't cleared. How to fix my problem?

try to set this mViewPager.setOffscreenPageLimit(3); inside setUpViewPager() method
Upate
By default setOffscreenPageLimit() will be set to 1, that means youll have 2 fragment pages active at once. Since you need to clear the texts from EditText of all the three fragment pages, then setting setOffscreenPageLimit(3) (because you are using 3 fragments) will have all 3 fragment page active and helpful in making necessary changes in all of them. For more information see the Docs
void setOffscreenPageLimit (int limit)
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.

Related

items in listview not appear

I try to make items appear in my list view, when add new contact then add it to list view ,it's not appear when I add new contact.
here is main_fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
ImageView contactImage;
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) view.findViewById(R.id.txtName);
emailTxt = (EditText) view.findViewById(R.id.txtEmail);
phoneTxt = (EditText) view.findViewById(R.id.txtPhone);
addressTxt = (EditText) view.findViewById(R.id.txtAddress);
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
if (contactAdapter != null) contactAdapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
resetAddContactPanel();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
final Button addContact = (Button) view.findViewById(R.id.btnadd);
nametxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addContact.setEnabled(!nametxt.getText().toString().trim().equals(""));
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
ArrayAdapter<import_fragment.Contact> contactAdapter;
ListView contactListView;
DatabaseHandler dbHandler;
int longClickedItemIndex;
public void onActivityResult(int reqCode, int resCode, Intent data) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
ImageView contactImageImgView;
contactImageImgView = (ImageView) getActivity().findViewById(R.id.ivContactImage);
if (resCode == Activity.RESULT_OK) {
if (reqCode == 1) {
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
private void resetAddContactPanel() {
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) getActivity().findViewById(R.id.txtName);
emailTxt = (EditText) getActivity().findViewById(R.id.txtEmail);
phoneTxt = (EditText) getActivity().findViewById(R.id.txtPhone);
addressTxt = (EditText) getActivity().findViewById(R.id.txtAddress);
nametxt.setText("");
phoneTxt.setText("");
emailTxt.setText("");
addressTxt.setText("");
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
{
ImageView contactImageImgView;
contactImageImgView = (ImageView) view.findViewById(R.id.ivContactImage);
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
if (dbHandler.getContactsCount() != 0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Contact Options");
menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Contact");
menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Contact");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO: Implement editing a contact
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(import_fragment.Contact contact) {
String name = contact.getName();
int contactCount = Contacts.size();
for (int i = 0; i < contactCount; i++) {
if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
return true;
}
return false;
}
private void populateList() {
contactAdapter = new ContactListAdapter(getActivity());
contactListView.setAdapter(contactAdapter);
}
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
private class ContactListAdapter extends ArrayAdapter<import_fragment.Contact> {
public ContactListAdapter(Context cntx) {
super(cntx, R.layout.fragment_import, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.fragment_import, parent, false);
import_fragment.Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
return view;
}
}
Someone told me u must setAdapter in onCreateView and when I did that i get error Null so I removed it, if this will solve problem then please tell me how to setAdapter in onCreateView without getting null error.

Receive ArrayList from Custom Adapter

Ive got a Array List in my CustomAdapter filled with the id of my checked element.
elementChecker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (elementChecker.isChecked()) {
checkedElements.add(id);
} else {
for (int i = 0; i < checkedElements.size() ; i++){
checkedElements.remove(id);
}
}
}
});
But how do I get access to this list from my Fragment?Thanks for your help.
EDIT: This is my getter But I cant call it from my Fragment.
public List<String> getSelectedElements(){
return checkedElements;
}
The Adapter is set in my DataListFragment:
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
EDIT2: Added The Fragment Code
public class ListViewFragment extends Fragment {
DbHelper mydb;
Spinner locationpicker;
LinearLayout qrStickerLayout;
ImageView qrCodeSticker;
TextView labelSticker;
TextView serialSticker;
private EditText roomnr;
public boolean roomNrOk = false;
public boolean locationOk = false;
public boolean listViewOk = false;
String actualLocation;
String dataList = "";
String selectedFromList;
String[] selectedElementArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
getActivity().setTitle(getString(R.string.listView));
registerForContextMenu(view);
final Context context = getContext();
mydb = new DbHelper(context);
locationpicker = (Spinner) view.findViewById(R.id.spinner_locations);
roomnr = (EditText) view.findViewById(R.id.editText_roomNr);
qrCodeSticker = (ImageView) view.findViewById(R.id.imageView_qrcode);
labelSticker = (TextView) view.findViewById(R.id.textView_QrSticker_label);
serialSticker = (TextView) view.findViewById(R.id.textView_QrSticker_serial);
qrStickerLayout = (LinearLayout) view.findViewById(R.id.linearLayout_QrCode);
Drawable drawableForFabSave = getResources().getDrawable(R.drawable.ic_save);
((MainActivity) getActivity()).fabsave.setImageDrawable(drawableForFabSave);
Drawable drawableForFabAdd = getResources().getDrawable(R.drawable.ic_add);
((MainActivity) getActivity()).fabmain.setImageDrawable(drawableForFabAdd);
((MainActivity) getActivity()).fabmain.animate().translationY(0);
((MainActivity) getActivity()).fabmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).scanQRCode();
((MainActivity) getActivity()).loadListViewFragment();
}
});
((MainActivity) getActivity()).fabdelete.animate().translationY(0);
final String locationNamesFromTableArray = mydb.getLocationNames();
if(!locationNamesFromTableArray.isEmpty()){
String[] roomNumbersFromTableArrayFinal = locationNamesFromTableArray.split("\t");
ArrayAdapter<String> adapter_locations;
adapter_locations = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, roomNumbersFromTableArrayFinal);
locationpicker.setAdapter(adapter_locations);
setFabdeleteVisible(listViewOk);
}
locationpicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
actualLocation = locationpicker.getSelectedItem().toString();
locationOk = true;
setFabsVisible(roomNrOk, true, listViewOk);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
roomnr.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
Pattern p = Pattern.compile("^[0-9]{3}$");
Matcher m = p.matcher(s);
roomNrOk = m.find();
setFabsVisible(roomNrOk, locationOk, listViewOk);
}
});
dataList = mydb.getElementsWithoutRoom();
if (!dataList.isEmpty()) {
final String[] dataListArray = dataList.split("\n");
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
dataListListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedFromList = (dataListListView.getItemAtPosition(position).toString());
selectedElementArray = selectedFromList.split("\t");
dataListListView.showContextMenu();
}
});
((MainActivity) getActivity()).fabdelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mydb.deleteAllWithoutRoom();
listViewOk = false;
dataListListView.setAdapter(dataListAdapter);
Toast toast = Toast.makeText(context, getResources().getString(R.string.toast_deleted), Toast.LENGTH_SHORT);
toast.show();
reloadListViewFragment();
}
});
}else{
TextView emptyElement = (TextView) view.findViewById(R.id.emptyElement);
emptyElement.setVisibility(View.VISIBLE);
}
((MainActivity) getActivity()).fabsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (roomNrOk && locationOk && !dataList.isEmpty()) {
String successfullSaved = getResources().getString(R.string.successfully)+ actualLocation + "-" + roomnr.getText().toString() + getResources().getString(R.string.saved);
mydb.setRoomNr(roomnr.getText().toString());
mydb.setRoomId(roomnr.getText().toString());
mydb.setLocationId(actualLocation);
Toast toast = Toast.makeText(getActivity(), successfullSaved, Toast.LENGTH_SHORT);
toast.show();
reloadListViewFragment();
} else {
Toast toast = Toast.makeText(getActivity(), getString(R.string.error_listView), Toast.LENGTH_SHORT);
toast.show();
}
}
});
((MainActivity) getActivity()).fabexport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File myDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + getResources().getString(R.string.sdcard_path));
if (!myDir.exists()) {
myDir.mkdir();
}
String fileName = getResources().getString(R.string.roomname) + actualLocation + getResources().getString(R.string.underline) + roomnr.getText().toString() + getResources().getString(R.string.roomname_ending);
File file = new File(myDir, fileName);
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter fos = new OutputStreamWriter(fOut);
fos.write(dataList);
fos.close();
fOut.close();
Toast toast = Toast.makeText(getActivity(), fileName + getResources().getString(R.string.saved), Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
return view;
}
public void reloadListViewFragment(){
Fragment fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment = new ListViewFragment();
ft.replace(R.id.container, fragment);
ft.commitAllowingStateLoss();
}
}
OK. I got that, the issue is because the dataListAdapter is of type ListAdapter where you are initializing with CustomListAdapter. So, it gave you the error Cannot resolve method. To resolve this you can do it two ways:-
You can change this line
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
to
final CustomListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
While accessing the getSelectedElements(), write like this
((CustomListAdapter)dataListAdapter).getSelectedElements();
Please check with the current answer and let me know for further.

Set checkBox in CustomAdapter Visible by clicking on ListView Element in Fragment

is it possible to call a method in my CustomAdapter to set a checkbox Visible/Gone by clicking on an Element on my Fragments Listview? Ive got those two methods:
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
But How do I access them from my Fragment? Or do I have do chose another way?
(I want to set the checkbox visible by after "long click" on one of the ListView Elements)
Fragment:
public class ListViewFragment extends Fragment {
[...]
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
getActivity().setTitle(getString(R.string.listView));
registerForContextMenu(view);
final Context context = getContext();
mydb = new DbHelper(context);
locationpicker = (Spinner) view.findViewById(R.id.spinner_locations);
roomnr = (EditText) view.findViewById(R.id.editText_roomNr);
Drawable drawableForFabAdd = getResources().getDrawable(R.drawable.ic_add);
((MainActivity) getActivity()).fabmain.setImageDrawable(drawableForFabAdd);
((MainActivity) getActivity()).fabmain.animate().translationY(0);
((MainActivity) getActivity()).fabmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).scanQRCode();
((MainActivity) getActivity()).loadListViewFragment();
}
});
((MainActivity) getActivity()).fabdelete.animate().translationY(0);
final String locationNamesFromTableArray = mydb.getLocationNames();
if(!locationNamesFromTableArray.isEmpty()){
String[] roomNumbersFromTableArrayFinal = locationNamesFromTableArray.split("\t");
ArrayAdapter<String> adapter_locations;
adapter_locations = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, roomNumbersFromTableArrayFinal);
locationpicker.setAdapter(adapter_locations);
setFabdeleteVisible(listViewOk);
}
locationpicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
actualLocation = locationpicker.getSelectedItem().toString();
locationOk = true;
setFabsVisible(roomNrOk, true, listViewOk);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
roomnr.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
Pattern p = Pattern.compile("^[0-9]{3}$");
Matcher m = p.matcher(s);
roomNrOk = m.find();
setFabsVisible(roomNrOk, locationOk, listViewOk);
}
});
dataList = mydb.getElementsWithoutRoom();
if (!dataList.isEmpty()) {
final String[] dataListArray = dataList.split("\n");
Log.d("DATALIST", dataListArray[0]);
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
dataListListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
((MainActivity) getActivity()).fabmain.animate().translationY(300);
}
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
((MainActivity) getActivity()).fabmain.animate().translationY(0);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
listViewOk = true;
setFabsVisible(roomNrOk, locationOk, true);
setFabdeleteVisible(listViewOk);
dataListListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedFromList = (dataListListView.getItemAtPosition(position).toString());
selectedElementArray = selectedFromList.split("\t");
dataListListView.showContextMenu();
}
});
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
(CustomListAdapter).setCheckBoxSelectItemVisible();
return true;
}
});
[...]
return view;
}
public void reloadListViewFragment(){
Fragment fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment = new ListViewFragment();
ft.replace(R.id.container, fragment);
ft.commitAllowingStateLoss();
}
[...]
}
CustomAdapter:
class CustomListAdapter extends ArrayAdapter<String> {
String doubleTab = "\t\t";
CheckBox checkBoxSelectItem;
public CustomListAdapter(Context context, String[] dataListFinal) {
super(context, R.layout.list_item_datalist ,dataListFinal);
}
public String allElementsAdapter = "";
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
return customView;
}
public String getAllElements(){
return allElementsAdapter;
}
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
}
first change your Custom Adapter constructor with following
ArrayList<Boolean> mIsVisible;
public CustomListAdapter(Context context, String[] dataListFinal,ArrayList<Boolean> isVisible) {
super(context, R.layout.list_item_datalist ,dataListFinal);
mIsVisible = isVisible;
}
then modify getView()
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
if(mIsVisible.get(position)){
checkBoxSelectItem.setVisibility(View.VISIBLE);
}else{
checkBoxSelectItem.setVisibility(View.GONE);
}
return customView;
}
After that modify your activity CustomAdapter creation part
final ArrayList<Boolean> isVisible=new ArrayList<Boolean>();
for(int count =0 ;count<dataListArray.length; count++){
isVisible.add(false);
}
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray, isVisible);
And last modify listener part
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(isVisible.get(position))
isVisible.set(position,false);
else
isVisible.set(position,true);
dataListAdapter.notifyDataSetChanged();
return true;
}
});
Done...!!!!!
It works with ((BaseAdapter)dataListAdapter).notifyDataSetChanged();

getting value from two spinner into string variables

I'm trying to pass the strings "año" and "artista" from two spinners to the next activity and I get the value "año" but "artista" is always void. I used this method to get the values in other activity and there it works but here, "artista" is always void. Moreover, I have tried with switch method and without success.
I hope someone helps me and tells me what I'm doing wrong. I read and look for information before ask for help,
This is my code,
public class Buscar extends Activity implements OnItemSelectedListener{
String año;
String artista;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buscar);
Buscar();
Spinner spinnerBuscarAño = (Spinner) findViewById(R.id.añoSpinner);
String[] añoBuscar = {"1995", "2000", "2005"};
spinnerBuscarAño.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, añoBuscar));
spinnerBuscarAño.setOnItemSelectedListener(this);
Spinner spinnerBuscarArtista = (Spinner) findViewById(R.id.artistaSpinner);
String[] artistaBuscar = {"Michael Jackson", "U2", "Depeche Mode"};
spinnerBuscarArtista.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, artistaBuscar));
spinnerBuscarArtista.setOnItemSelectedListener(this);
}
/*
public void onItemSelected(AdapterView<?> parent, View view,int pos, long id) {
switch (parent.getId()) {
case R.id.añoSpinner:
año = parent.getItemAtPosition(pos).toString();
break;
case R.id.artistaSpinner:
artista = parent.getItemAtPosition(pos).toString();
break;
default:
break;
}
}
*/
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id){
// TODO Auto-generated method stub
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.añoSpinner)
{
año = parent.getItemAtPosition(position).toString();
}
else if(spinner.getId() == R.id.artistaSpinner)
{
artista = parent.getItemAtPosition(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void Buscar() {
Button buttonBuscar = (Button) findViewById(R.id.buscar);
buttonBuscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),artista, Toast.LENGTH_SHORT).show();
Intent intentBuscar = new Intent(Buscar.this, ListadoMusica.class);
intentBuscar.putExtra("myaño", año);
intentBuscar.putExtra("myartista", artista);
startActivity(intentBuscar);
}
});
}
}
If someone can help me,
Thanks in advance,
Possibly you are trying to catch a string of intent with another name.
Try this code:
SpinnerTest.java
public class SpinnerTest extends Activity implements AdapterView.OnItemSelectedListener {
String year;
String artist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_activity);
Spinner spinnerYear = (Spinner) findViewById(R.id.spinner1);
final String[] years = {"1995", "2000", "2005"};
spinnerYear.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, years));
spinnerYear.setOnItemSelectedListener(this);
Spinner spinnerArtists = (Spinner) findViewById(R.id.spinner2);
final String[] artists = {"Michael Jackson", "U2", "Depeche Mode"};
spinnerArtists.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, artists));
spinnerArtists.setOnItemSelectedListener(this);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent searchIntent = new Intent(SpinnerTest.this, SearchActivity.class);
searchIntent.putExtra("year", year);
searchIntent.putExtra("artist", artist);
startActivity(searchIntent);
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()){
case R.id.spinner1:
year = adapterView.getSelectedItem().toString();
Toast.makeText(SpinnerTest.this, year, Toast.LENGTH_LONG).show();
break;
case R.id.spinner2:
artist = adapterView.getSelectedItem().toString();
Toast.makeText(SpinnerTest.this, artist, Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
SearchActivity.java:
public class SearchActivity extends ActionBarActivity {
String year;
String artist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_spinner_value);
TextView txtYear = (TextView) findViewById(R.id.txtYear);
TextView txtArtist = (TextView) findViewById(R.id.txtArtist);
if(getIntent().hasExtra("year")){
year = getIntent().getStringExtra("year");
txtYear.setText(year);
}
if(getIntent().hasExtra("artist")){
artist = getIntent().getStringExtra("artist");
txtArtist.setText(artist);
}
}
}
It works for me

pass data from fragment inside view pager to another activity

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

Categories

Resources