Edit Text inside Alert Dialog Builder - java

I have an Alert Dialog inside a Fragment:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
com.yanay.yanay.apps.odds.R.style.AppCompatAlertDialogStyle);
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_numberpicker, null));
View view = inflater.inflate(R.layout.dialog_numberpicker, null);
final EditText editText = (EditText) view.findViewById(R.id.numberpicked);
if (editText.getText().toString() != null){
numberpicked = editText.getText().toString();
Log.d("Text Picked", numberpicked);}
Boolean reverse = true;
String title = "";
String dialogMessage = "";
String buttonTitle = "";
if (!didStart && replies == 0) {
buttonTitle = "Choose Odds";
dialogMessage = ping.getBody() + " Challenged You! Odds you: " + ping.getNum() + ". Choose out of:";
title = "New Challenge";
message = numberpicked;
}
builder.setTitle(title);
builder.setMessage(dialogMessage);
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
Log.d("DidStart", didStart.toString());
Log.d("Replies", replies.toString());
if (replies < 3) {
builder.setPositiveButton(buttonTitle,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Pinger pinger = mPingerAdapter.getItem(position);
// pingSomeone(pinger);
final Context context = getActivity();
EditText choosenNumber = (EditText) getView().findViewById(R.id.numberpicked);
Bundle data = new Bundle();
data.putString(PingerKeys.ACTION, GcmAction.PING_CLIENT);
String from = ping.getFrom();
data.putString(PingerKeys.TO, ping.getFrom());
//PingerKeys.NUM = "3333";
data.putString(PingerKeys.NUM, message);
Log.d("LOOK HERE ####", message);
data.putString(PingerKeys.SENDER,
mDefaultSharedPreferences.getString(RegistrationConstants.TOKEN, "Test"));
try {
GoogleCloudMessaging.getInstance(context)
.send(FriendlyPingUtil.getServerUrl(getActivity()),
String.valueOf("6969"), data);
AnalyticsHelper.send(context, TrackingEvent.PING_SENT);
} catch (IOException e) {
Log.w(TAG, "Could not ping client.", e);
}
}
});}
builder.show();
replies = replies + 1;
}
Number Picked is always null. How can I get the value of the text entered into the edit text. The dialog layout is just a linear layout with an edit text inside.

Here is the way to get the EditText value from Dialog
LayoutInflater layoutInflater = LayoutInflater.from(YourActivity.this);
View rootView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(YourActivity.this);
alertDialogBuilder.setView(rootView);
final EditText yourEditText= (EditText) rootView .findViewById(R.id.edittext);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get the `EditText` value
Toast.makeText(YourActivity.this,"EditText value" + yourEditText.getText(),Toast.LENG_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();

Related

Set text Length of alert dialog in Android studio

How do I set the max of how many characters can be entered. So now the user can enter a lot in the alertdialog While it should have the max. it's not like XML. That would have been easier, any tips for this alert dialog?
private void RequestNewGroup()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialog);
builder.setTitle("Enter Group Name ");
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
builder.setView(groupNameField);
builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
String groupName = groupNameField.getText().toString();
if (TextUtils.isEmpty(groupName))
{
Toast.makeText(MainActivity.this, "Please write Group Name...", Toast.LENGTH_SHORT).show();
}
else
{
CreateNewGroup(groupName);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
builder.show();
}
You need to add a InputFilter to your EditText
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
// ### -> max length
groupNameField.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(###) });

I want to add same value in shared preference each time click button

My question is i have a list of food item. when user press add button to add the dish i am saving this dish name in shared preference. but when i press the same dish twice in shared preference should show 2 dishes with the same name. but each time i press same dish its showing me only one dish. this is my code below.
public class Cafetaria extends AppCompatActivity {
String title;
ListView listView;
View customNav;
public String value,secdish,thrDish,frthDish;
public String Drink,Drink2,Drink3,Drink4;
String selectedDrink;
Dialog ViewDialog;
TextView tv_foodtype,tv_drink;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cafetaria);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
title = getIntent().getStringExtra("option");
getSupportActionBar().setTitle(title);
ActionBar actionBar = getSupportActionBar();
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
customNav = LayoutInflater.from(this).inflate(R.layout.food_actionbar_layout, null); // layout which contains your button.
actionBar.setCustomView(customNav, lp);
actionBar.setDisplayShowCustomEnabled(true);
customNav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewDialog = new Dialog(Cafetaria.this);
ViewDialog.setContentView(R.layout.activity_order_detail);
ViewDialog.setTitle("Your Order Details");
tv_foodtype = (TextView)ViewDialog.findViewById(R.id.nameuser);
tv_drink = (TextView)ViewDialog.findViewById(R.id.passnum);
button = (Button)ViewDialog.findViewById(R.id.okBtn);
ViewDialog.show();
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
value=(mSharedPreference.getString("firstDish", ""));
Drink=(mSharedPreference.getString("selectedDrinks", ""));
Drink2=(mSharedPreference.getString("selectedDrinks1", ""));
Drink3=(mSharedPreference.getString("selectedDrinks2", ""));
Drink4=(mSharedPreference.getString("selectedDrinks3", ""));
secdish=(mSharedPreference.getString("secdish", ""));
thrDish=(mSharedPreference.getString("thirdDish", ""));
frthDish=(mSharedPreference.getString("fourtDish", ""));
tv_foodtype.setText("Main Dishes"+ " \n"+value + " \n" + secdish +"\n"+thrDish+"\n"+frthDish);
tv_drink.setText("Drink"+" \n"+Drink + " \n" + Drink2 +"\n"+Drink3+"\n"+Drink4);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewDialog.dismiss();
}
});
}
});
listView =(ListView)findViewById(R.id.listView);
Drawable chic = this.getResources().getDrawable(R.drawable.chicktikka);
final Drawable plus = this.getResources().getDrawable(R.drawable.plus);
Drawable minus = this.getResources().getDrawable(R.drawable.minus);
ArrayList<FoodItemData> listofItem = new ArrayList<>();
FoodListViewAdapter listViewAdapter= new FoodListViewAdapter(this,R.layout.item_layout,listofItem);
listView.setAdapter(listViewAdapter);
listofItem.add(new FoodItemData("Chicken Tikka","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Onion Bhaji","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Chicken Pizza","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Chicken Masala","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR1)
public void plusClick(View v)
{
if (listView.getPositionForView(v)==0) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("firstDish","Chicken Tikka");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Please Choose your drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
//Define the AlertDialog positive/ok/yes button
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();
}
});
//Define the Neutral/Cancel button in AlertDialog
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 1) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("secdish","Onion Bhaji");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
//Define the AlertDialog positive/ok/yes button
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks1",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 2) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("thirdDish","Chicken Pizza");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks2",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 3) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("fourtDish","Chicken Masala");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
//selectedItems.remove(which);
selectedItems.add(which);
}
}
});
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks3",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
}
public void minusClick(View v)
{
if (listView.getPositionForView(v)==0) {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("firstDish").commit();
mSharedPreference.edit().remove("selectedDrinks").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==1)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("secDish").commit();
mSharedPreference.edit().remove("selectedDrinks1").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==2)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("thirdDish").commit();
mSharedPreference.edit().remove("selectedDrinks2").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==3)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("fourtDish").commit();
mSharedPreference.edit().remove("selectedDrinks3").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
super.onResume();
if (getSupportActionBar() != null){
getSupportActionBar().setTitle(title);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return false;
}
#Override
protected void onRestart() {
super.onRestart();
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("firstDish").commit();
mSharedPreference.edit().remove("selectedDrinks").commit();
mSharedPreference.edit().remove("selectedDrinks1").commit();
mSharedPreference.edit().remove("selectedDrinks2").commit();
mSharedPreference.edit().remove("selectedDrinks3").commit();
mSharedPreference.edit().remove("secdish").commit();
mSharedPreference.edit().remove("thirdDish").commit();
mSharedPreference.edit().remove("fourtDish").commit();
}
}`
This is the result I am getting. I press this dish twice and its shown only once. It should be shown twice the same dish name. Please Guide.
The code is really long to follow on here. But speaking generally, do you save each dish with different key-value pair? Maybe think about such solution. OR you could store the dishes in an array, which can be stored in Shared prefs, and once you want to see your dishes, just read out the Array List and display the items inside it.
You store the String into an Array, whenever you want to do it in your code. It's just like mArrayList.add("String"); and then you can update yuor SharedPrefs the same you already do, just check the URL on how to store ArrayList to SharedPrefs. Would be a cleaner solution in my view.
Here you can see how to store ArrayList in SharedPreferences:
Save ArrayList to SharedPreferences
And the once you want to display the items from ArrayList, you pull ArrayList from SharedPrefs and display them in AlertDialog ListView.
And here it is explained how to display Array Items in AlertDialog:
How can I display a list view in an Android Alert Dialog?

Sending alert dialog entry to mysql database

Am new to android and i have successfully manged to show data from mysql database in a list and set an alert dialog for when an item is clicked.The Alert dialog has to take in a comment about the item clicked and send it to the mysql database but am stuck at making the connection.
Here is my code
public void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String fname = c.getString(TAG_FNAME);
String lname = c.getString(TAG_LNAME);
String idnum = c.getString(TAG_IDNUM);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_FNAME,fname);
persons.put(TAG_LNAME,lname);
persons.put(TAG_IDNUM,idnum);
personList.add(persons);
}
final ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, personList, R.layout.list_activity,
new String[]{TAG_ID,TAG_FNAME,TAG_LNAME,TAG_IDNUM},
new int[]{R.id.id, R.id.textViewFname, R.id.textViewLname,R.id.textViewIdnum}
);
list.setAdapter(adapter);
//alert dialog
//Create onclick listener class
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Alert id: "+TAG_IDNUM); //Set Alert dialog title here
alert.setMessage("Enter Your Comment here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(context);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// convert the input to a string and show in a toast.
String srt = input.getEditableText().toString();
Toast.makeText(SearchActivity.this,"Commenting Added", Toast.LENGTH_LONG).show();
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(SearchActivity.this,"Commenting cancled",Toast.LENGTH_LONG).show();
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
// End of onClick(View v)
}
});}
catch (JSONException e){}
}
So i managed to come up with the following but the variables am sending to the php file don't seem to be getting there.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
final String id_number =((TextView)view.findViewById(R.id.textViewIdnum)).getText().toString();
alert.setTitle("Alert id: "+id_number); //Set Alert dialog title here
alert.setMessage("Enter Your Comment here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(context);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// convert the input to a string and show in a toast.
String reason = input.getEditableText().toString();
Toast.makeText(SearchActivity.this,"Commenting...", Toast.LENGTH_LONG).show();
final String reason_key = input.getText().toString().trim();
//final String id_number_key = textview;
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.RESULT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(SearchActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SearchActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
});
Map<String,String> params = new HashMap<String, String>();
params.put(TAG_IDNUM,id_number);
params.put(reason_key,reason);
RequestQueue requestQueue = Volley.newRequestQueue(SearchActivity.this);
requestQueue.add(stringRequest);
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(SearchActivity.this,"Commenting cancled",Toast.LENGTH_LONG).show();
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
// End of onClick(View v)
}
});}
catch (JSONException e){}
}

Use only one AlertDialog for a ListView

I have a list view with 5 items. If i click on an item, it start an AlertDialog that ask me if i want to download the file. Each item, have a different url download.
Instead of create 5 AlertDialog, can i just create a single AlertDialog and start the correct download url on item selected?
public class MapsListActivity extends Downloader implements OnItemClickListener{
private static final File MAP4 = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map4.map");
private static final File MAP3 = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map3.map");
private static final File MAP2 = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map2.map");
private static final File MAP = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map.map");
ListView listView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String osmdroidFolder = "/osmdroid/";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myOsmdroidFolder = new File(extStorageDirectory + osmdroidFolder);
myOsmdroidFolder.mkdir();
String tilesFolder = "/osmdroid/tiles/";
File myTilesFolder = new File(extStorageDirectory + tilesFolder);
myTilesFolder.mkdir();
listView = (ListView) findViewById(R.id.mapsList);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
switch (position){
case 0:{
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
break;
case 1:{
if (MAP.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
case 2:{
if (MAP2.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
case 3:{
if (MAP3.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
case 4:{
if (MAP4.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
}
}
protected void DialogDownload() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Maps not present. Would you like to download ?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
/* functions that start the download
downloadmap();
downloadmap2();
downloadmap3();
downloadmap4();
*/
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public void DialogDownLoad(String message,int pos)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("title");
// set dialog message
alertDialogBuilder.setMessage(message)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
if(pos == 0){
// call downloadMap1();
}
if(pos == 1){
// call downloadMap2();
}
......................
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
............... //your code
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
and in your onItemClick() method
#Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
message = "Your url";
DialogDownload(message,pos);
}

Code breaks at AlertDialog creation. I think I have Context wrong...?

i can't seem to figure out why my app/code is crashing in this section. Any help would be appreciated. I think the problem lies on the creation of an AlertDialog in the else if statement.
Basically, this method is called on first launch of the application and asks the user to choose between two options: OCPS and Other. When OCPS is chosen, a SharedPreference is set. When other is selected, an AlertDialog with text box should pop up, allowing the user to input their own local URL, which is then saved to the SharedPreference.
Full code is available here: https://github.com/danielblakes/progressbook/
code follows:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstrun = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getBoolean(
"firstrun", true);
if (firstrun) {
new AlertDialog.Builder(this).setTitle("First Run").show();
pickDistrict(this);
getSharedPreferences("com.danielblakes.progressbook", MODE_PRIVATE)
.edit().putBoolean("firstrun", false).commit();
}
else {
String saved_district = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getString(
"district", null);
startupWebView(saved_district);
}
}
public Dialog pickDistrict(final Context context) {
AlertDialog.Builder districtalert = new AlertDialog.Builder(context);
districtalert
.setTitle(R.string.choose_district)
.setItems(R.array.districts,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == 0) {
String district_site = "https://parentaccess.ocps.net/General/District.aspx?From=Global";
startupWebView(district_site);
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString("district",
district_site).commit();
} else if (i == 1) {
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
customdistrict
.setTitle(
R.string.custom_district_title)
.setMessage(
R.string.custom_district_message);
final EditText input = new EditText(
getParent());
customdistrict.setView(input);
customdistrict
.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
String custom_url = input
.getText()
.toString();
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString(
"district",
custom_url)
.commit();
}
});
customdistrict
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
return;
}
}).show();
}
}
}).show();
return districtalert.create();
}
}
Change
AlertDialog.Builder customdistrict = new AlertDialog.Builder(this);
to
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
also,
final EditText input = new EditText(getParent());
needed to be changed to
final EditText input = new EditText(context);

Categories