I am making an android app that asks for the users to select a country via spinner.
When the user opens the app first time, user selects a country from list.
Then when app opens second time, I want the same country to be selected. I don't want user to select the country every time the app is opened.
How to do that?
You can use SharedPreferences to store the selection the first time that the user selects a country, and then use SharedPreferences again for the app to remember the selection, when the user returns a second time.
To store the selection in a SharedPrefence:
SharedPreferences.Editor editor = getPreferences(0).edit();
int selectedPosition = yourSpinner.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.apply();
To load the selection onto the spinner when reusing the app:
SharedPreferences prefs = getPreferences(0);
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
Hope this solves your issue :)
Try this one
String citySelected
final CharSequence[] items = {" abc ", " def ", " ghi ", " jkl ", " mno ",
" pqr ", " stu ",
" vwzyz "};
List<String> lanSelected = new ArrayList<>();
final boolean[] checkedItems = new boolean[]{false, false, false, false, false, false, false, false};
List<String> temp = new ArrayList<>();
for (int o = 0; o < items.length; o++) {
temp.add(items[o].toString());
}
final List<Integer> seletedItems = new ArrayList();
if (citySelected.equals("") || citySelected == null) {
} else
lanSelected = Arrays.asList(citySelected.split(","));
if (lanSelected.size() > 0) {
for (int p = 0; p < lanSelected.size(); p++) {
String x = lanSelected.get(p);
int xpos = temp.indexOf(x);
if (xpos != -1) {
checkedItems[xpos] = true;
seletedItems.add(xpos);
}
}
}
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(context);
}
// arraylist to keep the selected items
AlertDialog dialog = builder
.setTitle("city")
.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
seletedItems.add(indexSelected);
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove it
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String city = "";
for (int i = 0; i < seletedItems.size(); i++) {
if (i == seletedItems.size() - 1) {
city = city + items[Integer.parseInt(seletedItems.get(i).toString())];
} else {
city = city + items[Integer.parseInt(seletedItems.get(i).toString())] + ",";
}
}
btn_city_todisplay.setText(city);
dialog.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
}).create();
dialog.show();
Use spinner method to show selected item
spinner.setSelection(position);
Here position is the last selected position
You can use sharedPreference to store the country you have chosen, then search the map and find the position of country in your array, finally use setSelection(int position)to set the default country
Related
I'm using alert dialog to show some records.those records are comming from db and display in Alertdialog.when user click on item i want to get item name to Log.this is my code.it show item as [test] but i want it showing as test
ArrayList arrayList and String [] categoryStrings initialized on top
List<Video> vd=Video.findWithQuery(Video.class, "select * from Video");
if (vd.size()>0) {
for (Video v : vd) {
arrayList.add(v.getTitle());
}
final List<String> list = Arrays.asList(arrayList.toString());
categoryStrings=new String[list.size()];
categoryStrings=list.toArray(categoryStrings);
AlertDialog.Builder alert = new AlertDialog.Builder(Editmedia.this);
alert.setTitle("Media List");
alert.setCancelable(false);
final int selected = 0; // or whatever you want
alert.setSingleChoiceItems(categoryStrings, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//onclick
String categoryString = categoryStrings[item];
Log.d("sel", " " + item+" "+categoryString);
edit();
}
});
alert.show();
log value showing
0 [test] i want it as test
Log
Try this, it should help
String categoryString = categoryStrings[item];
categoryString = categoryString.replaceAll("[\\p{Ps}\\p{Pe}]","");
Log.d("sel", " " +" "+categoryString);
[EDIT]
String categoryString = categoryStrings[item];
categoryString = categoryString.replace("[","");
categoryString = categoryString.replace("]","");
Log.d("sel", " " +" "+categoryString);
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Media List");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
arrayAdapter.clear();
for (int i = 0; i < list.size(); i++) {
Log.i(LOG_TAG, list.get(i));
arrayAdapter.add(list.get(i));
}
builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), list.get(which),
Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
I have one TextView with title All Post.I'm displaying the popup window click on TextView and populate list view with two items in popup window.And trying to implement this - whenever click on list view item that item will be display in TextView and previous TextView title All Post will be add in listview in the place of clickable item.But my listview is not update on dismiss the popup window.
Here is my code of popup window.
String[] values = new String[] { "All Post", "My Post", "R-Post"};
ArrayList<String> filter_PostType = new ArrayList<String>();
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
if(str_LastSelectionValue.equals("NoVal"))
{
editor.putString("filter_post_title","All Post");
editor.commit();
}
else
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
}
textSearch.setText(str_LastSelectionValue);
Log.e("", " textSearch.getText().toString().trim() = " +
textSearch.getText().toString().trim());
textSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
popup_searchview = new PopupWindow(CustomActionActivity.this);
View layout = getLayoutInflater().inflate(R.layout.allpostsearch_popup, null);
popup_searchview.setContentView(layout);
popup_searchview.setHeight(220);
popup_searchview.setWidth(250);
popup_searchview.setOutsideTouchable(true);
popup_searchview.setFocusable(true);
popup_searchview.setBackgroundDrawable(new BitmapDrawable());
popup_searchview.showAsDropDown(v);
filter_list = (ListView) layout.findViewById(R.id.filter_ListView);
arr = new ArrayList<String>(Arrays.asList(values));
filter_PostType.clear();
for (int i = 0; i < arr.size(); i++) {
String str_PostType = arr.get(i);
if (!str_PostType.equals(str_LastSelectionValue)) {
filter_PostType.add(str_PostType);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
filter_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedFromList = (filter_list.getItemAtPosition(position).toString());
editor.putString("filter_post_title", selectedFromList);
editor.commit();
textSearch.setText(selectedFromList);
popup_searchview.dismiss();
removeItemFromList(position);
filterPost_adapter.notifyDataSetChanged();
arr = new ArrayList<String>(Arrays.asList(values));
filter_PostType.clear();
for (int i = 0; i < arr.size(); i++)
{
String str_PostType = arr.get(i);
if (!str_PostType.equals(textSearch.getText().toString().trim()))
{
filter_PostType.add(str_PostType);
int filterSize = filter_PostType.size();
Log.e(" UnMatched ", " In ListItem Click filterSize = " + filterSize);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
}
});
}
});
Use something like this:
String[] values = new String[] { "All Post", "My Post", "R-Post"};
ArrayList<String> filter_PostType = new ArrayList<String>();
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "NoVal");
if(str_LastSelectionValue.equals("NoVal"))
{
editor.putString("filter_post_title","All Post");
editor.commit();
}
else
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
}
textSearch.setText(str_LastSelectionValue);
Log.e("", " textSearch.getText().toString().trim() = " +
textSearch.getText().toString().trim());
textSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
popup_searchview = new PopupWindow(CustomActionActivity.this);
View layout = getLayoutInflater().inflate(R.layout.allpostsearch_popup, null);
popup_searchview.setContentView(layout);
popup_searchview.setHeight(220);
popup_searchview.setWidth(250);
popup_searchview.setOutsideTouchable(true);
popup_searchview.setFocusable(true);
popup_searchview.setBackgroundDrawable(new BitmapDrawable());
popup_searchview.showAsDropDown(v);
filter_list = (ListView) layout.findViewById(R.id.filter_ListView);
if(!filter_PostType.isEmpty())
filter_PostType.clear();
for (int i = 0; i < values.length; i++) {
if (!values[i].equals(str_LastSelectionValue)) {
filter_PostType.add(values[i]);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
filter_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedFromList = (filter_list.getItemAtPosition(position).toString());
editor.putString("filter_post_title", selectedFromList);
editor.commit();
str_LastSelectionValue=selectedFromList;
textSearch.setText(selectedFromList);
popup_searchview.dismiss();
}
});
}
});
}
You don't need to change your adapter after user selects something because the next time user clicks the textview, you are making a new popup window with a new adapter.
If there is anything you don't understand, leave a comment.
Hope this helps :)
I have set up a dialog box with one edit text box. I used a set filter for max number of charactures allowed but I dont see an a filter for minimum. I added code to add "x" to entered text if the user enters less than 8 chars. Code compiles but crashes.
and throws Error is "string longer than 9". and gives (16 as piece.length()). could use some help solving
public void onClick(View item) {
final EditText input = new EditText(this);
switch (item.getId()) {
case R.id.textView1:
strEditText = Title1.getText().toString(); // OK
input.setText(strEditText);
input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(8) }); // Set max # of charactures for Input
for (int i = 0; i < strEditText.length(); i++) { //
String piece = strEditText; //
String toBeAdded = ""; //
if (piece.length() < 8) {
int length = piece.length();
toBeAdded = piece;
while (length < 8) {
toBeAdded = toBeAdded + "X";
length++;
}
} else if (piece.length() > 8) {
throw new IllegalArgumentException("Error, string longer than 9");
} else {
toBeAdded = piece;
}
strEditText = strEditText + toBeAdded;
}// return to for-loop //
new AlertDialog.Builder(ElsEditTitles.this)
.setTitle("Ttile").setView(input).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
strReturn = input.getText().toString();
Title1.setText(strReturn);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
break;
i Cant Understand Why You Put This For : for (int i = 0; i < strEditText.length(); i++)
For Example if EditText is 'abc' strEditText is 'abc' and that for repeats 3 Time.
in First Time toBeAdded = 'abcXXXXX' and when code "strEditText = strEditText + toBeAdded;" run strEditText = 'abcabcXXXXX' and when That for goes into 2nd loop its Already more than 8 character and throws your Error.
Sorry For My Bad English..
I have different categories of filters like id, name, gender, area, caste, religion. Now i want to use multiple choice filters showing checkboxes, how can i work out with multiple choice filters because there are many kind of filters so permutation & combination is worst for it.
currently i am done with single selection of filter (1 checkbox true at a time).
String str[] = new String[('Z' - 'A') + 1];
boolean selectedItems[] = new boolean[str.length];
protected ArrayList<CharSequence> selectedChars = new ArrayList<CharSequence>();
private AlertDialog alertBox;
private void showSpinner() {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
int a = 0;
for (char c = 'A'; c < 'Z'; c++) {
str[a++] = String.valueOf(c);
}
boolean[] checkedChars = new boolean[str.length];
int count = str.length;
for (int i = 0; i < count; i++)
checkedChars[i] = selectedChars.contains(str[i]);
alertBuilder.setTitle("Select Country");
alertBuilder.setCancelable(true);
alertBuilder.setMultiChoiceItems(str, selectedItems,
new OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked)
selectedChars.add(str[which]);
else
selectedChars.remove(str[which]);
}
});
alertBox = alertBuilder.create();
alertBox.show();
}
it will jst display the spinner with mulitple selection options.
I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing:
public String getEmployeeID() {
final CharSequence[] items = {"By ID", "By Name", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this);
builder.setTitle("Find Employee");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("Cancel")) {
dialog.cancel();
empid = "";
} else if(items[item].equals("By ID")) {
dialog.cancel();
final Dialog dialog2 = new Dialog(LibraryScreen.this);
dialog2.setContentView(R.layout.peopledialog);
dialog2.setTitle("Employee ID");
dialog2.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee ID");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00000002);//numbers
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 15;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral);
String newemp = "";
db.open();
Cursor c = db.getEmployee(emplid.getText().toString());
if(c.moveToFirst()) {
empid = c.getString(c.getColumnIndex("employeeid"));
} else {
Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show();
empid = "";
}
c.close();
db.close();
dialog2.dismiss();
}
});
Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
empid = "";
}
});
dialog2.show();
} else if(items[item].equals("By Name")) {
dialog.cancel();
final Dialog dialog1 = new Dialog(LibraryScreen.this);
dialog1.setContentView(R.layout.peopledialog);
dialog1.setTitle("Employee's Name");
dialog1.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee Name");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00002001);//cap words
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 50;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral);
String firstname = emplid.getText().toString();
String lastname = "";
String matchlist = "";
String temptext = "";
int matchcount = 0;
if(firstname.lastIndexOf(" ") <= 0) {
lastname = firstname;
firstname = "X";
} else {
lastname = firstname.substring(firstname.lastIndexOf(" ") + 1);
firstname = firstname.substring(0, firstname.lastIndexOf(" "));
}
db.open();
Cursor c1, c2;
String titletext = "";
if(firstname.length() > 0) {
c1 = db.getEmployeeByName(lastname, firstname);
if(c1.getCount() == 0) {
c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname");
if(c1.getCount() == 0) {
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
}
}
if(c1.getCount() > 0) {
do {
c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid")));
if(c2.moveToFirst()) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) {
titletext = "Top Brass";
} else {
titletext = "Senior VP";
}
} else {
titletext = "VP";
}
} else {
titletext = "Director";
}
} else {
titletext = "Senior Manager";
}
} else {
titletext = "Manager";
}
} else {
titletext = "Employee";
}
matchcount++;
matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|";
} while(c1.moveToNext());
}
} else {
empid = "";
}
if(matchcount == 0) {
db.close();
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
} else {
final CharSequence[] items = new CharSequence[matchcount + 1];
items[0] = "(Cancel)";
for(int i = 1; i <= matchcount; i++) {
items[i] = matchlist.substring(0, matchlist.indexOf("|"));
matchlist = matchlist.substring(matchlist.indexOf("|") + 1);
}
db.close();
AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this);
builder1.setTitle("Select Employee");
builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("(Cancel)")) {
dialog.cancel();
empid = "";
} else {
String wasted = items[item].toString();
empid = wasted.substring(0, wasted.indexOf(":"));
dialog.cancel();
}
}
});
AlertDialog alert1 = builder1.create();
alert1.show();
}
dialog1.dismiss();
}
});
Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
empid = "";
}
});
dialog1.show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
return empid;
}
I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO.
My question:
Is there a way to put this function somewhere that can be called from many different activities?
If so:
How do I do that?
How do I set the context for the dialog boxes for multiple activities?
How do I get the employee id back to the function that needs it?
I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short.
A little late to the party - but recorded for posterity:
Read up on the Application class:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml's tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.
Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app).
You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application
import android.app.Application;
public class MyApplication extends Application {
public void myGlobalBusinessLogic() {
//
}
}
Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="MyApplication">
Finally, when you need to get to your common function just do something like:
MyApplication application = (MyApplication) getApplication();
application.myGlobalBusinessLogic();
If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.