set input range from 1-30 - java

i m getting an input using an EditText from the user but i don't want input more than 30 that is his input should be from 1-30 range, how should i do it??
final EditText personcount = findViewById(R.id.personcount);
final TextView personcountview = findViewById(R.id.personcountview);
final TextView itemcountview = findViewById(R.id.itemcountview);
final EditText itemcount = findViewById(R.id.itemcount);
personcount.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1)});
itemcount.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1)});
Toast.makeText(this, "EditText limit set to a single digit", Toast.LENGTH_SHORT).show();
Button next1 = findViewById(R.id.next1);
next1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num1= Integer.parseInt(personcount.getText().toString());
int num2 = Integer.parseInt(itemcount.getText().toString());
Intent personname = new Intent(getApplicationContext(), personname.class);
personname.putExtra("num", num1);
personname.putExtra("num2",num2);
startActivity(personname);
}

you can set maxLength in your editText in xml :
android:maxLength="30"
or set filter :
TextView edit= new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(30);
edit.setFilters(filterArray);

Related

Problem with checking that all EditTexts are empty

I have 5 EditTexts, when I am clicking on the button, I want to check that all of them are not empty in order to take data from them and put it into the database, and start another activity. If all of them are empty, a message would be displayed that "You need to fill everything". However, when all EditTexts are empty and I press the button, application crashes. How can I solve this problem and what can I do to get the desired result? (The code is not ended yet.)
public class Main2Activity extends AppCompatActivity {
DatabaseHelper myDB;
Button btnAdd;
EditText editText1,editText2,editText3,editText4,editText5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editText1 = (EditText) findViewById(R.id.name);
editText2 = (EditText) findViewById(R.id.year);
editText3 = (EditText) findViewById(R.id.month);
editText4 = (EditText) findViewById(R.id.day);
editText5 = (EditText) findViewById(R.id.price);
btnAdd = (Button) findViewById(R.id.btn_add);
myDB = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name1 = editText1.getText().toString();
String year2 = editText2.getText().toString();
int year1 = Integer.parseInt(year2);
String month2 = editText3.getText().toString();
int month1 = Integer.parseInt(month2);
String day2 = editText4.getText().toString();
int day1 = Integer.parseInt(day2);
String price2 = editText5.getText().toString();
int price1 = Integer.parseInt(price2);
if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {
AddData(name1, year1, month1, day1, price1);
editText1.setText("");
editText2.setText("");
editText3.setText("");
editText4.setText("");
editText5.setText("");
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
}
}
});
}
public void AddData(String name1, int year1, int month1, int day1, int price1) {
boolean insertData = myDB.addData(name1,year1,month1,day1,price1);
if(insertData==true){
Toast.makeText(this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
}
The crash happens here:
int year1 = Integer.parseInt(year2);
When EditText is empty, you are passing an empty string to Integer.parseInt, which results in NumberFormatException. To avoid this, move the parsing code into the validation block.
#Override
public void onClick(View v) {
String name1 = editText1.getText().toString();
String year2 = editText2.getText().toString();
String month2 = editText3.getText().toString();
String day2 = editText4.getText().toString();
String price2 = editText5.getText().toString();
if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {
// Move parsing code here
int year1 = Integer.parseInt(year2);
int month1 = Integer.parseInt(month2);
int day1 = Integer.parseInt(day2);
int price1 = Integer.parseInt(price2);
AddData(name1, year1, month1, day1, price1);
editText1.setText("");
editText2.setText("");
editText3.setText("");
editText4.setText("");
editText5.setText("");
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
}
}
You can allow the user to press the button only after entering text to all of your editTexts like this:
if (all editTexts got text inside) {
//not all editTexts got text inside them, user cant press the button
button.setClickable(false);
}
else{
//all editTexts got text inside them, user can now press the button
button.setClickable(true);
}
Note - "all editTexts got text inside" that I wrote inside the if statment is for you to make in any way that you would like to check.

How to display multiple EditText inputs after pressing Button in one TextView?

I'm in the beginning of my learning how to make apps. I want to make an app which should display randomized inputted tasks to do for the user. Firstly user should choose how many tasks would like to create and then write down tasks in EditText. I am able to create particular amount of EditText but I have no clue how to display all EditText input after pressing button. I have many versions of the code but non of them work. I got stuck and I need advice.
Here is one of my code version for the second activity.
public class TaskActivity extends AppCompatActivity {
LinearLayout containerLayout;
TextView receiverTV;
TextView tv;
TextView displayTaskTv;
EditText et;
Button btn;
Button randomTaskBtn;
int i = 0;
int size;
String inputEditText;
String inputTextView;
String stringsEt[];
String stringsTv [];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
containerLayout = (LinearLayout) findViewById(R.id.linear_layout);
receiverTV = (TextView) findViewById(R.id.receiver_textView);
Intent intent = getIntent();
int number = intent.getIntExtra("Number", defaultValue);
receiverTV.setText("You have chosen to add: " + number + " tasks!");
createEtTvBtn(number);
createBtn();
createTextView();
}
public void createEtTvBtn(int number) {
for (i = 1; i <= number; i++) {
tv = new TextView(this);
tv.setText("Task nr: " + i);
tv.setPadding(16, 16, 16, 16);
tv.setTextColor(Color.parseColor("#008b50"));
tv.setTextSize(20);
tv.setId(i + value);
containerLayout.addView(tv);
et = new EditText(this);
et.setHint("Enter task nr: " + i);
et.setId(i + value);
et.setLines(2);
containerLayout.addView(et);
btn = new Button(this);
btn.setText("Confirm task nr: " + i);
btn.setId(i + value);
containerLayout.addView(btn);
final List<EditText> allEditText = new ArrayList<EditText>();
final List<TextView>allTextView = new ArrayList<TextView>();
final List<Button>allButton = new ArrayList<Button>();
String[] stringsEditText = new String[(allEditText.size())];
String[] stringsTextView = new String[(allTextView.size())];
String[] stringsBtn = new String[(allButton.size())];
for(int i=0; i < allEditText.size(); i++){
stringsEditText[i] = allEditText.get(i).getText().toString();
}
for (int i=0; i < allTextView.size(); i++) {
stringsTextView[i] = allTextView.get(i).getText().toString();
size = allTextView.get(i).getText().toString().length();
}
for(int i=0; i < allButton.size(); i++){
stringsBtn[i] = allButton.get(i).getText().toString();
}
allTextView.add(tv);
allEditText.add(et);
allButton.add(btn);
allButton.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEditText = allEditText.get(0).getText().toString();
stringsEt = new String[] {allEditText.get(0).getText().toString()};
if (inputEditText.length() > 0) {
allTextView.get(0).setText(inputEditText);
allEditText.add(allEditText.get(0));
allEditText.get(0).setText("");
}
else if (inputEditText.length() ==0){
Toast.makeText(TaskActivity.this, "You need to write down your task", Toast.LENGTH_LONG).show();
}
inputTextView = allTextView.get(0).getText().toString();
stringsTv = new String[] {allTextView.get(0).getText().toString()};
if (inputTextView.length() > 0) {
allTextView.get(0).getText();
allTextView.add(allTextView.get(0));
}
}
});
}
}
private Button createBtn() {
randomTaskBtn = new Button(this);
randomTaskBtn.setText("Task");
containerLayout.addView(randomTaskBtn);
randomTaskBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double luckyTask = Math.random();
luckyTask *=size;
int luckyIndex = (int)luckyTask;
displayTaskTv.setText(stringsTv[luckyIndex]);
}
});
return randomTaskBtn;
}
private TextView createTextView() {
displayTaskTv = new TextView(this);
displayTaskTv.setTextSize(20);
displayTaskTv.setTextColor(Color.parseColor("#dd2626"));
displayTaskTv.setText("");
containerLayout.addView(displayTaskTv);
return displayTaskTv;
}
}
Thank you for any constructive advices.
I am sure my code is big mess. I wanted to created more methods but I didn't succeed.
This is what you should do
Step 1 -
Create multiple EditTexts and store each one of them in an ArrayList say myEditTextList.
Step 2- Take data from all edit texts
String str = ""
for(EditText et: myEditTextList) {
str += et.getText().toString();
}
Step 3- Display data in str wherever you want.

Displaying Double in another acitivity

I am trying to display a double from this class in another class..
So here is my code:
public class Calculator extends AppCompatActivity {
Button next;
TextView pPrice;
TextView renovations;
TextView misc2;
TextView util;
TextView rep;
TextView mortage;
TextView misc1;
TextView rent;
public double getStartingCostsResult() {
return startingCostsResult;
}
double startingCostsResult;
double monthlyMinus;
double monthlyPlus;
double monthlyROI;
double yearlyROI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
// Setting these textviews to those in the xml.
pPrice = (TextView) findViewById(R.id.pPrice);
renovations = (TextView) findViewById(R.id.renovations);
misc2 = (TextView) findViewById(R.id.misc2);
util = (TextView) findViewById(R.id.util);
rep = (TextView) findViewById(R.id.rep);
mortage = (TextView) findViewById(R.id.mortage);
misc1 = (TextView) findViewById(R.id.misc);
rent = (TextView) findViewById(R.id.rent);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent expense = new Intent(getApplicationContext(), Results.class);
if ((pPrice.getText().length() > 0) && (renovations.getText().length() > 0) && (misc2.getText().length() > 0)) {
double price = Double.parseDouble(pPrice.getText().toString());
// double costs = Double.parseDouble(cCosts.getText().toString());
double reno = Double.parseDouble(renovations.getText().toString());
double misc = Double.parseDouble(misc2.getText().toString());
startingCostsResult = price + reno + misc;
if((util.getText().length()>0) && (rep.getText().length()>0) && (mortage.getText().length()>0) && (misc1.getText().length()>0)){
double utilities = Double.parseDouble(util.getText().toString());
double repairs = Double.parseDouble(rep.getText().toString());
double mort = Double.parseDouble(mortage.getText().toString());
double miscsell = Double.parseDouble(misc1.getText().toString());
monthlyMinus = utilities + repairs + mort + miscsell;
if (rent.getText().length()>0){
double monthlyRent = Double.parseDouble(rent.getText().toString());
monthlyPlus = monthlyRent;
monthlyROI = monthlyPlus - monthlyMinus;
yearlyROI = monthlyROI *12;
startActivity(expense);
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
So I am trying to display the yearlyROI double in another class.
I have tried this:
Calculator calc = new Calculator();
otherClass.setText((int) calc.yearlyROI);
But my app crashes when I click next.
you should put an extra in the expense intent like this.
expense.putExtra("yearlyRoi",yearlyRoi);
then in the nexet activity you can get it like this.
Intent recievedIntent = this.getIntent();
double yearlyRoi = recievedIntent.getDoubleExtra("yearlyRoi", defaultValue);
default value can be 0.0 or anything you want.
as for the crash i think its another problem,you need to give us error log of your app.
If you want to access variables from a different Activity you need to add them to your intent.
In your case:
expense.putExtra("yearlyROI", yearlyROI);
startActivity(expense);
Then in your new Activity:
double yearlyROI = getIntent().getDoubleExtra("yearlyROI");
Hope it helps!

Make selected text from Edittext Bold and not-bold

I'm trying to make a feature for my app where the user can make a selected text Bold but I also want to make it so that if the selected text is already bold, then the text shall be set to normal again, a kind of an undo-function.
I have tried over 100 of combinations without any succses!
CharacterStyle csBold = new StyleSpan(Typeface.BOLD);
CharacterStyle csNormal = new StyleSpan(Typeface.NORMAL);
int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
SpannableStringBuilder ssb = new SpannableStringBuilder(editText.getText());
ssb.setSpan(csBold, start, end, 1);
SpannableStringBuilder ssb2 = new SpannableStringBuilder(editText.getText());
ssb2.setSpan(csNormal, start, end, 1);
switch(item.getItemId()) {
case R.id.bold:
while(editText.isSelected()){
if(editText.getSelectionStart() + editText.getSelectionEnd() == ssb.getSpanStart(start) + ssb.getSpanEnd(end)){
editText.setText(ssb2);
return true;
}else{
editText.setText(ssb);
return true;
}
}
Update ANSWER
Edittext editext;
Button bold_btn , normal_btn , itlac;
CharacterStyle styleBold , styleItalc;
boolean bold = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
styleBold = new StyleSpan(Typeface.BOLD);
styleNormal = new StyleSpan(Typeface.NORMAL);
styleItalc = new StyleSpan(Typeface.ITALIC);
underLine = new UnderlineSpan();
editext = (Editext) findViewById(R.id.editext);
bold_btn = (Button) findViewById(R.id.button1);
italic_btn = (Button) findViewById(R.id.button2);
italic_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String wholeText = username.getText().toString();
int start = username.getSelectionStart();
int end = username.getSelectionEnd();
SpannableStringBuilder sb = new SpannableStringBuilder(wholeText);
sb.setSpan(styleItalic, start, end, 0);
username.setText(sb);
}
});
........
.....
bold_btn.setOnClickListener(BoldbuttonListener);
normal_btn.setOnClickListener(normalbuttonListener);
}
View.OnClickListener BoldbuttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
bold = !bold;
String wholeText = username.getText().toString();
int start = username.getSelectionStart();
int end = username.getSelectionEnd();
CharacterStyle passedStyle;
SpannableStringBuilder sb = new SpannableStringBuilder(wholeText);
if(bold) {
passedStyle = styleNormal;
}else {
passedStyle = styleBold;
}
sb.setSpan(passedStyle, start, end, 0);
editext.setText(sb);
}
};
the same for normal effect

Difficulty saving and storing

I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);

Categories

Resources