Calculation with two Strings, Android - java

I'm trying to create a calculator for Android using Eclipse. This is my code for the function 'cal', 'cal' is executed when a button is clicked, But clicking on the button closes the application, I tried an other button with different function and it works fine. Can anyone point out the mistake that I've done?
public void cal( View view ){
EditText op = (EditText) findViewById(R.id.editText2);
EditText n1 = (EditText) findViewById(R.id.editText1);
EditText n2 = (EditText) findViewById(R.id.editText3);
EditText res = (EditText) findViewById(R.id.textView1);
String sn1 = n1.getText().toString();
String sn2 = n2.getText().toString();
String sres;
String sop;
int in1 = Integer.parseInt(sn1);
int in2 = Integer.parseInt(sn2);
int ires;
sop = op.getText().toString();
if(sop == "+"){
ires = in1 + in2;
sres = Integer.toString(ires);
res.setText(sres);
}
}

There is no exception in this.
I think you forgot to set the activity layout which causes your application force close.
or
Problem here
EditText res = (EditText) findViewById(R.id.textView1);
Are you sure your editText name is textView1 in your layout.
If it textView then do like this.
TextView res = (TextView) findViewById(R.id.textView1);

Related

Resetting activity when data cleared

I am currently working on an app, but there is a bug in it. Whenever a user installs the app or clears data, it should get reset. But instead the app fills in standard data for the user, instead of showing the start screen where user can input himself.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
savedData();
}
public void savedData() {
showGoalTextView = (TextView) findViewById(R.id.textView3);
showBeamsTextView = (TextView) findViewById(R.id.textView2);
showGoalEditText = (EditText) findViewById(R.id.editText2);
checkBtnPressed = (ImageButton) findViewById(R.id.imageButton5);
showBeamsEditText = (EditText) findViewById(R.id.editText4);
beamsGoal = (EditText) findViewById(R.id.editText4);
//Fetch the stored data and display it upon starting.
String goalSave = showGoalTextView.getText().toString();
String beamsSave = showBeamsTextView.getText().toString();
preferences = getSharedPreferences("userData", MODE_PRIVATE);
goalSave = preferences.getString("goals", goalSave);
beamsSave = preferences.getString("beam", beamsSave);
showGoalTextView.setText(goalSave);
showBeamsTextView.setText(beamsSave);
//Hide all the first use stuff
showGoalEditText.setVisibility(View.GONE);
checkBtnPressed.setVisibility(View.GONE);
showBeamsEditText.setVisibility(View.GONE);
beamsGoal.setVisibility(View.GONE);
}
public void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
//Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
//Get saved version
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = preferences.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);
//Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
//No big deal
return;
} else if (savedVersionCode == DOESNT_EXIST) {
//TODO This is a new install
resetAll();
} else if (currentVersionCode > savedVersionCode) {
//TODO This is an upgrade
return;
}
//Update sharedPreferences with the current version code
preferences.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
public void resetAll() {
//For when resetting
TextView showGoalTextView =
(TextView) findViewById(R.id.textView3);
EditText showGoalEditText =
(EditText) findViewById(R.id.editText2);
ImageButton checkBtnPressed =
(ImageButton) findViewById(R.id.imageButton5);
EditText showBeamsEditText =
(EditText) findViewById(R.id.editText4);
EditText beamsGoal =
(EditText) findViewById(R.id.editText4);
//Clear editTexts
showGoalEditText.getText().clear();
showBeamsEditText.getText().clear();
//Show all editTexts
showGoalEditText.setVisibility(View.VISIBLE);
checkBtnPressed.setVisibility(View.VISIBLE);
showBeamsEditText.setVisibility(View.VISIBLE);
beamsGoal.setVisibility(View.VISIBLE);
//Get the text view
TextView showResetTextView =
(TextView) findViewById(R.id.textView2);
//Get the value of the text view
String resetString = showResetTextView.getText().toString();
//Convert value to a number and reset it
Integer reset = Integer.parseInt(resetString);
reset = 0;
//Display the new value in the text view.
showResetTextView.setText(reset.toString());
showGoalTextView.setText("BEAMS");
}
My question is mainly on the checkFirstRun method.
I want to input:
} else if (savedVersionCode == DOESNT_EXIST) {
//TODO This is a new install
resetAll();
Unfortunately, I can't get it to work. Can anyone point out the issue at hand?
SharedPreferences is not cleared with uninstall (at least, not since Marshmallow). This might help you solve it SharedPreferences are not being cleared when I uninstall

Set id in dynamic edittext and textview

I have some troubles trying to put an id to a dynamic edittext and texview in Android Studio, i want to use this id to get the id's in another functions.
Note: Im not setting any id in the onCreate function.
This is my code:
for (Map.Entry<String,String> entry : getMap(newContact).entrySet()) {
total++;
TextView ProgrammaticallyTextView = new TextView(this.getActivity());
EditText ProgrammaticallyEditText = new EditText(this.getActivity());
ProgrammaticallyTextView.setId(total);
ProgrammaticallyEditText.setId(total+1);
ProgrammaticallyTextView.setText(entry.getKey());
ProgrammaticallyEditText.setText(entry.getValue());
linearLayout.addView(ProgrammaticallyTextView);
linearLayout.addView(ProgrammaticallyEditText);
total++;
}
This is the function that i use the edittext and textview id's
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_create:
String test = "";
for(int i=0; i < (this.total); i+=2){
TextView tv = (TextView) v.findViewById(i++);
EditText et = (EditText) v.findViewById(i+2);
if ((i+2) >= this.total){
test += tv.getText()+"="+et.getText();
}else
{
test += tv.getText()+"="+et.getText()+",";
}
}
mContact = getMap(test);
newContactRequest();
break;
}
}
I appreciate any help!
You need to explicitly change the data type to string. Just writing i++ tries to assign that value as an integer.
I think if you change your lines to these it should work.
TextView tv = (TextView) v.findViewById(String.valueOf(i++));
EditText et = (EditText) v.findViewById(String.valueOf(i+2));

How to make random string replace textview?

I have an activity with 3 edittexts and a button.
I have a second activity with 2 textviews.
When button is clicked i want two random edittexts values from activity1 to replace the text on textviews on activity2.
I managed to do that, but not randomly. How can I make it random?
Here is the first activity.
final EditText et = (EditText) findViewById(R.id.editText);
final EditText et1 = (EditText) findViewById(R.id.editText2);
final EditText et2 = (EditText) findViewById(R.id.editText3);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Intent i = new Intent(MainActivity.this, postavke.class);
i.putExtra("prvi", et.getText().toString());
i.putExtra("drugi", et1.getText().toString());
i.putExtra("treci", et2.getText().toString());
startActivity(i);
}
});
}
Here is the second activity.
TextView tv = (TextView) findViewById(R.id.asdf);
tv.setText(getIntent().getExtras().getString("prvi"));
TextView dr = (TextView) findViewById(R.id.asdg);
dr.setText(getIntent().getExtras().getString("drugi"));
In your second activity:
String[] texts = new String[]{
getIntent().getExtras().getString("prvi"),
getIntent().getExtras().getString("drugi"),
getIntent().getExtras().getString("treci"),
};
TextView tv = (TextView) findViewById(R.id.asdf);
TextView dr = (TextView) findViewById(R.id.asdg);
Random random = new Random();
tv.setText(texts[random.nextInt(3)]);
dr.setText(texts[random.nextInt(3)]);
Or, for unique values:
First activity:
final EditText et = (EditText) findViewById(R.id.editText);
final EditText et1 = (EditText) findViewById(R.id.editText2);
final EditText et2 = (EditText) findViewById(R.id.editText3);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
ArrayList<String> texts = new ArrayList<>();
texts.add(et.getText().toString());
texts.add(et1.getText().toString());
texts.add(et2.getText().toString());
Intent i = new Intent(MainActivity.this, postavke.class);
i.putExtra("texts", texts);
startActivity(i);
}
});
}
Second activity:
ArrayList<String> texts = getIntent().getExtras().getStringArrayList("texts");
TextView tv = (TextView) findViewById(R.id.asdf);
TextView dr = (TextView) findViewById(R.id.asdg);
Collections.shuffle(texts);
tv.setText(texts.get(0));
dr.setText(texts.get(1));
Add your Strings(Eg : getIntent().getExtras().getString("prvi")) from previous Activity to a ArrayList.
Then do simply Collection.shuffle(your_list);
Get items from ArrayList & set it to your TextViews.
Declare an array that will contain the values:
public String[] randomAnswers = new String[3]; //3 because you said you have 3 random strings
In your onCreate() add the values to the array:
randomAnswers[0] = getIntent().getExtras().getString("prvi");
randomAnswers[1] = getIntent().getExtras().getString("drugi");
randomAnswers[2] = getIntent().getExtras().getString("treci");
Select two random values:
private static final Random RANDOM = new Random(); //in java.util package
Inside onCreate:
final int randomInt1 = RANDOM.nextInt(3); //nextInt(int) goes from 0 to int-1, considering arrays start at index=0 we want to get a random number from: 0, 1, 2
int randomInt2;
do {
randomInt2 = RANDOM.nextInt(3);
} while (randomInt1 == randomInt2);
final String firstRandomString = values[randomInt1];
final String secondRandomString = values[randomInt2];`
you can use some thing like this the edited form of #Joe Frostick answere:
String[] texts = new String[]{
getIntent().getExtras().getString("prvi"),
getIntent().getExtras().getString("drugi"),
getIntent().getExtras().getString("treci"),
};
TextView tv = (TextView) findViewById(R.id.asdf);
TextView dr = (TextView) findViewById(R.id.asdg);
Random random = new Random();
texts.remove(random.nextInt(3));
tv.setText(texts[0]);
dr.setText(texts[1]);
Thanks for the help everyone, I really didn't expect so many answers in not much time. You're the best!

How to run custom function within another one?

i build complicated application on android studio and i have this code which i have to put it in another function upon click it:
EditText e1 = (EditText) findViewById(R.id.Name);
EditText e2 = (EditText) findViewById(R.id.Room);
EditText e3 = (EditText) findViewById(R.id.Date);
EditText e4 = (EditText) findViewById(R.id.Age);
EditText e5 = (EditText) findViewById(R.id.Height);
EditText e6 = (EditText) findViewById(R.id.Weight);
EditText e7 = (EditText) findViewById(R.id.SerumC);
EditText e8 = (EditText) findViewById(R.id.SUN);
EditText e9 = (EditText) findViewById(R.id.ALB);
SResult.setVisibility(View.INVISIBLE);
r11b.setVisibility(View.INVISIBLE);
iup.setVisibility(View.INVISIBLE);
alert.setVisibility(View.INVISIBLE);
rup.setVisibility(View.INVISIBLE);
r11.setVisibility(View.INVISIBLE);
e1.setVisibility(VISIBLE);
e2.setVisibility(VISIBLE);
e3.setVisibility(VISIBLE);
e4.setVisibility(VISIBLE);
e5.setVisibility(VISIBLE);
e6.setVisibility(VISIBLE);
e7.setVisibility(VISIBLE);
e8.setVisibility(VISIBLE);
e9.setVisibility(VISIBLE);
Male.setVisibility(VISIBLE);
Female.setVisibility(VISIBLE);
Black.setVisibility(VISIBLE);
NonBlack.setVisibility(VISIBLE);
Stable.setVisibility(VISIBLE);
NonStable.setVisibility(VISIBLE);
Scrlabel.setVisibility(VISIBLE);
clearH.setVisibility(VISIBLE);
clearHN.setVisibility(VISIBLE);
calcH.setVisibility(VISIBLE);
calcHN.setVisibility(VISIBLE);
menuH.setVisibility(VISIBLE);
menuHN.setVisibility(VISIBLE);
equatlab.setVisibility(VISIBLE);
r12equ.setVisibility(VISIBLE);
printC.setVisibility(View.INVISIBLE);
printCH.setVisibility(View.INVISIBLE);
homeC.setVisibility(View.INVISIBLE);
homeCH.setVisibility(View.INVISIBLE);
returnC.setVisibility(View.INVISIBLE);
returnCH.setVisibility(View.INVISIBLE);
par.setVisibility(VISIBLE);
but as you see it's long one and with time i will face a hard problem to make any change in my app, so i need to store this in a custom function and upon click the button the action of this function start like this:
public class visistore {
EditText e1 = (EditText) findViewById(R.id.Name);
EditText e2 = (EditText) findViewById(R.id.Room);
EditText e3 = (EditText) findViewById(R.id.Date);
EditText e4 = (EditText) findViewById(R.id.Age);
EditText e5 = (EditText) findViewById(R.id.Height);
EditText e6 = (EditText) findViewById(R.id.Weight);
EditText e7 = (EditText) findViewById(R.id.SerumC);
EditText e8 = (EditText) findViewById(R.id.SUN);
EditText e9 = (EditText) findViewById(R.id.ALB);
SResult.setVisibility(View.INVISIBLE);
r11b.setVisibility(View.INVISIBLE);
iup.setVisibility(View.INVISIBLE);
alert.setVisibility(View.INVISIBLE);
rup.setVisibility(View.INVISIBLE);
r11.setVisibility(View.INVISIBLE);
e1.setVisibility(VISIBLE);
e2.setVisibility(VISIBLE);
e3.setVisibility(VISIBLE);
e4.setVisibility(VISIBLE);
e5.setVisibility(VISIBLE);
e6.setVisibility(VISIBLE);
e7.setVisibility(VISIBLE);
e8.setVisibility(VISIBLE);
e9.setVisibility(VISIBLE);
Male.setVisibility(VISIBLE);
Female.setVisibility(VISIBLE);
Black.setVisibility(VISIBLE);
NonBlack.setVisibility(VISIBLE);
Stable.setVisibility(VISIBLE);
NonStable.setVisibility(VISIBLE);
Scrlabel.setVisibility(VISIBLE);
clearH.setVisibility(VISIBLE);
clearHN.setVisibility(VISIBLE);
calcH.setVisibility(VISIBLE);
calcHN.setVisibility(VISIBLE);
menuH.setVisibility(VISIBLE);
menuHN.setVisibility(VISIBLE);
equatlab.setVisibility(VISIBLE);
r12equ.setVisibility(VISIBLE);
printC.setVisibility(View.INVISIBLE);
printCH.setVisibility(View.INVISIBLE);
homeC.setVisibility(View.INVISIBLE);
homeCH.setVisibility(View.INVISIBLE);
returnC.setVisibility(View.INVISIBLE);
returnCH.setVisibility(View.INVISIBLE);
par.setVisibility(VISIBLE);
}
then, in my main activity :
button.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
return true;
}
if (event.getAction()== MotionEvent.ACTION_DOWN)
{
visistore
}
return true;
}
});
Is this right?! or if it's wrong so i need to correct me
If i understood your problem correctly then , it is simple as Just define a boolean isButtonClicked
make this isButtonClicked = true onClick event
then put if(isButtonClicked) condition in your touchClick event.
Hope you got it
You don't want to set an OnTouchListener but an OnClickListener. The in the onClick() method of the OnClickListener call the appropriate function.

Edittext field outside scope of alert dialog? Nullpointer Exception

I created an AlertDialog such that when you press a Button, the Dialog pops up and a layout appears with EditTexts. However, I created the layout in the actual code rather than in the xmlfile. For some reason, when the AlertDialog pops up, it's not able to find the EditText field and gives me a NullPointerException.
//private Lecture lecture;
private LectureManager lectureManager;
public void addWork(View view) {
LinearLayout layout = new LinearLayout(this);
EditText weight = new EditText(this);
EditText mark = new EditText(this);
mark.setInputType(InputType.TYPE_CLASS_NUMBER);
weight.setInputType(InputType.TYPE_CLASS_NUMBER);
weight.setId(99);
mark.setId(100);
layout.addView(mark);
layout.addView(weight);
AlertDialog.Builder addwork = new AlertDialog.Builder(this);
addwork.setView(layout);
addwork.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText eweight = (EditText) findViewById(99);
EditText emark = (EditText) findViewById(100);
String coursename = ecoursename.getText().toString();
And for some reason, I'm getting a NullPointerException at the "EditText weight" line. I believe that maybe it's not finding anything with ID 99 and that the EditText might be out of scope? Thanks in advance!
Actually, when you make these calls:
EditText eweight = (EditText) findViewById(99);
EditText emark = (EditText) findViewById(100);
you're calling the findViewById() method of your Activity, not the AlertDialog. In order to retrieve the views from the Dialog, you can use something like this, inside onClick():
EditText eweight = (EditText) ((AlertDialog)dialog).findViewById(99);
EditText emark = (EditText) ((AlertDialog)dialog).findViewById(100);
Hope this helps.
Try this..
Use final for both EditText while initilization like below
final EditText weight = new EditText(this);
final EditText mark = new EditText(this);
Then you can get the text from EditText in PositiveButton
String weight_txt = weight.getText().toString().trim();
String mark_txt = mark.getText().toString().trim();
No need to set id for EditText also no need findViewById.
i think you need to do this
EditText eweight = (EditText) view.findViewById(99);
and view is , what you have passed in your addWork() method parameter.

Categories

Resources