This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
The functionality of my program is not working properly. It is not doing what I need it to do. I don't have any errors in the code but the app isn't doing what I want it to do.
**UPDATE: Okay thank you very much for the help. the button displays a value for TextView ce. However, the app does not seem to run my ifstatement to get a new value of CE1 which would be = 4*credit_1. The app is taking the initialized value of CE1 which is = 0, and converting that to a string CE1s. Hence dispalying 0.0 in TextView ce. Why is the app not taking my ifstatement if(grade_1.equals("A")) into consideration?
Here is the MainActivity.java:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText course1 = (EditText)findViewById(R.id.Course1);
EditText credit1 = (EditText)findViewById(R.id.editText7);
final EditText grade1 = (EditText)findViewById(R.id.editText13);
final Button b = (Button)findViewById(R.id.button1);
final TextView ce = (TextView)findViewById(R.id.textView5);
String grade_1 = grade1.getText().toString();
String text = credit1.getText().toString();
if (!TextUtils.isEmpty(text)) {
// call parseDouble in here
double credit_1 = Double.parseDouble(text);
double CE1=0;
if (grade_1 =="A")
CE1 = 4*credit_1;
final String CE1s = Double.toString(CE1);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v){
ce.setText(CE1s);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
}
}
Here is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rutgersgpacalculator"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.rutgersgpacalculator.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
make sure that you verify if text is not null and it's rode when you click it. You should also consider verify without TextUtils like if (text != null && text.length > 0) {...}
b.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// get the text when you click it to make sure it's live while click
String text = credit1.getText().toString();
if (!TextUtils.isEmpty(text)) {
double credit_1 = Double.parseDouble(text);
ce.setText(Double.toString( (grade_1.equals("A")) ? 4*credit_1 : 0));
}
});
Related
The first variable that i need help with is totalTxt. This variable holds the value of all of the money the user has entered in the previous categories. This variable should be displayed next to "Your Total Spending is:". The second variable i need help with is still2. This variable hold the value of the user's goal and subtracts totalTxt from it. It should be displayed for next to "You Need to Save:". Also how with I impleament ScrollView? I tried adding that into the layout but on the emulator I couldnt scroll and therefore "You Need to Save:" was being cut off. Down below is my code...Help Please.
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button calculate = (Button) findViewById(R.id.calculate);
calculate.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
EditText goal = (EditText) findViewById (R.id.GoalText);
double goalTxt = Double.parseDouble(goal.getText().toString());
EditText groceries = (EditText) findViewById (R.id.GroceriesText);
double groceriesTxt = Double.parseDouble(groceries.getText().toString());
EditText rent = (EditText) findViewById (R.id.RentText);
double rentTxt = Double.parseDouble(rent.getText().toString());
EditText utilities = (EditText) findViewById (R.id.UtilitiesText);
double utilitiesTxt = Double.parseDouble(utilities.getText().toString());
EditText clothingshoesetc = (EditText) findViewById (R.id.ClothingShoesEtcText);
double clothingshoesetcTxt = Double.parseDouble(clothingshoesetc.getText().toString());
EditText entertainmentdiningetc = (EditText) findViewById (R.id.EntertainmentDiningEtcText);
double entertainmentdiningetcTxt = Double.parseDouble(entertainmentdiningetc.getText().toString());
EditText transportationcabtraingas = (EditText) findViewById (R.id.TransportationCabTrainGasText);
double transportationcabtraingasTxt = Double.parseDouble(transportationcabtraingas.getText().toString());
EditText others = (EditText) findViewById (R.id.OthersText);
double othersTxt = Double.parseDouble(others.getText().toString());
EditText total = (EditText) findViewById (R.id.YourTotalSpendingText);
double totalTxt = groceriesTxt + rentTxt + utilitiesTxt + clothingshoesetcTxt +
entertainmentdiningetcTxt + transportationcabtraingasTxt + othersTxt;
Toast.makeText(getApplicationContext(), Double.toString(totalTxt), Toast.LENGTH_LONG).show();
EditText still2= (EditText) findViewById (R.id.YouNeedToSaveText);
double still = goalTxt - totalTxt;
Toast.makeText (getApplicationContext (), Double.toString(still), Toast.LENGTH_LONG).show();
if (still < 0){
String stop = ("STOP SPENDING SO MUCH MONEY!");
Toast.makeText(getApplicationContext(), (stop), Toast.LENGTH_LONG).show(); }
if (still > 0) {
String go = ("Keep going! Piggy B. believes in you!");
Toast.makeText(getApplicationContext(), (go), Toast.LENGTH_LONG).show(); }
}
}
In your layout xml, I'm guessing you have a LinearLayout (or some layout) surrounding the collection of EditTexts.
In your layout xml file add a ScrollView surrounding the LinearLayout. Something like:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="#+id/GoalText"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
other edit text tags here
</LinearLayout>
</ScrollView>
Adding the ScrollView enables the user to scroll the screen (if the view is larger than the screen).
UPDATE:
I have 4 imageButtons and each one needs a "setOnClickListener" or similar. Once the listener fires, I have an intent to take the user to the next Activity, which is currently just a blank page:
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
I started out with 4 Buttons, and had it all working, and then decided to use imageButtons instead for aesthetics.
I'm not sure what the difference is in "buttons" and "imageButtons" are, but you most certainly can't interchange them. My best 'Googling' has not turned up any solution so far in understanding how to modify my earlier 'button' solution.
Any assist would be welcome,
Ed
Here is the MainActivity.java code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//In this next line, note that 'btn' will never be used, it's
//grayed out in the "Button btn...", and in the (R.id.btn) it is
//shown in red font, indicating I probably need to declare a resource of some kind?
Button btn = (Button)findViewById(R.id.btn);
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is the activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:clickable="true">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:background="#drawable/new_song"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton2"
android:background="#drawable/loadsong"
android:layout_alignTop="#+id/imageButton"
android:layout_toRightOf="#+id/imageButton"
android:layout_toEndOf="#+id/imageButton"
android:layout_marginLeft="55dp"
android:layout_marginStart="55dp"/>
</RelativeLayout>
ImageButton in Android is not a subclass of Button, but of ImageView, so you can't store a ImageButton in a Button variable. So you need to use ImageButton as your button object class. The method setOnClickListener is not static and should be set on the button object you want to use. Also the Button id you try to use is not in your xml (at least not the part you posted). So your code should read sth like this:
ImageButton btn = (ImageButton)findViewById(R.id.imageButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
});
If you originally had buttons that were working, you may have forgotten to change the cast type. For example
Button btn = (Button)findViewById(R.id.btn); //Will work.
ImageButton btn = (Button)findViewById(R.id.btn); //Might compile, but will not work.
Alternatively, if you left the XML tag as a normal button
<Button android:id = .../>
and tried to cast it to an image button, an error would be thrown. You would need to change the tag to <ImageButton android:id = .../>
Otherwise, I'm not sure what changes you made that would result in this going wrong. Further details as to the nature of the error would be helpful in solving the problem
You should ImageButton instead of Button.
Must use setOnClickListener to Button object btn instead of Button class
Update your onCreate() method as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton btn = (ImageButton) findViewById(R.id.imageButton);
ImageButton btn2 = (ImageButton) findViewById(R.id.imageButton2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something...
}
});
}
Hope this will help~
I'm trying to understand the total flow of Android applications, and I'm running into what I consider to be a strange situation (note: Im VERY new to android programming).
I made a test application with just a multiline edit text field. I wrote 1234 on the field. Without anything else, with no other changes to the default Eclipse ADT made application and without overriding anything specifically in the backend, I changed orientation. 1234 remained. I then hit the home button, then opened it from recent apps. 1234 remained.
My understanding of the app lifecycle was that the application was stopped and started when the home button is pressed, and the application is destroyed and created when the application's orientation is changed. If this is correct, is there some form of automatic state keeping that takes place? I was under the assumption that I had to pull, from the state bundle, individual variables and restore them myself. Is that not correct?
Any explanation of this that a more seasoned Android dev could give would be great. I've been trying to find the appropriate answer, but to no avail.
MainActivity.java
package com.example.teststate;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.teststate.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
Snippet from Manifest.xml
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Thank you!
The reason this happens is because the view explicitly saves and restores its state on orientation changes, by overriding View#onSaveInstanceState() and View#onRestoreInstanceStance(Parcelable). Here's the of the implementation in TextView (super class of EditText)
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
// Save state if we are forced to
boolean save = mFreezesText;
int start = 0;
int end = 0;
if (mText != null) {
start = getSelectionStart();
end = getSelectionEnd();
if (start >= 0 || end >= 0) {
// Or save state if there is a selection
save = true;
}
}
if (save) {
SavedState ss = new SavedState(superState);
// XXX Should also save the current scroll position!
ss.selStart = start;
ss.selEnd = end;
if (mText instanceof Spanned) {
Spannable sp = new SpannableStringBuilder(mText);
if (mEditor != null) {
removeMisspelledSpans(sp);
sp.removeSpan(mEditor.mSuggestionRangeSpan);
}
ss.text = sp;
} else {
ss.text = mText.toString();
}
if (isFocused() && start >= 0 && end >= 0) {
ss.frozenWithFocus = true;
}
ss.error = getError();
return ss;
}
return superState;
}
[...]
#Override
public void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
// XXX restore buffer type too, as well as lots of other stuff
if (ss.text != null) {
setText(ss.text);
}
if (ss.selStart >= 0 && ss.selEnd >= 0) {
if (mText instanceof Spannable) {
int len = mText.length();
if (ss.selStart > len || ss.selEnd > len) {
String restored = "";
if (ss.text != null) {
restored = "(restored) ";
}
Log.e(LOG_TAG, "Saved cursor position " + ss.selStart +
"/" + ss.selEnd + " out of range for " + restored +
"text " + mText);
} else {
Selection.setSelection((Spannable) mText, ss.selStart, ss.selEnd);
if (ss.frozenWithFocus) {
createEditorIfNeeded();
mEditor.mFrozenWithFocus = true;
}
}
}
}
if (ss.error != null) {
final CharSequence error = ss.error;
// Display the error later, after the first layout pass
post(new Runnable() {
public void run() {
setError(error);
}
});
}
}
As you can see, it saves the state in a Parcelable object, which is then passed along to a view with the same android:id in the new instance, and onRestoreInstanceState() gets called on the new view. If you create a custom view, which doesn't just consists of other views, you might want to override these methods.
I am not able to give you a code level explanation. But it is one of those things android promised to do. You can check out this Recreating activity
Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
I have an Activity which has an 'OK' button. And I have an 'Edit' button which will open a Dialog (theme="#android:style/Theme.Holo.Light.Dialog"). When I am in the EditDialog, I can see the OK button in the background Activity, and I can press that, and it the press is getting registered.
Is there a way to disable the background Activity actions when a Dialog is open? i.e. I want to modify things in the Dialog alone.
Edit: Adding a sample code which shows this behaviour.
Main Activity:
public class DialogTestActivity extends Activity implements OnClickListener {
private final String TAG = "DialogTest.main";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.button_open)).setOnClickListener(this);
((Button) findViewById(R.id.button_ok)).setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_ok:
Log.w(TAG, "OK Button Pressed!");
break;
case R.id.button_open:
Log.d(TAG, "Opening new Window.");
Intent intent = new Intent(this, TestDialog.class);
startActivity(intent);
default:
break;
}
}
}
TestDialog 'dialog':
public class TestDialog extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_dialog);
LayoutParams params = getWindow().getAttributes();
params.height = LayoutParams.WRAP_CONTENT;
Window window = this.getWindow();
window.setAttributes((android.view.WindowManager.LayoutParams) params);
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
}
}
Manifest:
<activity
android:name=".DialogTestActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TestDialog"
android:label="#string/dialog_label"
android:theme="#android:style/Theme.Holo.Light.Dialog" >
</activity>
With the above code, when the TestDialog was open, the Button Press on the background Activity were registered - OK Button Pressed! will be logged.
First, this is not a dialog. This is a dialog-themed activity. A dialog inherits from Dialog.
Second, your use of WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL is giving you precisely the behavior that you do not want. Delete this line of code, and things should work better.
Nothing in the underlying Activity should be clickable when a Dialog is in the foreground (this is how Dialogs in Android work). If you are able to interact with the underlying Activity when the Dialog is open, then there is probably something wrong with your implementation.
Edit:
Remove this line and all should work:
this.setCanceledOnTouchOutside(false);
If your Activity is opened with set Dialog theme use code below
setFinishOnTouchOutside(false);
The next code shows three buttons. You can increase and decrease the text size of one of those buttons , called 'main' button. The main button also has an image (compound drawable)
You'll note that the text position will change (Eg: increase the text to a big size, and then decrease it to its original size ). Also, you can see the text size changes int logcat.
This behavior is reproduced in android 3.1
This behavior is not reproduced in android 2.2
Why is this happening?
the code:
public class Acc extends Activity {
/**
* main button
*/
Button b;
/*
* the text size
*/
float textSize;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Button(this); //create main button
b.setText("I'm main button"); //set its text
b.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon, 0, 0); //add a drawable
textSize=14;//assign initial textsize
b.setTextSize(textSize); //set it to the button's text size
b.setHeight(200);
LinearLayout layout = (LinearLayout) findViewById(R.id.main); //get the activity layout
layout.addView(b); //add the main button to the layout
addZoomInOutButtons(layout); //add two buttons to increase and decrease the main button's height and text size
Log.v("my log","FIRST TIME: text size:"+textSize);
}
/**
* Create two buttons, to increase and decrease with and text size of main button
* #param layout
*/
private void addZoomInOutButtons(LinearLayout layout){
Button bzi = new Button(this);
bzi.setText("zoom in");
Button bzo = new Button(this);
bzo.setText("zoom out");
layout.addView(bzi);
layout.addView(bzo);
bzi.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textSize+=10;
b.setTextSize(textSize);
Log.v("my log","text size:"+textSize);
}
});
bzo.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textSize-=10;
b.setTextSize(textSize);
Log.v("my log","text size:"+textSize);
}
});
}
}
also the manifest:
<?xml version="1.0" encoding="utf-8"?>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Acc"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8"/>