Options Menu never shows in Fragment - android

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.

Related

Alertdialog selected items Arraylist is growing when i came from child activity

I have 2 Activities A(user input) and B (Display based on user input). Where in Activity A, i am selecting multiple values from alert dialog and put it in arraylist then pass it on to the activity B. So when i want to change the values i need to comeback to Activity A and i can reselect. But When i am reselecting the value or removing any values the older selected values are also exist so that my Arraylist is keep on growing. Please help.
Activity A:
public class AllMovieRating extends ActionBarActivity implements View.OnClickListener {
private Views mViews;
final ArrayList ilist = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_movie_rating);
mViews=new Views();
mViews.irating.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imdb_rating:
ilist();
break;
}
}
private void filtervalues() {
Intent intent = new Intent(AllRating.this,sharedcollect.class);
intent.putExtra("im",ilist);
startActivity(intent);
}
public ArrayList ilist() {
final CharSequence[] ratings = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
final boolean[] ratingschecked = {false, false, false, false, false, false, false, false, false, false};
SharedPreferences sharedPreferences = this.getSharedPreferences("checkedrate_i", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
int size = sharedPreferences.getInt("size", 0);
for(int j=0;j<size;j++)
{
ilist.add(sharedPreferences.getString("selectedratings" + j, null));
//Log.e("Kumar", "" + selectedratings);
}
for(int j=0;j<=ratingschecked.length;j++){
if(ilist.contains((String.valueOf(j)))) {
ratingschecked[j-1] = true;
}
}
builder.setTitle("Select Ratings");
builder.setMultiChoiceItems(ratings, ratingschecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if(!ilist.contains((String)String.valueOf(ratings[which]))){
ilist.add(String.valueOf(ratings[which]));
ratingschecked[which]=true;
}
} else if ((ilist.contains((String)String.valueOf(ratings[which])))) {
ilist.remove(String.valueOf(ratings[which]));
// Log.e("Kumar", String.valueOf(ratings[which]));
ratingschecked[which]=false;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// editor.putString("checked", String.valueOf(selectedratings));
for (int i = 0; i < ilist.size(); i++) {
editor.putString("selectedratings" + i, String.valueOf(ilist.get(i)));
}
editor.putInt("size", ilist.size());
editor.apply();
//Log.e("Shiva", String.valueOf(selectedratings));
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
builder.show();
return ilist;
}
Activity B:
public class sharedcollect extends ActionBarActivity {
ListView movielist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sharedcollect);
Intent i = getIntent();
ArrayList<String> list = i.getStringArrayListExtra("im");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sharedcollect, menu);
return true;
}
#Override
public void onBackPressed() {
//do whatever to save the settings
moveTaskToBack(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()){
case R.id.action_settings:
Intent intent = new Intent(sharedcollect.this,AllMovieRating.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
} }}
Tried using OnBackPressed() inside onOptionsItemSelected(MenuItem item) in Activity B but that doesn't helped. How can i control array list so that i will send only the selected items.
You will need to clear the array Before every reselecting in Activity A.
ilist.clear();
In your case my guess is to do add the following in your Activity A.
EDITED:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.imdb_rating:
ilist.clear();
ilist();
break;
}}

Using smsmanagaer is not working in alertbox

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();

App crash when open EDIT dialog and rotate device

I have a problem. When I click "ADD exercise" and open ADD dialog to put some info everything works good even when I rotate device. But when I rotate device with "EDIT dialog" the APP is crashing
Please, help me.
Need something to prevent it. (I'm not programmer, so its not easy for me)
public class ShowExercisesListActivity extends ListActivity {
private static final String TAG = "Exercises";
private List<Exercise> mExercises;
private LayoutInflater mInflater;
private ArrayAdapter<Exercise> mArrayAdapter;
private View mAddExerciseDialogLayout;
private Context mContext;
private EditText exerciseName;
private static final int DIALOG_ADD_EXERCISE = 0;
// package scope, since it is accessed in inner classes
WorkoutTrackerApp mApp;
/**
* Called when the activity is first created.
*
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.type_list);
mApp = (WorkoutTrackerApp) getApplication();
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mExercises = DBUtil.fetchAllExercises(this);
mArrayAdapter = new ArrayAdapter<Exercise>(this, R.layout.type_list_item, mExercises) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (null == convertView) {
row = mInflater.inflate(R.layout.type_list_item, null);
} else {
row = convertView;
}
Exercise type = (Exercise) mExercises.get(position);
TextView tv = (TextView) row.findViewById(android.R.id.text1);
tv.setText(type.getName());
return row;
}
};
setListAdapter(mArrayAdapter);
//dialog box layout
mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
mAddExerciseDialogLayout = inflater.inflate(R.layout.add_type_dialog, (ViewGroup) findViewById(R.id.type_layout_root));
exerciseName = (EditText) mAddExerciseDialogLayout.findViewById(R.id.type_name);
//register for context menu
registerForContextMenu(getListView());
if (mExercises.size() == 0) {
// if there are no exercises initially, then show the add type dialog
showDialog(DIALOG_ADD_EXERCISE);
}
//Начало:Активация кнопки "Добавить упражнение"
Button addExerciseButton = (Button) findViewById(R.id.menu_add_exercise);
addExerciseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mApp.setCurrrentDialogStatus(DialogStatus.ADD);
showDialog(DIALOG_ADD_EXERCISE);
}
});
//Конец: Активация кнопки "Добавить упражнение"
//Начало:Активация иконки Верхней плашки
ImageButton GoHomeButton = (ImageButton) findViewById(R.id.imageButton1);
GoHomeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent5 = new Intent(ShowExercisesListActivity.this, AndroidApp.class);
ShowExercisesListActivity.this.startActivity(myIntent5);
}
});
//Конец:Активация иконки Верхней плашки
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Exercise type = mExercises.get(position);
Log.v(TAG, "Clicked " + type.getName() + "Id: " + type.getId());
Intent intent = new Intent(this.getApplicationContext(),
TabWidget.class);
intent.putExtra("typeId", type.getId());
startActivity(intent);
}
/**
* When the context menu is created
*
* #see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.exercise_context_menu, menu);
}
/**
* When a context menu item is selected
*
* #see android.app.Activity#onContextItemSelected(android.view.MenuItem)
*/
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit_exercise:
//Edit Exercise name
mApp.setCurrentExerciseDialogStatus(DialogStatus.EDIT);
editExercise((int) info.id);
return true;
case R.id.delete_exercise:
//Delete Exercise and all its entries
deleteExercise((int) info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.types_menu, menu);
return true;
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_exercise:
mApp.setCurrentExerciseDialogStatus(DialogStatus.ADD);
showDialog(DIALOG_ADD_EXERCISE);
break;
case R.id.home: // Go Back to local website
Intent myIntent3 = new Intent(ShowExercisesListActivity.this, AndroidApp.class);
ShowExercisesListActivity.this.startActivity(myIntent3);
return true;
case R.id.close: // Close WebView
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return true;
case R.id.google: // Open new WebView with the e.g. Google Url
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://vk.com/gymtraining")));
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/* (non-Javadoc)
* #see android.app.Activity#onCreateDialog(int)
*/
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch (id) {
case DIALOG_ADD_EXERCISE:
AlertDialog.Builder builder;
//build the dialog
builder = new AlertDialog.Builder(mContext);
builder.setView(mAddExerciseDialogLayout);
builder.setMessage(this.getString(R.string.add_exercise_title))
.setCancelable(false)
.setPositiveButton(this.getString(R.string.add, this.getString(R.string.exercise)), null)
.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
dialog = builder.create();
break;
default:
dialog = null;
break;
}
return dialog;
}
/* (non-Javadoc)
* #see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
AlertDialog alertDialog = (AlertDialog) dialog;
Button positiveButton = null;
switch (id) {
case DIALOG_ADD_EXERCISE:
switch (mApp.getCurrentExerciseDialogStatus()) {
case DEFAULT:
case ADD:
alertDialog.setMessage(this.getString(R.string.add_exercise_title));
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, this.getString(R.string.add, this.getString(R.string.exercise)), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Insert the new data into db
String typeName = exerciseName.getText().toString();
Exercise newExercise = DBUtil.insertExercise(mContext, typeName);
Toast.makeText(mContext, mContext.getResources().getString(R.string.exercise_saved), Toast.LENGTH_SHORT).show();
mArrayAdapter.add(newExercise);
mArrayAdapter.notifyDataSetChanged();
}
});
positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setText(this.getString(R.string.add, this.getString(R.string.exercise)));
positiveButton.invalidate();
exerciseName.setText("");
break;
case EDIT:
alertDialog.setMessage(this.getString(R.string.edit, this.getString(R.string.exercise)));
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, this.getString(R.string.edit_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Update the data into db
Exercise exerciseToEdit = (Exercise) exerciseName.getTag();
exerciseToEdit.setName(exerciseName.getText().toString());
DBUtil.updateExercise(mContext, exerciseToEdit);
Toast.makeText(mContext, mContext.getResources().getString(R.string.exercise_saved), Toast.LENGTH_SHORT).show();
mArrayAdapter.notifyDataSetChanged();
}
});
Exercise exerciseToEdit = (Exercise) exerciseName.getTag();
exerciseName.setText(exerciseToEdit.getName());
positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setText(this.getString(R.string.edit_button));
positiveButton.invalidate();
break;
}
default:
break;
}
}
/**
* Edit Exercise name
*
* #param id
*/
private void editExercise(int position) {
exerciseName.setTag(mExercises.get(position));
showDialog(DIALOG_ADD_EXERCISE);
}
/**
* Delete an Exercise
*
* #param position
*/
private void deleteExercise(int position) {
Exercise exercise = mExercises.get(position);
DBUtil.deleteExercise(mContext, exercise.getId());
Toast.makeText(mContext, mContext.getResources().getString(R.string.exercise_deleted), Toast.LENGTH_SHORT).show();
mArrayAdapter.remove(exercise);
mArrayAdapter.notifyDataSetChanged();
}
}
I can't go over the whole code right now but if your problem is only when you rotate the phone and it is not necessary to have the rotation activated, then why don't you just add either of the following lines into your activity definition in your AndroidManifest.xml
android:screenOrientation="portrait"
or
android:screenOrientation="landscape"

What if you don't want to create dozen classes for AlertDialogs?

I have many different states according to which I need to feedback to User with a message in form of AlertDialog. It's just insane to create a separate class for each alert. What I have now is:
class FeedbackAlertDialog extends DialogFragment {
private String message;
private int action;
FeedbackAlertDialog() {
}
FeedbackAlertDialog(String message, int action) {
this.message = message;
this.action = action;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(message)
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
switch (action) {
case action: // It's impossible because the int should be final
}
startActivity(new Intent(getActivity(), MainActivity.class));
}
}).show();
}
}
The problem is that I can't use switch because int should be final. How to come up with this situation?
use:
FeedbackAlertDialog.this.action
As far as i can see this should be in the switch.
This same way is used for accesing higher level variables (Notice Setters in a simple model).
in your case you have to first get into the scope of the root object(your case FeedbackAlertDialog).
It was just impossible because you need to use a constant in switch.
EDIT ::
Try this simple java demo at your computer system:
public class CalcDemo {
public static void main(String[] args) {
int n1 = 6, n2 = 3;
int opr = 1;
MyMath math = new MyMath(n1, n2, opr);
System.out.println("Answer :: "+math.getResult());
}
}
class MyMath {
int n1, n2, opr;
public MyMath() { }
public MyMath(int n1, int n2, int opr) {
this.n1 = n1;
this.n2 = n2;
this.opr = opr;
}
public int getResult() {
//int ch = opr;
switch (opr) {
case 1: return n1-n2;
//break;
case 2: return n1+n2;
default : System.out.println("Invalid Choice");
break;
}
return 0;
}
}
Do one Trick as following:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setTitle(message)
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final int action1 = action; // <---- --- Try This
switch (action1) { // <--- --- Use as This
case action1: // I THINK, NOW THIS IS POSSIBLE
}
startActivity(new Intent(getActivity(), MainActivity.class));
}
}).show();
}

Saving Option Menu Shared Preferences

I have a option menu. When the activity loses focus, the selected option menu item(s) retain state, but when my activity is destroyed, all the options are reset.
How can I save the state of the selected preference after resuming from a destroyed state? Having problem visualizing how to implement Shared Preferences for the code.
(Only needed for the boolean values but I have included the static menu items.)
public final static int MENU_SOMETHING_MODE_ON = 1;
public final static int MENU_SOMETHING_MODE_OFF = 2;
public final static int MENU_FULLSCREEN_ON = 3;
public final static int MENU_FULLSCREEN_OFF = 4;
public final static int MENU_SOUND_ON = 5;
public final static int MENU_SOUND_OFF = 6;
public final static int MENU_FASTER = 7;
public final static int MENU_SLOWER = 8;
public final static int MENU_SOMETHING = 9;
public final static int MENU_EXTRAS = 10;
private static boolean soundOn = true;
private static boolean mFaster = true;
private boolean fullscreen = true;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_SOMETHING, 0, R.string.menu_new_something);
menu.add(0, MENU_SOMETHING_MODE_ON, 0,
R.string.menu_something_on);
menu.add(0, MENU_SOMETHING_MODE_OFF, 0,
R.string.menu_something_off);
menu.add(0, MENU_FULLSCREEN_ON, 0, R.string.menu_fullscreen_on);
menu.add(0, MENU_FULLSCREEN_OFF, 0, R.string.menu_fullscreen_off);
menu.add(0, MENU_SOUND_ON, 0, R.string.menu_sound_on);
menu.add(0, MENU_SOUND_OFF, 0, R.string.menu_sound_off);
menu.add(0, MENU_FASTER, 0, R.string.menu_faster);
menu.add(0, MENU_SLOWER, 0, R.string.menu_slower);
menu.add(0, MENU_EXTRAS, 0, R.string.menu_extras);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
menu.findItem(MENU_SOUND_ON).setVisible(!getSoundOn());
menu.findItem(MENU_SOUND_OFF).setVisible(getSoundOn());
menu.findItem(MENU_SOMETHING_ON).setVisible(
getMode() == SOMETHING_NORMAL);
menu.findItem(MENU_SOMETHING_OFF).setVisible(
getMode() != SOMETHING_NORMAL);
menu.findItem(MENU_FULLSCREEN_ON).setVisible(!fullscreen);
menu.findItem(MENU_FULLSCREEN_OFF).setVisible(fullscreen);
menu.findItem(MENU_FASTER).setVisible(getFaster());
menu.findItem(MENU_SLOWER).setVisible(!getFaster());
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case MENU_SOMETHING:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you sure?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'YES' Button
something.new();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Something");
// Icon for AlertDialog
alert.setIcon(R.drawable.dialog);
alert.show();
return true;
case MENU_SOMETHING_ON:
setMode(THIS_SOMETHING);
return true;
case MENU_SOMETHING_OFF:
setMode(THIS_NORMAL);
return true;
case MENU_FULLSCREEN_ON:
fullscreen = true;
setFullscreen();
return true;
case MENU_FULLSCREEN_OFF:
fullscreen = false;
setFullscreen();
return true;
case MENU_SOUND_ON:
setSoundOn(true);
return true;
case MENU_SOUND_OFF:
setSoundOn(false);
return true;
case MENU_FASTER:
setFaster(false);
return true;
case MENU_SLOWER:
setSlower(true);
return true;
case MENU_EXTRAS:
startExtras();
return true;
}
return false;
}
private void setFullscreen()
{
if (fullscreen) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
mView.requestLayout();
}
public synchronized static void setMode(int newMode)
{
Mode = newMode;
}
public synchronized static int getMode()
{
return Mode;
}
public synchronized static boolean getSoundOn()
{
return soundOn;
}
public synchronized static void setSoundOn(boolean so)
{
soundOn = so;
}
public synchronized static boolean getFaster()
{
return Faster;
}
public synchronized static void setFaster(boolean dont)
{
Faster = dont;
}
This is a fantastic tutorial on how to create a preference activity along with how to get/set these preferences. It will also show you how to use shared preferences if you choose not to implement a preference activity.
Almost all users are familiar with a preference activity because it is how they adjust settings on their phone.
While not the only way to implement "options," or possibly perhaps not even the best way, it works great, has a ton of flexibility, and is simple and quick to implement.

Categories

Resources