I'm new to android development having some problems. I created a list view that is based on the user input. User has to enter a category in a dialog box and then it's added into the list. Works like a charm. The question is how do I retain those categories once the user exits from an app and starts it again ? When the user starts the app, the list is blank. Do I have to create a preference screen or something to save what the user types ? Here is my code:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
#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()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
*/
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity
You can save it in SQLite DB, use CursorAdapter for your list view.
If the amount of data you want to save is relatively small you can use SharedPreferences to save the String data in your onClick method.
#Override
public void onClick(DialogInterface dialog, int which) {
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
// Add all string data to List<String> listItem
listItem.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
When the user leaves your activity, use the onStop() callback method to save your List<Strings> and store it through SharedPreferences.
#Override
private void onStop() {
super.onStop();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(getResources().getString(R.string.list_of_strings), new HashSet<String>(listItem));
editor.commit;
}
Using the onStart() callback, initialize your List and SharedPreferences. When the user navigates to your activity, your list will be reinitialized when it was saved via onStop().
Finally, iterate through your list, add your items to your ArrayList', create yourArrayAdapter` and set it to your list.
#Override
private onStart(){
super.onStart();
SharedPreferences mSharedPreferences;
mSharedPreferences = this.getApplicationContext().getSharedPreferences("MyPreferences", 0);
List<String> listItems = new ArrayList<String>(mSharedPreferences.getStringSet("ListOfStrings", null));
ListIterator li = listItem.listIterator(0);
while (li.hasNext()) {
newStatusList.add((String)li.next());
}
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
Related
In this application, I have a listview and a sqlitedatabase. There is a floating action button which on clicking displays a dialog box containing two edittext one for name and another for number. The problem is that the after clicking on the add option of the dialog box the entry is not shown on the listview. But when the activity is destroyed and onCreate is called again on the activity , the entry is shown.
I tried using adapter.notifyDataSetChanged() but it doesn't work. The code is shown below :
Code
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
Cursor cursor=manager.fetch();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),
R.layout.row_item, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
/*adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();*/
insertData(name.getText().toString(),phone.getText().toString());
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
Some of the statements are commented because I tried to get the desired result but couldn't get it.
There's a couple things here you have to change. Taking a look at this code:
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) && !TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(), "Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
When you click the "Add" button, right away you call adapter.notifyDataSetChanged();. In your case, you are only supposed to call that after you have added items to listView, but you haven't added anything yet.
You insert into your database using manager.insert(name.getText().toString(), phone.getText().toString());, but you don't update listView with your newly added data. You need to insert that data to the database, and then also add that data to listView.
Now you can call adapter.notifyDataSetChanged();.
I would recommend that when you want to insert into your database, create a method which will insert the data, add the new data to the listView, and then tell the adapter to refresh.
Edit
Regarding your recent edit, there's still a few things that need to be taken care of.
You should not have listView.setAdapter(adapter) in the method. You had it right the first time (in onCreate() but before the dialog builder).
You call manager.insert(fname,phnumber);, but still do not add the newly inserted data to listView.
Here's pseudocode for what you should have in your method:
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
// Code to add the data you just inserted into the manager above to `listView`.
adapter.notifyDataSetChanged();
}
Remember, adapter.notifyDataSetChanged(); only updates listView if there's changes to listView, and as of right now you haven't added/deleted/modified listView.
After you insert the entries in your database, you should fetch the data again so that your list has the newest entry. So you can either modify your code to be able to add a data point to the list you are passing to the adapter or refetch the data from the database after insertions and before notifyDatasetChanged().
i have did some changes into the code please try it and let me know if it is helpful or not
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),R.layout.row_item, cursor, from, to, 0);
//adapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
Cursor cursor = manager.fetch();
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}}
Try to use notifyDataSetChanged after insert operation. In all place where you call(try to call) notify manager data isn't change yet.
//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
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();
I'm creating this ListView with the option to add new item through menu, but I already read all the codes/examples here in Stackoverflow and I was not able to adapt my code with them.
I tried to use the onSaveInstanceState but I was not able to start the application when I try to use in onCreate.
What is the best way to save this list with the new values when entered?
Code that I tried to use:
protect void onCreate(...)
{
...
if (savedInstanceState.containKey(MYLISTKEY))
{
alllist = savedInstanceState.getStringArrayList(MYLISTKEY);
} else {
}
}
Here is my code:
public class MainActivity extends Activity {
private static final String MYLISTKEY = "myListItems";
final Context context = this;
private ListView mainListView;
private ArrayAdapter<String> listAdapter;`
private ArrayList<String> allList = new ArrayList<String>();
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putStringArrayList(MYLISTKEY, allList);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.mainListView);
// TODO: Populate explicitely your list
// Create and populate a List of planet names.
String[] listitems = new String[] { };
allList.addAll(Arrays.asList(listitems));
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, allList);
// Add more planets. If you passed a String[] instead of a List<String>
// into the ArrayAdapter constructor, you must not add more items.
// Otherwise an exception will occur.
listAdapter.add( "Item A" );
listAdapter.add( "Item B" );
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
}
#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;
}
/* (non-Javadoc)
* #see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
// Action Add Item to the listview
case R.id.action_add:
addListItem();
return true;
// Save list to SharedPreferences
default:
return super.onOptionsItemSelected(item);
}
}
// Add new item list when choose "New Item" on menu
private void addListItem() {
// get prompt.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompt, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompt.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
listAdapter.add(userInput.getText().toString());
listAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
As your comment // Save list to SharedPreferences suggests you should save the data in the list to some kind of persistent storage and not rely on the savedInstanceState bundle.
See the Android dev docs note re. what to store in onSaveInstanceState:
Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the
activity (the state of the UI)—you should never use it to store
persistent data. Instead, you should use onPause() to store persistent
data (such as data that should be saved to a database) when the user
leaves the activity.
http://developer.android.com/guide/components/activities.html
In my main class i've a button to call a class which shows a dialog box with an edittext. My problem is this - Main activity is not getting edittext value at the first run, if i run it for a second time, i get the old edittext value.
It seems the main activity class executes the full block of code and returns a previous value which is stored in the class, i've tried many methods including shared preference.
MainActivity.java
public class MainActivity extends Activity {
EditText comment_et,input_et;
Spinner spinner;
Button addbutton,reportbut;
String input_string,date,time,comment,item;
TextView date_tv,time_tv;
String temp[];
Datas datatemp;
String savedinput;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences prefs = getSharedPreferences("myprefs", 0);
savedinput= prefs.getString("KEY_SAVEDINPUT","");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)findViewById(R.id.spin1);
input_et = (EditText)findViewById(R.id.input_et);
addbutton = (Button)findViewById(R.id.addbutton);
reportbut = (Button)findViewById(R.id.report);
comment_et = (EditText)findViewById(R.id.comment_et);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
date_tv = (TextView)findViewById(R.id.date_tv);
time_tv = (TextView)findViewById(R.id.time_tv);
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
date = ""+mDay+"/"+mMonth+1+"/"+mYear;
time = ""+mHour+":"+mMinute;
date_tv.setText(date);
time_tv.setText(time);
int max_id = db.getDatasCount();
for(int i = 1; i<max_id+1 ;i++)
{
datatemp = db.getItemOnly(i);
String s = datatemp._item.toString();
list.add(" "+ s);
}
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true);
System.out.println("main : " +savedinput);
}
});
reportbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
startActivity(i);
}
});
spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
item = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Button submit = (Button)findViewById(R.id.save);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
comment = comment_et.getText().toString();
System.out.println("comment:"+comment);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addData(new Datas(item, comment, date, time));
Toast.makeText(getApplicationContext(), "Data Submitted Successfully",
Toast.LENGTH_LONG).show();
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Datas> datas = db.getAllDatas();
for (Datas d : datas) {
String log = "Id: "+d.getID()+" ,Item: " + d.getItem() + " ,Comment: " + d.getComment() + " ,Date: " + d.getDate() + ",Comment: " + d.getTime();
// Writing Contacts to log
Log.d("Item: ", log);
}
}
});
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#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);
return true;
}
}
AlertDialogManager.java
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
String savedinput;
public void showAlertDialog(final Context context, String title, String message,
Boolean status)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
//setting input
final EditText input = new EditText(context);
alertDialog.setView(input);
// saving input to a string
savedinput = input.getText().toString();
System.out.println(savedinput);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("KEY_SAVEDINPUT", savedinput);
editor.commit();
System.out.println("from class "+savedinput);
}
});
// Showing Alert Message
alertDialog.show();
}
String getItem()
{
return savedinput;
}
}
and here is my logcat, just for further clarification
02-01 13:48:43.372: I/System.out(897): main : firstexecute
02-01 13:48:46.942: W/KeyCharacterMap(897): No keyboard for id 0
02-01 13:48:46.942: W/KeyCharacterMap(897): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-01 13:48:49.532: I/System.out(897): from class secondexecute
You have several issues here.
You shouldn't read savedValue in onCreate, you should do it only when you actually use it. See #ρяσѕρєяK answer.
alert.showAlertDialog is non blocking. So after dialog is shown line System.out.println("main : " + savedInput); is executed. It doesn't wait for your input. So you should call some other action beside saving to shared preferences on dialog's ok buttonn. This action should invoke logic that should happen after user entered some text in the dialog.
Update
public void showAlertDialog(final Context context, String title, String message,
Boolean status, final Spinner spinner)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
//setting input
final EditText input = new EditText(context);
alertDialog.setView(input);
// saving input to a string
savedinput = input.getText().toString();
System.out.println(savedinput);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
// do whatever you want with spinner and savedInput here.
}
});
// Showing Alert Message
alertDialog.show();
}
onClick to show dialog:
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true, (Spinner) findViewById(R.id.spin1));
Update 2
Apparently you need to add new item to your spinner adapter. For this you can create list of all items and pass this list along with adapter to dialog. When user enters string and press OK button onClick method adds this string to the list and call notifyDataSetChanged to update UI:
Add this in MainActivity:
List<String> spinnerItems;
In onCreate:
spinnerItems = new ArrayList<String>();
adapter = enw ArrayAdapter<String>(this, 0, spinnerItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Pass spinnerItems and adapter to showAlertDialog:
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true, spinnerItems, adapter);
And finally add text to list and notify adapter:
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
spinnerItems.add(savedInput);
adapter.notifyDataSetChanged();
}
});
you will need get latest value on Button click instead of onCreate to get latest value from SharedPreferences as :
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true);
savedinput= prefs.getString("KEY_SAVEDINPUT",""); //<<< get value here
System.out.println("main : " +savedinput);
}
});
or you will try to get value from onResume of Activity
This
savedinput = input.getText().toString();
is evaluated when it is run. Not when you call getItem(). The value you'll get is what it was, in this case, before the alert was displayed.
same logic goes for
savedinput= prefs.getString("KEY_SAVEDINPUT","");