I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
I only want my AlertDialog to be dismissed when certain conditions are met (when name and surname given are valid) - else it should always be on top of the parent view. My code is this:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final TextView instructions = new TextView(this);
instructions.setText(R.string.alert_enter_data);
final EditText name = new EditText(this);
name.setHint(R.string.name);
final EditText surname = new EditText(this);
surname.setHint(R.string.surname);
LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(instructions);
ll.addView(name);
ll.addView(surname);
alert.setView(ll);
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1)) {
dialog.dismiss();
}
}
});
final AlertDialog alert_dialog = alert.create();
alert_dialog.setCanceledOnTouchOutside(false);
alert_dialog.show();
With this code the AlertDialog disappears when the button is pressed, regardless of the input text. I then tried this:
alert_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
String email_txt = email.getText().toString();
String cellphone_txt = cellphone.getText().toString();
String postcode_txt = postcode.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1) && (email_txt.length() > 4)) {
if (debug_mode) {Log.i(TAG,"clause 1");}
String data_to_upload = name_txt + ", " + surname_txt + ", " + email_txt + ", "+ cellphone_txt + ", " + postcode_txt + "\n";
// upload_to_github(data_to_upload);
alert_dialog.dismiss();
}
}
});
}
});
But this way I get not Button at all. The Alert Dialog only contains the EditText fields.
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
and
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
both are different buttons.
try
Button b = alert.getButton(AlertDialog.BUTTON_NEUTRAL);
I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.
I have 2 EditTexts that get a String and when the Button is clicked it converts char of this String to int. It then sums all int of chars and when sum of int is odd (totals&1 == 0) a Dialog shows "that is odd". And after else, the second Dialog shows "that is even". I need to set AlertDialog to show that.
final EditText ed1 = (EditText) findViewById(R.id.edtFather);
final EditText ed2 = (EditText) findViewById(R.id.edtMother);
//final TextView tv = (TextView) findViewById(R.id.txtfather);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String dataF = ed1.getText().toString();
char[] charArray = dataF.toCharArray();
int totalF = 0;
for (char ch: charArray) {
totalF += characterMap.get(ch);
}
String dataM = ed2.getText().toString();
char[] charArr = dataM.toCharArray();
int totalM = 0;
for (char ch2: charArr) {
totalM += characterMap.get(ch2);
}
int sum = totalF + totalM;
int totals = sum % 5;
if ((totals & 1) == 0)
//alert dialog 1 show "that is odd"
else {
//alert dialog 2 show "that is even"
}
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("that is odd");
builder.setCancelable(true);
AlertDialog alert = builder.create();
alert.show();
Just write "that is even" instead of "that is odd" for the second dialog.
Use Toast for this purpose, they are a lot easier and fast for a single message.
Toast.makeText(this, "Your Message here",
Toast.LENGTH_LONG).show();
i found that i use AlertDialog like this :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
builder.setMessage("that is odd");
builder.setCancelable(true);
AlertDialog alert = builder.create();
String dataF = ed1.getText().toString();
char[] charArray = dataF.toCharArray();
int totalF = 0;
for (char ch: charArray) {
totalF += characterMap.get(ch);
}
String dataM = ed2.getText().toString();
char[] charArr = dataM.toCharArray();
int totalM = 0;
for (char ch2: charArr) {
totalM += characterMap.get(ch2);
}
int sum = totalF + totalM;
int totals = sum % 5;
if ((totals & 1) == 0)
alert.show();
else {
AlertDialog.Builder builder1 = new AlertDialog.Builder(StartActivity.this);
builder1.setMessage("that is even");
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
});
I'm preety new on android and trying to write an application but I wrote some code and run on android device till here there is no any problem but when I try to launch query window "sorgulama.xml" application stopped my xml file like this
and my java scource file ( java code ) like this
public class Sorgulama extends Activity implements OnClickListener {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnSorgula:
String sorgu = txtSorgu.getText().toString();
Sorgula(sorgu);
break;
case R.id.btnKisaYollar:
KisaYollar();
break;
case R.id.btnTablo:
Tablolar();
break;
}
}
Button btnSorgula, btnKisaYollar, btnTablo;
EditText txtSorgu;
TableLayout tbl;
ResultSetMetaData metaData;
TableRow renkTableRow;
int kolonSayisi = 0, tvId = 0, otoId = 1;
String url,driver,userName ,password;
ArrayList<String> arrayTablolar = new ArrayList<String>();
ArrayList<String> arrayResults = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.sorgulama);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setTitle("MSSQL Uygulaması v1.0");
Kontroller();
Ayarlar();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
}
private void Ayarlar()
{
DB db = new DB(this);
db.open();
Cursor c = db.Query();
String ipAdresi = null, veriTabaniAdi = null, kullaniciAdi = null, sifre = null;
while(c.moveToNext())
{
ipAdresi = c.getString(c.getColumnIndex("IpAdresi"));
veriTabaniAdi = c.getString(c.getColumnIndex("VeriTabaniAdi"));
kullaniciAdi = c.getString(c.getColumnIndex("KullaniciAdi"));
sifre = c.getString(c.getColumnIndex("Sifre"));
}
url = "jdbc:jtds:sqlserver://" + ipAdresi +";databaseName=" +veriTabaniAdi+"";
driver = "net.sourceforge.jtds.jtbc.Driver";
userName = kullaniciAdi;
password = sifre;
db.close();
}
private void Kontroller()
{
btnSorgula = (Button) findViewById(R.id.btnSorgula);
btnKisaYollar = (Button) findViewById(R.id.btnKisaYollar);
btnTablo = (Button) findViewById(R.id.btnTablo);
txtSorgu = (EditText) findViewById(R.id.txtSorgu);
tbl = (TableLayout) findViewById(R.id.tblSonuc);
btnSorgula.setOnClickListener(this);
btnKisaYollar.setOnClickListener(this);
btnTablo.setOnClickListener(this);
}
private void KisaYollar(){
final CharSequence cs[];
cs = new String[5];
cs[0] = "select";
cs[1] = "*";
cs[2] = "from";
cs[3] = "where";
cs[4] = "and";
cs[5] = "or";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Kısa Yollar").setIcon(R.drawable.logo).setItems(cs, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String sorgu = txtSorgu.getText().toString();
txtSorgu.setText(sorgu+cs[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void Tablolar(){
}
private void Sorgula(String sorgu)
{
}
}
Can anyone help me about this issue pls?
you missed super.onCreate(savedInstanceState). Also
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
must be called before setContentView