I have an activity with multiple EditText, after entered data and click button SAVE for save them in Database(Mysql) it open Fragment which have ListView populated with this data from database.
PROBLEM:
ListView isn't showing new data that I have entered in activity!!!, even the new data is added im my ArrayList correctly.
But when I start this Fragment for the second time it shows the Listview with new data correctly.
My Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_liste_symbole_monetaire, container, false);
symbolMonList.clear();
lv = (SwipeMenuListView) rootView.findViewById(R.id.lv_liste_symboleMon);
adapter = new SymbMoneLvAdapter(getActivity());
FloatingActionButton btn = (FloatingActionButton) rootView.findViewById(R.id.btnAjoutAjoutSymboleMon);
btn.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(), AjouterSymbMoneActivity.class);
startActivity(intent);
}
});
deleteItemLv();
getListSymbolMon();
return rootView;
}
public void deleteItemLv(){
SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.GRAY));
// set item width
openItem.setWidth(dp2px(90));
// set item title
openItem.setTitle("Ouvrir");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getActivity());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
deleteItem.setWidth(dp2px(90));
// set a icon
deleteItem.setIcon(R.drawable.ic_delete);
// add to menu
menu.addMenuItem(deleteItem);
}
};
lv.setMenuCreator(creator);
lv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
//Ouvrir item
break;
case 1:
deleteItemDialog(position);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
}
public int dp2px(int dp) {
DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
//Dialog delete item:
public void deleteItemDialog(final int position){
Toast toast = Toast.makeText(getActivity(), "size:"+position, Toast.LENGTH_LONG);
toast.show();
Toast toat = Toast.makeText(getActivity(), "sizeTotal:"+symbolMonList.size(), Toast.LENGTH_LONG);
toat.show();
Toast oast = Toast.makeText(getActivity(), "code:"+symbolMonList.get(position).getCode(), Toast.LENGTH_LONG);
oast.show();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity() );
alertDialogBuilder.setTitle("Supprimer");
alertDialogBuilder.setMessage("Voulez vous supprimer ce symbole monétaire?");
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Code = symbolMonList.get(position).getCode();
Call<Void> api =API.deleteSymboleMon("delete", Code);
api.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if(response.isSuccessful()){
Toast toast = Toast.makeText(getActivity(), "Symbole Monétaire supprimé", Toast.LENGTH_LONG);
toast.show();
symbolMonList.remove(position);
adapter.notifyDataSetChanged();
}else {
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
}
}
)
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
//Get liste des SM
private void getListSymbolMon(){
final ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage("Chargement en cours...");
Call<List<SymbMoneItems>> api =API.getListSymbolMon();
api.enqueue(new Callback<List<SymbMoneItems>>() {
#Override
public void onResponse(Call<List<SymbMoneItems>> call, Response<List<SymbMoneItems>> response) {
if (response.isSuccessful()){
List<SymbMoneItems> List = response.body();
addListSymbolMon(List);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}else{
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
Toast toast = Toast.makeText(getActivity(), "Erreur", Toast.LENGTH_LONG);
toast.show();
}
}
#Override
public void onFailure(Call<List<SymbMoneItems>> call, Throwable t) {
Toast toast = Toast.makeText(getActivity(), "Erreur "+t, Toast.LENGTH_LONG);
toast.show();
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
});
}
public void addListSymbolMon(List<SymbMoneItems> lem){
for (int i=0;i< lem.size();i ++){
SymbMoneItems fac = lem.get(i);
symbolMonList.add(fac);
}
adapter.addAll(symbolMonList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
in my Adapter
public void addAll(ArrayList<SymbMoneItems> result) {
this.listSymb = result;
this.notifyDataSetChanged();
}
Thanks for any help.
Setting data using "=" doesn't actually have any change on dataset for adapter.
Change your addAll() method like below:
public void addAll(ArrayList<SymbMoneItems> result) {
this.listSymb.clear();
this.listSymb.addAll(result);
this.notifyDataSetChanged();
}
Related
I have developed a show dialog alert box in a fragment. After pressing the OK button in the box, It does not exits the screen. The show dialog alert keeps prompting on the screen. I don't want to quit the app after pressing OK, but I want it to go back to the HomeScreen. How to make sure that show dialog alert box will exit the screen after pressing OK?
Here is the code
public class FavouriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
private SharedPreference sharedPreference;
private StaggeredGridView mStaggeredView;
TextView tv;
ImageView iv;
String text;
String favouriteUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_favourite_staggeredgridview, container, false);
mStaggeredView = (StaggeredGridView) rootView.findViewById(R.id.staggeredview);
mStaggeredView.setOnScrollListener(scrollListener);
sharedPreference = new SharedPreference();
// iv=(ImageView)rootView.findViewById(R.id.imageView);
text = sharedPreference.getValue(getActivity());
sharedPreference.saveFavourite(getActivity(), text);
String[] photoUrl;
photoUrl = new String[10];
if(photoUrl==null){
Toast.makeText(getActivity(),"no favourite list",Toast.LENGTH_SHORT).show();
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (photoUrl.length == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
}
for (int index = 0; index < photoUrl.length; index++) {
photoUrl[index]=text;
if(text==null){
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
else {
StaggeredGridViewItem item;
item = new FavouriteGridItem(getActivity(), photoUrl); //pass one image of index
mStaggeredView.addItem(item);
}
}
// URL url = null;
// try {
// url = new URL(text);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
// iv.setImageBitmap(bmp);
return rootView;
}
private void showAlert(String string, String message) {
if (getActivity() != null && !getActivity().isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.create();
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();
//getActivity().finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
private StaggeredGridView.OnScrollListener scrollListener = new StaggeredGridView.OnScrollListener() {
public void onTop() {
}
public void onScroll() {
}
public void onBottom() {
}
};
#Override
public void onResume() {
super.onResume();
}
}
//imports
public class MainActivity extends Activity implements OnCheckedChangeListener
{
int count=0,ints......;
TextView textviews...;
int itemCode,month;
ArrayList<String> Name = new ArrayList<String>();
AlertDialog alertDialog ;
SharedPreferences sp;
EditText EtItemCode;
Editor editor ;
RadioButton RbForItemCode,RbForItemName;
RadioGroup RgForItemVsName;
PopupWindow popupWindowItems;
String popUpItems[];
ProgressDialog pDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//shared prefs
sp = this.getSharedPreferences("MySharedPrefsFile", Context.MODE_PRIVATE);
editor = sp.edit();
intForShardPref= sp.getInt("NEW_INSTALLATION",1); // getting Integer(1 is for no)
if(intForShardPref==1){
Intent intent = new Intent(this,Verify.class);
startActivityForResult(intent, 1);
}
else{
//do nothing
}
EtItemCode.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ToCheckItemCodeOfEdittext = EtItemCode.getEditableText().toString();
DatabaseHandler db=new DatabaseHandler(MainActivity.this);
List<Item> Items = db.getAllItemWithSubString(ToCheckItemCodeOfEdittext,itemNumberOrNameSelectedInRadioButtonOptions);
if(EtItemCode.length()>2){
if(EtItemCode.length()>3||flagForPopUpWindow>EtItemCode.length())
popupWindowItems.dismiss();
Name.clear();
for (Item cn : Items) {
if(RbForItemCode.isChecked()==true){
Name.add(Integer.toString(cn.getItemNumber()));
}
else{
Name.add(cn.getName());
}
}
popUpItems = new String[Name.size()];
Name.toArray(popUpItems);
popupWindowItems = popupWindowItems();
***popupWindowItems.setFocusable(false);***
popupWindowItems.showAsDropDown(findViewById(R.id.et_item_code), -5, 0);
}
else{
if(flagForPopUpWindow==3&&EtItemCode.length()==2)
popupWindowItems.dismiss();
}
flagForPopUpWindow=EtItemCode.length();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
private void init() {
// TODO Auto-generated method stub
//some code
}
public PopupWindow popupWindowItems() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewItems = new ListView(this);
// set our adapter and pass our pop up window contents
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
this, //context for activity
android.R.layout.simple_list_item_1, //layout used
Name){ //Items to be displayed
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item.toString();
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
//listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
listViewItems.setAdapter(adapter);
// set the item click listener
listViewItems.setOnItemClickListener(new ItemsDropdownOnItemClickListener());
// some other visual settings
//popupWindow.setFocusable(true);
popupWindow.setWidth(EtItemCode.getWidth());
//popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);
popupWindow.setHeight(r.height()-3*EtItemCode.getHeight());
// set the list view as pop up window content
popupWindow.setContentView(listViewItems);
return popupWindow;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.phone_number:
Intent p = new Intent(MainActivity.this,PhoneNumber.class);
startActivity(p);
break;
case R.id.exit:
finish();
break;
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//some code
}
class LoadDataBase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("DataBase Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
Log.d("Reading: ", "Reading all Items..");
List<Item> Items = db.getAllItem();
//some code
//DatabaseHandler db1 = new DatabaseHandler(this);
count= db.getItemCount();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
public class ItemsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "Item is: ", Toast.LENGTH_SHORT).show();
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EtItemCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// dismiss the pop up
popupWindowItems.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
Toast.makeText(MainActivity.this, "Item is: " + selectedItemText, Toast.LENGTH_SHORT).show();
DatabaseHandler db =new DatabaseHandler(MainActivity.this);
Item item= new Item();
if(RbForItemCode.isChecked()==true){
item = db.getItem(Integer.valueOf(selectedItemText));
}
else if(RbForItemName.isChecked()==true){
item = db.getItem(selectedItemText);
}
itemCode=item.getItemNumber();
}
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(RbForItemCode.isChecked()==true){
itemNumberOrNameSelectedInRadioButtonOptions="id";
//some code
}
}
else if(RbForItemName.isChecked()==true){
//some code
}
}
}
This code is working fine on my phone galaxy note 2(custom rom of note 4.. Android 4.4.4).By fine I mean I can type in edittext and popupwidow shows up after 3rd text(because of condition I have put) and I can select an option from the popupwindow. When I try to run the code on any other phone like galaxy grand then callback to ItemsDropdownOnItemClickListener is not registered and I can only scroll the popupwindow and keep on typing in edittext but cannot select any of the options in the popupwindow. If I set popupWindowItems.setFocusable(false) to true i.e popupWindowItems.setFocusable(true), and then as soon as I type 3rd letter in edittext,edittext looses focus and popwindow gains it. Now I can select anything.. But now I cannot continue to type in edittext.I have to manually select edittext and type.
Now I want that after tying 3rd word in edittext a popupwindow should appear(which currently is appearing) and edittext doesn't loose focus(so that i can continue typing).. Further if I select anything from popupwindow ,ItemsDropdownOnItemClickListener should be called which is currently being not called in other phones when popupWindowItems.setFocusable(false);
I am doing this to load data from sqlite database and show in popupwindow once the user types 3rd word. Any suggestion is recommended
Edit: Problem solved. Now using AutoComplete TextView
I'm a little new to Parse and Android development, so please excuse me if this question is trite or annoying. I've looked all over the Parse forums for a good way to delete items from a ParseQueryAdapter and haven't found anything satisfactory.
What I want is when a user confirms an item to be deleted/added, that item is immediately deleted/added to the ListView and updates the Parse server in the background. Help?
final ParseUser currentUser = ParseUser.getCurrentUser();
final ParseQueryAdapter<ParseObject> mainAdapter =
new ParseQueryAdapter<ParseObject>(this, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
// Here we can configure a ParseQuery to our heart's desire.
ParseQuery query = new ParseQuery("todo");
//query.whereEqualTo("user", currentUser);
return query;
}
});
mainAdapter.setTextKey("title");
// Set the ListActivity's adapter to be the PQA
final ListView list = getListView();
list.setAdapter(mainAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final int pos = position;
new AlertDialog.Builder(thisactivity)
.setTitle("Confirmation Dialog")
.setMessage("Do you really want to delete it?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ParseObject toBeDeleted = mainAdapter.getItem(pos);
toBeDeleted.deleteInBackground();
mainAdapter.loadObjects();
}})
.setNegativeButton(android.R.string.no, null).show();
}
});
final EditText todoName = (EditText)findViewById(R.id.todoName);
Button adder= (Button) findViewById(R.id.addTodo);
adder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTodo(todoName.getText().toString(), currentUser);
todoName.setText("");
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(todoName.getWindowToken(), 0);
mainAdapter.loadObjects();
}
});
Perhaps I can help you with this problem.
The following removal procedure:
private void delItem(Basket object) {
final ParseItems finalitem = object.getParseItem();
ParseQuery<Basket> query = Basket.getQuery();
query.setMaxCacheAge(TimeUnit.SECONDS.toMillis(1));
query.setCachePolicy(ParseQuery.CachePolicy.NETWORK_ELSE_CACHE);
//query.fromLocalDatastore();
query.whereEqualTo("parseItem", finalitem);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.whereNotEqualTo("sent", true);
query.getFirstInBackground(new GetCallback<Basket>() {
#Override
public void done(final Basket basket, ParseException e) {
if (basket != null) {
basket.increment("quantity", -1);
basket.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
SuperToast superToast = new SuperToast(context);
superToast.setDuration(SuperToast.Duration.VERY_SHORT);
superToast.setText("del: " + finalitem.getName() + "-1=" + basket.getQuantity());
superToast.setIcon(R.drawable.del, SuperToast.IconPosition.LEFT);
superToast.show();
}
});
if (basket.getQuantity() <= 0) {
basket.deleteEventually(new DeleteCallback() {
#Override
public void done(ParseException e) {
SuperToast superToast = new SuperToast(context);
superToast.setDuration(SuperToast.Duration.VERY_SHORT);
superToast.setText("remove: " + finalitem.getName());
superToast.setIcon(R.drawable.del, SuperToast.IconPosition.LEFT);
superToast.show();
}
});
}
}
}
});
smsmanager is not working,its not showing any error also,it function is not working at all,dialog dismiss only working.
Mainactivity.java
public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
private List items;
private Button btnGetSelected;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
initView();
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://dry-brushlands-3645.herokuapp.com/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
//mDbHelper.open();
//Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
//String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
//int[] to = new int[]{R.id.text1};
/* Now create a simple cursor adapter and set it to display
SimpleCursorAdapter projects =
new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
setListAdapter(projects);
*/
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
/*dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, ProjectEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Application bean : items) {
if (bean.isSelected()) {
sb.append(Html.fromHtml(bean.getContent()));
sb.append(",");
}
}
showAlertView(sb.toString().trim());
}
#SuppressWarnings("deprecation")
private void showAlertView(String str) {
AlertDialog alert = new AlertDialog.Builder(this).create();
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
dialog.dismiss();
}
});
In my code i am using sms manager for sending sms which are the thing getting from my listview,it has to send sms,but after clicking the ok button,nothing is work, dialog dismiss only working,not sms manager is not working.
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
"phoneNo" in this place specify the number for which you want to send sms
ok what is that selected data does that contain the phone numbers or the some text data that needs to be sent as a message. see "phoneNo" is string what you are passing. In your phone in place of number if you type phoneNo how will it send to which number will it send. that 1st parameter is the phone number to which you want to send sms. if you are selecting the phone number from the list get that to a variable and put that variable in place of "phoneNo"
if you want to enter the number when the alert is shown then here is the code
private void showAlertView(String str) {
final EditText input = new EditText(YOURACTIVITYNAME.this);
AlertDialog alert = new AlertDialog.Builder(YOURACTIVITYNAME.this)
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
String value;
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(input.getText().toString(), null, "sms message", null, null);
dialog.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
For some reason my Fragment never calls onCreateOptionsMenu to inflate my menu, the overflow menu never appears and pressing the menu button in the emulator also does nothing. I've tried using setHasOptionsMenu(true) but this also does anothing.
Any ideas?
Here's my onCreate, onCreateOptionsMenu and onPrepareOptionsMenu
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setMenuVisibility(true);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
EDIT:
Full Fragment code.
public class BackupFragment extends ExpandableListFragment {
public static final Uri SMS_URI = Uri.parse("content://sms");
private static final int CONTEXTMENU_IMPORT = 21;
private static final int CONTEXTMENU_DELETEFILE = 22;
private static final int CONTEXTMENU_DELETEDAY = 23;
private static final int UPLOAD_DROPBOX = 24;
private static final int UPLOAD_DRIVE = 25;
private static final int DIALOG_LICENSEAGREEMENT = 1;
private static final int DIALOG_ABOUT = 2;
public static final int DIALOG_EXPORT = 4;
public static final String STANDARD_DIRNAME = new StringBuilder(Environment.getExternalStorageDirectory().toString()).append("/backup/").toString();
public static File DIR;
public static final boolean CANHAVEROOT = checkRoot();
public static BackupFragment INSTANCE;
#SuppressWarnings("deprecation")
public static final int API_LEVEL = Integer.parseInt(Build.VERSION.SDK);
public BackupFilesListAdapter listAdapter;
private AlertDialog deleteFileDialog;
private AlertDialog deleteDayDialog;
private ProgressDialog exportDialog;
private ProgressDialog importDialog;
private AlertDialog selectExportsDialog;
private ExporterInfos exporterInfos;
private View FragmentView;
/**
* Sets up the main content of the application (i.e. loads the list of
* available backups and generates the context menu).
*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentView = inflater.inflate(R.layout.backup_fragment, container, false);
//registerForContextMenu(FragmentView);
return FragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
INSTANCE = this;
super.onActivityCreated(savedInstanceState);
Crittercism.init(getActivity().getApplicationContext(), "516574be558d6a5f8a00001f");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String dirName = preferences.getString(Strings.PREFERENCE_STORAGELOCATION, STANDARD_DIRNAME);
if (TextUtils.isEmpty(dirName)) {
dirName = STANDARD_DIRNAME;
}
DIR = new File(dirName);
listAdapter = new BackupFilesListAdapter(getActivity(), preferences);
getExpandableListView().setAdapter(listAdapter);
getExpandableListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
ExpandableListView.ExpandableListContextMenuInfo expandableInfo = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
menu.setHeaderTitle(((TextView) ((ExpandableListView.ExpandableListContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText());
if (ExpandableListView.getPackedPositionType(expandableInfo.packedPosition) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
menu.add(0, CONTEXTMENU_IMPORT, Menu.NONE, R.string.button_import);
menu.add(0, CONTEXTMENU_DELETEFILE, Menu.NONE, R.string.contextmenu_deletefile);
menu.add(0, UPLOAD_DROPBOX, Menu.NONE, R.string.upload_dropbox);
menu.add(0, UPLOAD_DRIVE, Menu.NONE, R.string.upload_drive);
} else {
menu.add(0, CONTEXTMENU_DELETEDAY, Menu.NONE, R.string.contextmenu_deletedaydata);
}
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setMenuVisibility(true);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(getClass().getSimpleName(), item.toString());
switch (item.getItemId()) {
case R.id.menu_about: {
showDialog(DIALOG_ABOUT);
break;
}
case CONTEXTMENU_DELETEFILE: {
/* using "showDialog" with a Bundle is only available from api version 8 on, so we cannot directly use this. Lets impose this */
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
if (ExpandableListView.getPackedPositionType(packedPosition) != ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
break;
}
final File file = listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition));
if (deleteFileDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(android.R.string.dialog_alert_title);
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// just to enable the button
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setMessage(Strings.EMPTY); // just so that the string is available
deleteFileDialog = builder.create();
}
deleteFileDialog.show();
deleteFileDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!file.exists() || file.delete()) {
listAdapter.remove(file);
} else {
// show error
}
deleteFileDialog.dismiss();
}
});
deleteFileDialog.setMessage(String.format(getString(R.string.question_deletefile), file.toString()));
break;
}
case CONTEXTMENU_IMPORT: {
ExpandableListView.ExpandableListContextMenuInfo menuInfo = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
long packedPosition = menuInfo.packedPosition;
if (ExpandableListView.getPackedPositionType(packedPosition) != ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
break;
}
if (importDialog == null) {
importDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(importDialog);
new ImportTask(importDialog, listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition)), (Integer) menuInfo.targetView.getTag());
break;
}
case CONTEXTMENU_DELETEDAY: {
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
if (ExpandableListView.getPackedPositionType(packedPosition) != ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
break;
}
final int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
Date date = listAdapter.getGroup(groupPosition);
if (deleteDayDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(android.R.string.dialog_alert_title);
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// just to enable the button
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setMessage(Strings.EMPTY); // just so that the string is available
deleteDayDialog = builder.create();
}
deleteDayDialog.show();
deleteDayDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Vector<File> files = listAdapter.getChildren(groupPosition);
Vector<File> deletedFiles = new Vector<File>();
for (File file : files) {
if (!file.exists() || file.delete()) {
deletedFiles.add(file);
} else {
// show error
}
}
listAdapter.remove(deletedFiles);
deleteDayDialog.dismiss();
}
});
deleteDayDialog.setMessage(String.format(getString(R.string.question_deletefile), DateFormat.getDateInstance().format(date)));
break;
}
case R.id.menu_exporteverything: {
if (exportDialog == null) {
exportDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(exportDialog);
checkExportTaskForIncompleteData(new ExportTask(exportDialog, listAdapter, EverythingExporter.ID));
break;
}
case R.id.menu_export: {
if (selectExportsDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle(R.string.dialog_export);
exporterInfos = Exporter.getExporterInfos(getActivity());
builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setItems(exporterInfos.names, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exportDialog == null) {
exportDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(exportDialog);
checkExportTaskForIncompleteData(new ExportTask(exportDialog, listAdapter, exporterInfos.ids[which]));
}
});
selectExportsDialog = builder.create();
}
selectExportsDialog.show();
break;
}
case R.id.menu_settings: {
break;
}
case UPLOAD_DROPBOX: {
Intent i = new Intent(getActivity(), Dropbox.class);
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
final File file = listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition));
i.putExtra("file", file.toString());
i.putExtra("path", file.getName());
startActivity(i);
break;
}
case UPLOAD_DRIVE: {
Intent i = new Intent(getActivity(), DriveAuth.class);
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
final File file = listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition));
i.putExtra("file", file.toString());
i.putExtra("path", file.getName());
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
/**
* Checks if the exporter that is attached to the given ExportTask may
* produce incomplete data and shows a warning if this is the case and
* if the user wants to get notified. Note that the standard setting is
* to show the warning.
* The user may also cancel the warning dialog which results in the
* export to be not performed.
*
* #param exportTask task whose exporter is checked w.r.t. incomplete
* exports
*/
private void checkExportTaskForIncompleteData(final ExportTask exportTask) {
Exporter exporter = exportTask.getExporter();
if (!PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(Strings.PREFERENCE_HIDEDATAWARNINGS, false) && exporter.maybeIncomplete()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(android.R.string.dialog_alert_title);
builder.setMessage(getString(R.string.warning_incompletedata_export, exporter.getIncompleteDataNames(getActivity())));
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
exportTask.execute();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setCancelable(true);
builder.show();
} else {
exportTask.execute();
}
}
/**
* Here, the given progress dialog will be reset.
*
* #param dialog progress dialog to be reset
*/
private void checkProgressDialog(ProgressDialog dialog) {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.setMessage(Strings.EMPTY); // we just have to set some non-null value to enable the title
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
if (importDialog == null) {
importDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(importDialog);
new ImportTask(importDialog, listAdapter.getChild(groupPosition, childPosition), (Integer) v.getTag());
return true;
}
protected void showDialog(int id) {
if (id == DIALOG_LICENSEAGREEMENT) {
AlertDialogFragment myDialogFragment = AlertDialogFragment.newInstance();
myDialogFragment.show(getFragmentManager(), "myDialogFragment");
}
}
/**
* In order to perform certain backups (such as the wifi settings), we
* need root to access the corresponding configuration files.
*
* #return true if <i>root</i> access can be obtained, <i>false</i>
* otherwise
*/
private static boolean checkRoot() {
try {
Process process = Runtime.getRuntime().exec("/system/bin/ls -l /system/bin/su /system/xbin/su");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
reader.close();
process.destroy();
return line != null && line.length() > 9 && line.charAt(9) == 'x';
} catch (Exception e) {
return false;
}
}
}
You're probably inflating stuff on the activity and not calling super.
If you're inflating any menu items on any other fragment or in the activity you should also call super.onCrea .... on them.
Another option for common menu problems is, if you're using actionbar sherlock, you should extend the SherlockFragment in order to use the menu.
Moving to ABS instead of the Support library seems to have fixed things, it may have been due to conflicts with the SlidingMenu library I am using.