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"
Related
My items for Listview are not showing, can someone point me where is the error.
There is no error when adding items but its not showing on the Listview. I revised my post, I'm trying to use BaseAdapter to populate the items. I can confirm that the items are added to the database because the total amount is updated everytime i add item.
public class ViewTransactions extends Activity {
private ListView mListViewTransactions;
private TransactionAdapter mAdapter;
private List<TransactionModel> mListTransactions;
/** transactions data source. */
private TransactionDao transactionSource;
/** Currently selected broker, as specified by intent received from ViewBrokers class. */
private BrokerModel currentBroker;
/** The sum total of all transactions for the active broker. */
private BigDecimal brokerTotal;
private ArrayAdapter<TransactionModel> aa;
/** Action mode for the context menu. */
private ActionMode aMode;
/** Call back methods for the context menu. */
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
/** Title which displays broker name. */
private TextView title;
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_transactions, menu);
// disable listener here; moved from onPrepareActionMode
title = (TextView) findViewById(R.id.exCat);
title.setClickable(false); // prevent navigation away from activity
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
title = (TextView) findViewById(R.id.exCat);
title.setClickable(false); // prevent navigation away from activity
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
// edit selected expense
editTransaction();
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.action_del:
// delete selected expense
deleteTransaction();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
// unselect item that was selected (if it wasn't deleted)
final ListView lv = (ListView)findViewById(R.id.tList);
lv.clearChoices();
lv.setItemChecked(lv.getCheckedItemPosition(), false);
lv.post(new Runnable() {
#Override
public void run() {
lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
}
});
aMode = null;
title.setClickable(true); // restore broker name click
}
};
/**
* Class to asynchronously retrieve transactions from database.
*/
private class GetTransactions extends AsyncTask<Void, Void, List<TransactionModel>> {
#Override
protected List<TransactionModel> doInBackground(Void... params) {
// retrieve all transactions for the user and broker
return transactionSource.getTransactions(currentBroker);
}
#Override
protected void onPostExecute(final List<TransactionModel> result) {
mAdapter = new TransactionAdapter(ViewTransactions.this, mListTransactions);
mListViewTransactions.setAdapter(mAdapter);
mListViewTransactions.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
// Called when the user long-clicks on an item
public boolean onItemLongClick(AdapterView<?> aView, View view, int i, long l) {
if (aMode != null) {
return false;
}
mListViewTransactions.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// mark item at position i as selected
mListViewTransactions.setItemChecked(i, true);
// Start the CAB using the ActionMode.Callback defined above
aMode = ViewTransactions.this.startActionMode(mActionModeCallback);
return true;
}
});
}
}
/**
* Class to asynchronously add new expense to database.
*/
private class AddTransaction extends AsyncTask<String, Void, TransactionModel> {
#Override
protected TransactionModel doInBackground(String... params) {
return transactionSource.newTransaction(params[0], new BigDecimal(params[1]), params[2],
currentBroker);
}
#Override
protected void onPostExecute(TransactionModel result) {
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
mAdapter = new TransactionAdapter(ViewTransactions.this, mListTransactions);
// mAdapter.add(result);
mAdapter.notifyDataSetChanged();
// update total
brokerTotal = brokerTotal.add(result.getTransactionAmount());
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
}
}
/**
* Class to asynchronously edit an expense in database.
*/
private class EditTransaction extends AsyncTask<TransactionModel, Void, TransactionModel> {
#Override
protected TransactionModel doInBackground(TransactionModel... params) {
return transactionSource.editTransaction(params[0]);
}
#Override
protected void onPostExecute(TransactionModel result) {
// #SuppressWarnings("unchecked")
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
aa.notifyDataSetChanged();
// update total
brokerTotal = brokerTotal.add(result.getTransactionAmount());
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
}
}
/**
* Class to asynchronously delete an expense from database.
*/
private class DeleteTransaction extends AsyncTask<TransactionModel, Void, TransactionModel> {
#Override
protected TransactionModel doInBackground(TransactionModel... params) {
return transactionSource.deleteTransaction(params[0]); // delete selected item from db
}
#Override
protected void onPostExecute(TransactionModel result) {
// #SuppressWarnings("unchecked")
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
aa.remove(result); // remove selected item from adapter
aa.notifyDataSetChanged();
// update total
brokerTotal = brokerTotal.subtract(result.getTransactionAmount());
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
}
}
/**
* Method to record a new expense. Called when Add button in action bar is clicked.
*/
private void addTransaction() {
// build dialog to ask for expense details
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Record Transaction");
builder.setMessage("Please enter transaction details.");
// construct input fields
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final EditText enterDate = new EditText(this);
final EditText enterCost = new EditText(this);
final EditText enterDesc = new EditText(this);
enterDate.setHint("Date");
enterCost.setHint("Amount");
enterDesc.setHint("Transaction");
enterDate.setInputType(InputType.TYPE_CLASS_DATETIME); // date text
enterDate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
enterCost.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); // to accept dollar amount
enterCost.setKeyListener(DigitsKeyListener.getInstance("0123456789.-")); // accept digits
enterDesc.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); // description text
enterDesc.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
ll.addView(enterDate);
ll.addView(enterCost);
ll.addView(enterDesc);
builder.setView(ll);
// add ok and cancel buttons
builder.setPositiveButton(R.string.ok, null);
builder.setNegativeButton(R.string.cancel, null);
// create dialog
final AlertDialog dia = builder.create(); // don't show yet
// set listener to description input field to click OK when done
enterDesc.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set listener to date input field to click OK when done
enterDate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set input mode to let keyboard appear when dialog is shown
dia.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dia.show();
// override onclick for OK button; must be done after show()ing to retrieve OK button
dia.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// retrieve name entered
String date = enterDate.getText().toString().trim();
String cost = enterCost.getText().toString().trim();
String desc = enterDesc.getText().toString().trim();
// perform checks and add if pass
if (cost.equals("")) { // must not be empty
enterCost.setError("Please enter an amount.");
//} else if (!Pattern.matches("^(\\d{1,10})?(\\.\\d{0,2})?$", cost)) { // must be $$
// enterCost.setError("Please enter a valid amount.");
} else {
// can be added
new AddTransaction().execute(date, cost, desc);
dia.dismiss();
}
}
});
}
/**
* Method to edit selected expense. Called when Edit button is clicked in context menu.
*/
private void editTransaction() {
// retrieve adapter and retrieve selected expense
// ListView lv = getListView();
#SuppressWarnings("unchecked")
// final ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
// final TransactionModel exToEdi = aa.getItem(lv.getCheckedItemPosition()); // get item at checked pos
// build dialog to ask for expense details
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Edit Transaction");
builder.setMessage("Please enter transaction details.");
// construct input fields
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final EditText enterDate = new EditText(this);
final EditText enterCost = new EditText(this);
final EditText enterDesc = new EditText(this);
// enterDate.setText(exToEdi.getTransactionDate());
// enterCost.setText(exToEdi.getTransactionAmount().toString());
// enterDesc.setText(exToEdi.getTransactionDescription());
enterDate.setInputType(InputType.TYPE_CLASS_DATETIME); // description text
enterDate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
enterCost.setInputType(InputType.TYPE_CLASS_NUMBER); // to accept dollar amount
enterCost.setKeyListener(DigitsKeyListener.getInstance("0123456789.")); // accept digits
enterDesc.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); // description text
enterDesc.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
ll.addView(enterDate);
ll.addView(enterCost);
ll.addView(enterDesc);
builder.setView(ll);
// add ok and cancel buttons
builder.setPositiveButton(R.string.ok, null);
builder.setNegativeButton(R.string.cancel, null);
// create dialog
final AlertDialog dia = builder.create(); // don't show yet
// set listener to description input field to click OK when done
enterDesc.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set listener to date input field to click OK when done
enterDate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set input mode to let keyboard appear when dialog is shown
dia.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dia.show();
// override onclick for OK button; must be done after show()ing to retrieve OK button
dia.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// retrieve name entered
String date = enterDate.getText().toString().trim();
String cost = enterCost.getText().toString().trim();
String desc = enterDesc.getText().toString().trim();
// perform checks and add if pass
if (cost.equals("")) { // must not be empty
enterCost.setError("Please enter a dollar amount.");
//} else if (!Pattern.matches("^(\\d{1,10})?(\\.\\d{0,2})?$", cost)) { // must be $$
// enterCost.setError("Please enter a valid dollar amount.");
} else {
// can be changed
// brokerTotal = brokerTotal.subtract(exToEdi.getTransactionAmount());
// exToEdi.setTransactionAmount(new BigDecimal(cost));
// exToEdi.setTransactionDescription(desc);
// exToEdi.setTransactionDate(date);
// new EditTransaction().execute(exToEdi);
dia.dismiss();
}
}
});
}
/**
* Method to delete selected expense. Called when Delete button is clicked in context menu.
*/
private void deleteTransaction() {
// get list view and list adapter
// ListView lv = getListView();
// #SuppressWarnings("unchecked")
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
// int pos = lv.getCheckedItemPosition(); // get pos of selected item
// TransactionModel del = aa.getItem(pos); // get item in adapter at position pos
// new DeleteTransaction().execute(del); // delete expense async and update total
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.capital_activity_view_transactions);
initViews();
currentBroker = (BrokerModel) getIntent().getSerializableExtra(IntentTags.CURRENT_BROKER);
// set totalCost = ; here
// set title to broker
TextView title = (TextView) findViewById(R.id.exCat);
title.setText(currentBroker.getBroker());
title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it = new Intent(ViewTransactions.this, ViewBrokers.class);
startActivity(it);
}
});
// open data source
transactionSource = new TransactionDao(this);
transactionSource.open();
// display total for user, cat, month/year
brokerTotal = transactionSource.getTotalCost(currentBroker);
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
new GetTransactions().execute(); // retrieve display transactions for the broker
}
private void initViews(){
this.mListViewTransactions = (ListView)findViewById(R.id.tList);
}
#Override
protected void onResume() {
transactionSource.open();
super.onResume();
}
#Override
protected void onPause() {
transactionSource.close();
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
getMenuInflater().inflate(R.menu.view_transactions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_new) {
addTransaction();
return true;
} else if (id == R.id.switch_user) {
// Intent intent = new Intent(this, ViewUsers.class);
// startActivity(intent); // start user activity
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class TransactionAdapter extends BaseAdapter {
public static final String TAG = "ListTransactionsAdapter";
private List<TransactionModel> mItems;
private LayoutInflater mInflater;
public TransactionAdapter(Context context, List<TransactionModel> listBrokers) {
this.setItems(listBrokers);
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return (getItems() != null && !getItems().isEmpty()) ? getItems().size() : 0 ;
}
#Override
public TransactionModel getItem(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null ;
}
#Override
public long getItemId(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position).getId() : position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if(v == null) {
v = mInflater.inflate(R.layout.capital_row_layout_transaction, parent, false);
holder = new ViewHolder();
holder.txtCapitalTransactionDate = (TextView) v.findViewById(R.id.capital_broker_date_transaction);
holder.txtCapitalTransaction = (TextView) v.findViewById(R.id.capital_broker_add_transaction);
holder.txtCapitalTransactionAmount = (TextView) v.findViewById(R.id.capital_broker_add_amount);
v.setTag(holder);
}
else {
holder = (ViewHolder) v.getTag();
}
// fill row data
TransactionModel currentItem = getItem(position);
if(currentItem != null) {
holder.txtCapitalTransactionDate.setText(currentItem.getTransactionDate());
holder.txtCapitalTransaction.setText(String.valueOf(currentItem.getTransactionDescription()));
holder.txtCapitalTransactionAmount.setText(String.valueOf(currentItem.getTransactionAmount()));
}
return v;
}
public List<TransactionModel> getItems() {
return mItems;
}
public void setItems(List<TransactionModel> mItems) {
this.mItems = mItems;
}
class ViewHolder {
TextView txtCapitalTransactionDate;
TextView txtCapitalTransaction;
TextView txtCapitalTransactionAmount;
}
}
//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 know this question has been asked a couple of times before and i tried all of the suggestions there and i still cant refresh my list view after i add a new item to the list
can anyone please try to explain how can i do it?
thnaks
this is the code of the adding:
public class MainActivity extends ListActivity {
private DBHandler dataBase;
private ArrayList<Movies> list;
private ArrayAdapter<Movies> adapter;
private ListView lv;
private ImageButton addMovie;
private Intent intent;
final static int FLAG_FOR_ADDING=1;
final static int FLAG_FOR_EDITING=2;
final static int FLAG_FROM_MENU=3;
private int selected_movie;
private String the_movie;
private String movie_title;
private String movie_description;
private String movie_url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
dataBase = new DBHandler(MainActivity.this);
// by pressing this button the user will get instructions about how to use this application
Button start = (Button)findViewById(R.id.how_to_start);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(MainActivity.this, "Press the plus button for adding a movie or the menu button for the menu", Toast.LENGTH_LONG).show();
}
});
// by pressing this button, the menu of this application will open
ImageButton menu = (ImageButton)findViewById(R.id.menu_context);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openOptionsMenu();
}
});
addMovie = (ImageButton)findViewById(R.id.add_movie);
addMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerForContextMenu(addMovie);
openContextMenu(addMovie);
}
});
// the array list is getting the movies from the database
list = dataBase.getAllMovies();
// here i am setting the adapter that will handle the list
adapter = new ArrayAdapter<Movies>(MainActivity.this, R.layout.row,list);
// i am getting a default xml
lv=getListView();
// i am connecting between the list and the adapter
lv.setAdapter(adapter);
// by short pressing an item on the list the user will move to the edit_a_movie page
// in order to edit the movie
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
intent = new Intent(MainActivity.this,Edit_A_Movie.class);
// i am sending the information of the item that been pressed to the edit_a_movie page
// the id, title,description and the url_photo
intent.putExtra("item_id", list.get(position).getId());
intent.putExtra("item_title", list.get(position).getTitle().toString());
intent.putExtra("item_description", list.get(position).getDescription().toString());
intent.putExtra("item_url", list.get(position).getPhoto_url().toString());
startActivityForResult(intent, FLAG_FOR_EDITING);
}
});
// a long press on a movie in the list will open a context menu for deleting or editing the item
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// i am getting the information of the movie that was pressed
selected_movie = list.get(position).getId();
the_movie = String.valueOf(selected_movie);
movie_title = list.get(position).getTitle().toString();
movie_description = list.get(position).getDescription().toString();
movie_url = list.get(position).getPhoto_url().toString();
// i register to a context menu
registerForContextMenu(lv);
openContextMenu(lv);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
// by pressing the exit option, the user will exit the application
case R.id.menu_exit:
finish();
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
break;
// this option will delete all the movies from the list
case R.id.menu_delete:
dataBase.deleteAllMovies();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// if the user will press the menu button he will get the menu and if he will press
// the plus button he will get 2 options: 1. move to the edit a movie page
// 2. move to the search a movie from the Internet page
// if the user will press a long press on a movie he will get 2 options:
//1. update the movie
//2. delete the movie
if(v.getId() == R.id.menu_context){
getMenuInflater().inflate(R.menu.main, menu);
}
else if (v.getId() == R.id.add_movie){
getMenuInflater().inflate(R.menu.aad_menu, menu);
}
else {
getMenuInflater().inflate(R.menu.edit_or_delete, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
// selecting this option will exit the application
case R.id.menu_exit:
finish();
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
break;
// this option will delete all the movies from the list
case R.id.menu_delete:
dataBase.deleteAllMovies();
break;
// this option will move the user to the edit a movie page
case R.id.move_to_edit:
intent = new Intent(MainActivity.this,Edit_A_Movie.class);
startActivityForResult(intent, FLAG_FOR_ADDING);
break;
// this option will get the user move to the add a movie from the Internet page
case R.id.move_to_search:
break;
// if the user will press on a movie he will be able to update the movie or delete it
//this option will delete the movie
case R.id.delete_menu_movie:
dataBase.deleteMovie(the_movie);
break;
// this option will move the user to the edit_a_movie page
case R.id.edit_menu_movie:
intent = new Intent(MainActivity.this,Edit_A_Movie.class);
// i am sending the information of the pressed movie
intent.putExtra("item_id",selected_movie);
intent.putExtra("item_title", movie_title);
intent.putExtra("item_description", movie_description);
intent.putExtra("item_url", movie_url);
startActivityForResult(intent, FLAG_FROM_MENU);
break;
default:
break;
}
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// this is the info i am getting from the edit_a_movie page in order to put it in the database
// i am using it to add a new movie to the list
if(requestCode==FLAG_FOR_ADDING && resultCode==RESULT_OK){
// this is the info i received
String title_from_adding = data.getStringExtra("user_title");
String description_from_adding = data.getStringExtra("user_desciption");
String url_from_adding = data.getStringExtra("user_url");
// here i am putting the info in the database
dataBase.addMovie(title_from_adding, description_from_adding, url_from_adding);
// in case that the user pressed the cancel button he will get a massage
} else if
(requestCode==FLAG_FOR_ADDING && resultCode==RESULT_CANCELED){
Toast.makeText(MainActivity.this, "No movie has been added", Toast.LENGTH_LONG).show();
}
// i am using the info from the edit_a_movie page in order to update a movie
else if
(requestCode==FLAG_FOR_EDITING && resultCode==RESULT_OK ){
String position_from_editing = data.getStringExtra("position");
String title_from_editing = data.getStringExtra("user_title");
String description_from_editing = data.getStringExtra("user_desciption");
String url_from_editing = data.getStringExtra("user_url");
// the database is being updating
dataBase.updateMovie(position_from_editing, title_from_editing, description_from_editing, url_from_editing);
}
// this case is for editing the movie that was long pressed
else if
(requestCode==FLAG_FROM_MENU && resultCode==RESULT_OK){
// i am receiving the updated information from the edit_a_movie page
String position_from_menu = data.getStringExtra("position");
String title_from_menu = data.getStringExtra("user_title");
String description_from_menu = data.getStringExtra("user_desciption");
String url_from_menu = data.getStringExtra("user_url");
//the database is being updating with the new information
dataBase.updateMovie(position_from_menu, title_from_menu, description_from_menu, url_from_menu);
}
}
}
You should call notifyDataSetChanged on the adapter.
After dataBase.addMovie(..)
adapter.notifyDataSetChanged();
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.