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")
}
Related
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.
I have 2 fragments, one contains List class and other is Favorites class That shares List from List.
How can i open correct Activity from Favorites fragment
Favorite class
public class FavoriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
ListView favoriteList;
SharedPreference sharedPreference;
List<Station> favorites;
Activity activity;
ListAdapter listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_station_list, container,
false);
// Get favorite items from SharedPreferences.
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(activity);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
favoriteList = (ListView) view.findViewById(R.id.list_product);
if (favorites != null) {
listAdapter = new ListAdapter(activity, favorites);
favoriteList.setAdapter(listAdapter);
favoriteList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,int position, long arg3) {
Intent i;
switch (position)
{
case 0:
i = new Intent(getActivity(), Citizen.class);
startActivity(i);
break;
case 1:
i = new Intent(getActivity(), Ntv.class);
startActivity(i);
break;
}
}
});
favoriteList
.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity,
favorites.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_fill);
} else {
sharedPreference.removeFavorite(activity,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.star_blank);
listAdapter.remove(favorites
.get(position));
Toast.makeText(
activity,
activity.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
return view;
}
public void showAlert(String title, String message) {
if (activity != null && !activity.isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(activity)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void onResume() {
getActivity().setTitle(R.string.favorites);
getActivity().getActionBar().setTitle(R.string.favorites);
super.onResume();
}
}
List class
public class ListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "product_list";
Activity activity;
ListView stationListView;
List<Station> stations;
ListAdapter listAdapter;
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_station_list, container,
false);
findViewsById(view);
setStations();
listAdapter = new ListAdapter(activity, stations);
stationListView.setAdapter(listAdapter);
stationListView.setOnItemClickListener(this);
stationListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
stationListView = (ListView) view.findViewById(R.id.list_product);
}
private void setStations() {
Station station1 = new Station(1, R.drawable.ic_launcher, "Ntv", "Programme",1);
Station station2 = new Station(2, R.drawable.albania_tave, "Ntv", "Programme",2);
Station station3 = new Station(3, R.drawable.albania_tave,"Kiss tv", "Programme",3);
Station station4 = new Station(4, R.drawable.albania_tave, "Ntv", "Programme",4);
Station station5 = new Station(5, R.drawable.ic_launcher, "Ntv", "Citizen",5);
Station station6 = new Station(6, R.drawable.ic_launcher, "Citizen", "Citizen",6);
Station station7 = new Station(7, R.drawable.ic_launcher, "Ntv", "Programme",7);
Station station8 = new Station(8,R.drawable.ic_launcher, "Ntv", "Programme",8);
Station station9 = new Station(9,R.drawable.ic_launcher, "Ntv", "Programme",9);
Station station10 = new Station(10,R.drawable.ic_launcher,"Ntv", "Programme",10);
stations = new ArrayList<Station>();
stations.add(station1);
stations.add(station2);
stations.add(station3);
stations.add(station4);
stations.add(station5);
stations.add(station6);
stations.add(station7);
stations.add(station8);
stations.add(station9);
stations.add(station10);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i;
switch (position)
{
case 0:
i = new Intent(getActivity(), Citizen.class);
startActivity(i);
break;
case 1:
i = new Intent(getActivity(), Ntv.class);
startActivity(i);
break;
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, stations.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_fill);
} else {
sharedPreference.removeFavorite(activity, stations.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.star_blank);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
I would like to pass the selected item "id" from listview to popupMenu , the mainActivity:
public class ListChildrenActivity extends AppCompatActivity implements Config, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "ListChildrenActivity";
ProgressDialog progressDialog;
Toolbar toolbar;
ChildrenAdapter adapter;
ListView listView;
int idConnexion, id;
private SwipeRefreshLayout refreshLayout;
Intent intent;
Child childObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_child);
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Listes des enfants");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), MainMedecinActivity.class);
startActivity(intent);
}
});
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
showChildren();
}
});
showChildren();
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View view, int itemInt, long lng) {
//String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
//Toast.makeText(ListChildrenActivity.this, selectedFromList, Toast.LENGTH_SHORT).show();
//TextView v = (TextView)view.findViewById(R.id.tv);
//String itemId = v.getText().toString();
childObj = (Child) listView.getItemAtPosition(itemInt);
id = childObj.getIdEnfant();
Toast.makeText(ListChildrenActivity.this, ""+id, Toast.LENGTH_SHORT).show();
}
});
}
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
}
private ArrayList<Child> generateData(String content) {
ArrayList<Child> children = new ArrayList<Child>();
JSONObject jObj = null;
JSONArray ja = null;
try {
ja = new JSONArray(content);
for (int i = 0; i < ja.length(); i++) {
jObj = ja.getJSONObject(i);
children.add(new Child(jObj.getInt("idEnfant"), jObj.getString("nomEnfant"), jObj.getString("prenomEnfant")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return children;
}
public void showChildren() {
if (!validate()) {
failed();
return;
}
SharedPreferences prefs = getSharedPreferences("Info_Connexion", Context.MODE_PRIVATE);
idConnexion = prefs.getInt("idConnexion", 0);
progressDialog = new ProgressDialog(ListChildrenActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("La liste des enfants ...");
progressDialog.show();
if (isOnline()) {
requestData(SERVER_URL + "enfant/read/", idConnexion);
} else {
Toast.makeText(ListChildrenActivity.this, "Eroor network", Toast.LENGTH_SHORT).show();
}
}
private void requestData(String url, int id) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
RequestPackage p = new RequestPackage();
p.setMethod("POST");
p.setUri(url);
p.setParam("idMedecin", String.valueOf(id));
MessagesTask task = new MessagesTask();
task.execute(p);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public void success(final int id, final ProgressDialog progressDialog, String content, SwipeRefreshLayout refreshLayout) {
// 1. pass context and data to the custom adapter
adapter = new ChildrenAdapter(this, generateData(content));
// 2. Get ListView from activity_main.xml
// 3. setListAdapter
listView.setAdapter(adapter);
if (id != 0) {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
} else {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
Toast.makeText(ListChildrenActivity.this, "Eroor server or input", Toast.LENGTH_SHORT).show();
}
}
public boolean validate() {
boolean valid = true;
return valid;
}
public void failed() {
Toast.makeText(getBaseContext(), "List Children failed", Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
TextView scoreView = (TextView) findViewById(R.id.score);
switch (item.getItemId()) {
case R.id.infos:
intent = new Intent(getBaseContext(), ChildInformationsActivity.class);
intent.putExtra("idEnfant", id );
startActivity(intent);
return true;
case R.id.signes_diagnostic:
intent = new Intent(getBaseContext(), ChildSignesDiagnosticActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.bilan_bio:
intent = new Intent(getBaseContext(), ChildBilanBioActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.traitement_medical:
intent = new Intent(getBaseContext(), ChildTraitementMedicalActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.imagerie:
intent = new Intent(getBaseContext(), ChildImagerieActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
default:
return false;
}
}
private class MessagesTask extends AsyncTask<RequestPackage, String, String> {
#Override
protected String doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return content;
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
#Override
protected void onPostExecute(String content) {
Log.i(TAG, "------------------------" + content);
success(idConnexion, progressDialog, content, refreshLayout);
}
}
}
enter image description here
class adapter:
public class ChildrenAdapter extends ArrayAdapter<Child> {
private final Context context;
private final ArrayList<Child> childrenArrayList;
public ChildrenAdapter(Context context, ArrayList<Child> childrenArrayList) {
super(context, R.layout.row_child, childrenArrayList);
this.context = context;
this.childrenArrayList = childrenArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowChildView = inflater.inflate(R.layout.row_child, parent, false);
// 3. Get the two text view from the rowView
TextView nameView = (TextView) rowChildView.findViewById(R.id.name);
TextView dateView = (TextView) rowChildView.findViewById(R.id.date);
TextView scoreView = (TextView) rowChildView.findViewById(R.id.score);
// 4. Set the text for textView
//String text = childrenArrayList.get(position).getNomEnfant())+" "+childrenArrayList.get(position).getNomEnfant();
nameView.setText(childrenArrayList.get(position).getNomEnfant()+" "+childrenArrayList.get(position).getPrenomEnfant());
dateView.setText("22/12/2012");
scoreView.setText(String.valueOf(childrenArrayList.get(position).getIdEnfant()));
scoreView.setBackgroundResource(R.drawable.circular_textview);
// 5. retrn rowView
return rowChildView;
}
}
Whene i click to the row of listview i get the "id" but how i can pass it to the popupMenu.
The solution: it just add settag(position) to imageview in getview, then :
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
listView.performItemClick(v, (Integer) v.getTag(),listView.getItemIdAtPosition((Integer) v.getTag()));
}
You can use interface to communicate between them
In your adapter class, initialize
private OnItemSelectedListener mListener;
and add these methods
public void setOnItemClickLister(OnItemSelectedListener mListener) {
this.mListener = mListener;
}
//Creating an interface
public interface OnItemSelectedListener {
public void onItemSelected(String s);
}
in onClick function in adapter
use this
mListener.onItemSelected(id);
//id is your string
you can call it in MainActivity,
adapter.setOnItemClickLister(new OnItemSelectedListener() {
#Override
public void onItemSelected(String s) {
//you will get the string here, you can pass it as an argument in popup menu
}
});
On the adapter Side:
view.findViewById(R.id.menu_btn).setTag(id);
On the ListActivity Side:
public void showPopUp(View v){
currentId = v.getTag().toString();
PopupMenu popupMenu=new PopupMenu(this,v);
popupMenu.setOnMenuItemClickListener(ListActivity.this);
MenuInflater inflater=popupMenu.getMenuInflater();
inflater.inflate(R.menu.my_pop_up,popupMenu.getMenu());
popupMenu.show();
}
On XML side:
<ImageButton android:id="#+id/menu_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_overflow"
android:layout_marginStart="10dp"
android:layout_marginEnd="20dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:onClick="showPopUp"/>
Note: onClick="showPopUp" is very critical here.
This should be helpful. Thank you.
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.
I have and android app that works on android 4.0 great, but it crashes on android 4.3 and 4.4. I get this from the logCat
01-11 14:40:27.669: E/ACRA(25835): ACRA caught a IllegalStateException exception for quran. Building report.
01-11 14:40:27.789: E/AndroidRuntime(25835): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131099688, class android.widget.ListView) with Adapter(class quran.functions.PlaylistAdapter)]
Here is my code:
public class Playlist extends FragmentActivity {
private ListView list;
private Button manager, downloadAll;
private TextView reciter;
public static PlaylistAdapter adapter;
private ArrayList<Songs> songs;
private int RECITER_ID;
private String url, title, label;
private SlidingMenu slidingMenu;
private DatabaseHelper db;
private ImageView nowPlaying, back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
initWidgets();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
intent.putExtra("songs", songs);
if (getIntent().getIntExtra("duaa", -1) == 115)
intent.putExtra("lang", 115);
intent.putExtra("position", position);
intent.putExtra("fromClass", this.getClass() + "");
// intent.putExtra("mp3link", mp3link);
startActivity(intent);
}
});
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
XmlMapParser m = new XmlMapParser(Playlist.this, RECITER_ID);
HashMap<String, ArrayList<String>> map = m.convert();
map.keySet();
label = map.get("RecitorLabel").get(0);
title = map.get("Title").get(0);
url = map.get("Link").get(0);
back = (ImageView) findViewById(R.id.playlist_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
db.openDB();
for (int i = 1; i < map.get("Link").size(); i++) {
if (db.isDownloaded(i, title, RECITER_ID)) {
songs.add(new Songs(i, map.get("Title").get(i),
Environment.getExternalStorageDirectory()
.getPath()
+ "/"
+ getString(R.string.app_name)
+ "/"
+ title
+ "/"
+ map.get("Title").get(i)
+ ".mp3", title, true, RECITER_ID,
false));
} else
songs.add(new Songs(i, map.get("Title").get(i), url
+ label + "/"
+ new DecimalFormat("000").format(i) + ".mp3",
title, false, RECITER_ID, false));
}
db.closeDB();
// Log.v("--",m.convert().get("Link").get(1));
// [RecitorLabel, Title, Link] THIS ARE THE KEYS m
// Log.v("--", map.get("RecitorLabel").get(0));
// Log.v("--", map.get("Link").get(1));
return null;
}
protected void onPostExecute(Void result) {
adapter = new PlaylistAdapter(Playlist.this, songs);
list.setAdapter(adapter);
reciter.setText(songs.get(0).getRecitorName());
};
}.execute();
}
#Override
public void onBackPressed() {
if (slidingMenu.isMenuShowing()) {
slidingMenu.toggle();
} else {
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
try {
if (Tplayer.getInstance().isPlaying()) {
adapter = new PlaylistAdapter(this, songs);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
this.slidingMenu.toggle();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.slidingMenu.toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initWidgets() {
db = new DatabaseHelper(this);
manager = (Button) findViewById(R.id.playlist_download_manager);
manager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Playlist.this, DownloadManager.class);
startActivity(intent);
}
});
reciter = (TextView) findViewById(R.id.playlist_reciter_name_top);
list = (ListView) findViewById(R.id.playlist_list);
downloadAll = (Button) findViewById(R.id.playlist_download_all);
manager = (Button) findViewById(R.id.playlist_download_manager);
songs = new ArrayList<Songs>();
RECITER_ID = getIntent().getIntExtra("filename", -1);
// downloadAll.setOnClickListener(new OnClickListener() {
//
// #Override
// public void onClick(View v) {
// new DownloadAll(Playlist.this, songs);
// db.openDB();
// for (int i = 0; i < songs.size(); i++) {
// db.addDownloaded(songs.get(i).getNumber(), songs.get(i)
// .getLink(), 0, songs.get(i).getRecitorID(), "",
// songs.get(i).getTitle());
// }
// db.closeDB();
// }
// });
nowPlaying = (ImageView) findViewById(R.id.playlist_now_playing);
nowPlaying.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Tplayer tplayer = Tplayer.getInstance();
if (tplayer.isPlaying()) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
if (tplayer.isPlaying())
intent.putExtra("songs", tplayer.getSongs());
else
intent.putExtra("songs", songs);
if (tplayer.getSongs().size() == 14)
intent.putExtra("lang", 115);
intent.putExtra("position", tplayer.getPosition());
startActivity(intent);
}
}
});
// Jeremy Feinstein slidinglistadapter line 94
slidingMenu = new SlidingMenu(this);
slidingMenu.setMode(SlidingMenu.LEFT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowWidthRes(R.dimen.slidingmenu_shadow_width);
slidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow);
slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
slidingMenu.setFadeDegree(0.35f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
slidingMenu.setMenu(R.layout.slidingmenu);
}
}
and my playlist adapter class:
public class PlaylistAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
private ArrayList<Songs> data;
private DatabaseHelper db;
private SharedPreferences prefs;
int playpos;
int recitorID;
public PlaylistAdapter(Activity a, ArrayList<Songs> songs) {
activity = a;
data = songs;
db = new DatabaseHelper(a);
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
prefs = activity.getSharedPreferences("quantic.Quran",
Context.MODE_PRIVATE);
recitorID = prefs.getInt("recID", -1);
playpos = prefs.getInt("posPlaying", -1);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
final ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.song_item, parent, false);
ImageView download = (ImageView) vi
.findViewById(R.id.playlist_item_download);
db.openDB();
if (db.isDownloaded(data.get(position).getNumber(), data.get(position)
.getRecitorName(), data.get(position).getRecitorID()))
download.setImageResource(R.drawable.download_yes);
else {
download.setImageResource(R.drawable.download_no);
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DownloadFileFromURL(activity, data.get(position)
.getRecitorName(), data.get(position).getTitle(),
data.get(position).getLink(), data.get(position)
.getNumber(), data.get(position)
.getRecitorID()).execute();
if (!db.isDBOpen())
db.openDB();
db.addDownloaded(data.get(position).getNumber(),
data.get(position).getLink(), 0, data.get(position)
.getRecitorID(), "", data.get(position)
.getTitle());
Toast.makeText(activity,
"Downloading " + data.get(position).getTitle(),
Toast.LENGTH_SHORT).show();
}
});
}
db.closeDB();
TextView number = (TextView) vi.findViewById(R.id.playlist_item_num);
TextView reciterName = (TextView) vi
.findViewById(R.id.playlist_item_reciterName);
reciterName.setText(data.get(position).getRecitorName());
if (activity.getClass() == Playlist.class) {
reciterName.setVisibility(View.GONE);
}
TextView title = (TextView) vi.findViewById(R.id.playlist_item_reciter);
title.setText(data.get(position).getTitle());
number.setText((position + 1) + "");
ImageView eq = (ImageView) vi.findViewById(R.id.playlist_item_equlizer);
if (Tplayer.getInstance().isPlaying())
if (Tplayer.getInstance().getPosition() == position
&& data.get(position).getRecitorID() == Tplayer
.getInstance().getSong().getRecitorID()) {
eq.setVisibility(View.VISIBLE);
Ion.with(eq).load("http://darkodev.info/quran/dots.gif");
} else {
eq.setVisibility(View.GONE);
}
return vi;
}
}
Very old question, but no answer. I'm sure you have found a fix by now, but anyway.
You're changing the songs list object in background, and if Android decides to redraw your list (user scrolls your list), effectively accessing the songs list object, it may have changed and cause this exception to be thrown.
You need to use a temporary songs list and create a new adapter with it to update your list, thus not changing the current adapter list until you set a new adapter from the main UI thread.