I'm trying to build an app where someone can fill in their personal data like their name, telephone number, Email...
For each field mentioned above, I created an EditText. Now my goal is to save the user's input using SharedPreferences so that he/she don't have to fill it up every time they reopen the app.
The codes I've found take care of saving the data for one EditText only (Save entered text in editText via button). How can I achieve that on multiple EditText fields?
This is my XML file below:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vul dit compleet in"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Naam: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Naam"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="Vul uw naam in"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Functie: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Functie"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="Vul uw functie in"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Personeelsnummer "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Plnr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="Vul uw plnr in"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="NS mail"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Telefoon: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Telefoon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="zonder +31"/>
<Button
android:id="#+id/button_Opslaan"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/edit_Bericht"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:layout_weight="0.03"
android:background="#009CDE"
android:drawableLeft="#drawable/ic_launcher"
android:text="Opslaan"
android:textColor="#FFFFFF"/>
</LinearLayout>
</ScrollView>
You just have to save each EditText value and retrieve them next time your Activity reloads. The code below is adapted from the link you mentioned in your question:
public class PersonalInformation extends Activity{
private SharedPreferences savedFields;
private Button saveButton;
private EditText editText1;
private EditText editText2;
// Add all your EditTexts...
// Upon creating your Activity, reload all the saved values.
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
saveButton = (Button) findViewById(R.id.your_save_button_id);
editText1 = (EditText) findViewById(R.id.your_edit_text_1_id);
editText2 = (EditText) findViewById(R.id.your_edit_text_2_id);
// Keep adding all your EditTexts the same way...
// "info" is just a tag name, use anything you like
savedFields = getSharedPreferences("info", MODE_PRIVATE);
// In case no value is already saved, use a Default Value
editText1.setText(savednotes.getString("editText1", "Default Value 1"));
editText2.setText(savednotes.getString("editText2", "Default Value 2"));
// Save the changes upon button click
saveButton.setOnClickListener(saveButtonListener);
}
public OnClickListener saveButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor preferencesEditor = savedFields.edit();
if(editText1.getText().length() > 0) // Not empty
preferencesEditor.putString("editText1", editText1.getText());
if(editText2.getText().length() > 0) // Not empty
preferencesEditor.putString("editText2", editText2.getText());
// You can make a function so you woudn't have to repeat the same code for each EditText
// At the end, save (commit) all the changes
preferencesEditor.commit();
}
}
};
}
Try this to store in shared preferences
// MY_CONTAINER - a static String variable like:
//public static final String MY_CONTAINER = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_CONTAINER , MODE_PRIVATE).edit();
editor.putString("edittext1", "value1"); // you can also use like this editor.putString("edittext1", ed1.getText().toString())
editor.putString("edittext2", "value2");
editor.putString("edittext3", "value3");
editor.putString("edittext4", "value4");
editor.putString("edittext5", "value5");
editor.commit();
To retrieve
SharedPreferences prefs = getSharedPreferences(MY_CONTAINER, MODE_PRIVATE);
String edit1 = prefs.getString("edittext1");
String edit2 = prefs.getString("edittext2");
String edit3 = prefs.getString("edittext3");
String edit4 = prefs.getString("edittext4");
String edit5 = prefs.getString("edittext5");
Related
I have getting error while calling intent from Fragment.
Following are the log error of the same. Below are the pieces of code from the same activities. The application automatically gets off as i click on the Button for Login.
Please help me out.
Thank you in advance.
Log Report
Process: com.example.lenovo.skanda, PID: 7978
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.lenovo.skanda.AdminFragment$1.onClick(AdminFragment.java:43)
HomeFragment.java
public class AdminFragment extends Fragment implements View.OnClickListener{
View viewroot;
View v1;
private EditText Name;
private EditText Password;
static Button Login;
public static Button myLog;
private int Counter = 5;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
viewroot = inflater.inflate(R.layout.fragment_admin,container,false);
Name = (EditText) getActivity().findViewById(R.id.editText);
Password = (EditText) getActivity().findViewById(R.id.editText2);
Login = (Button) getActivity().findViewById(R.id.button2);
myLog = (Button) viewroot.findViewById(R.id.button2);
myLog.setOnClickListener(this);
myLog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
validate(Name.getText().toString(), Password.getText().toString());
}
});
return viewroot;
}
private void validate (String userName, String userPassword){
if((userName.equals("Admin")) && (userPassword.equals("123"))){
Intent intent = new Intent(AdminFragment.this.getActivity(), Login.class);
startActivity(intent); //Login is the second activity
}
else {
Counter --;
Toast.makeText(getActivity(), "No. of Attempts Left for Login" + String.valueOf(Counter), Toast.LENGTH_SHORT).show();
if (Counter == 0){
Login.setEnabled(false);
Toast.makeText(getActivity(), "For Enable the Login Please Contact..!!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onClick(View v) {
validate(Name.getText().toString(),Password.getText().toString());
}
}
fragment_admin.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#android:color/background_dark">
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/animation_view"
android:layout_width="185dp"
android:layout_height="155dp"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
app:lottie_autoPlay="true"
app:lottie_colorFilter="#FFBC00"
app:lottie_fileName="user.json"
app:lottie_loop="true" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="admin login"
android:textAllCaps="true"
android:textColor="#FFBA24"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editText"
android:layout_alignStart="#+id/editText2"
android:layout_marginBottom="-247dp"
android:text="Enter your username"
android:textAllCaps="true"
android:textColor="#B7BE5D"
android:textSize="15dp" />
<EditText
android:id="#+id/editText2"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="183dp"
android:ems="10"
android:fontFamily="monospace"
android:hint="Password"
android:inputType="textPassword"
android:textColorHint="#FFFFFF" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:text="Enter your password"
android:textAllCaps="true"
android:textColor="#B7BE5D"
android:textSize="15dp" />
<EditText
android:id="#+id/editText"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="247dp"
android:ems="10"
android:fontFamily="monospace"
android:hint="Username"
android:inputType="textPersonName"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
<EditText
android:id="#+id/Editinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="62dp"
android:text="No. of attempts left : "
android:textColor="#FFF"
android:textSize="15dp"
android:textStyle="italic" />
<Button
android:id="#+id/button2"
android:layout_width="210dp"
android:layout_height="45dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="111dp"
android:background="#drawable/rounded_button"
android:text="login"
android:textAllCaps="true"
android:textColor="#000"
android:visibility="visible" />
<Button
android:id="#+id/button"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#19193E"
android:text="LOG IN PROBLEM? CONTACT US."
android:textColor="#FFF"
android:onClick="onClick"
android:visibility="visible" />
</RelativeLayout>
You can't use getActivity().findViewById() like that.
Inside onCreateView(), you haven't yet returned the Fragment's View, meaning it isn't attached to the Activity. getActivity().findViewById() returns null because the Activity currently has no View with that ID. It only will after viewroot is returned, which is after you're invoking it.
Instead, you can do one of two things:
Replace getActivity() with viewroot:
Name = (EditText) viewroot.findViewById(R.id.editText);
Password = (EditText) viewroot.findViewById(R.id.editText2);
Login = (Button) viewroot.findViewById(R.id.button2);
Move your code to onViewCreated() and keep using getActivity() (you should be using the passed view variable, however).
In general, you don't want to use getActivity().findViewById(). If you need to find a View in that Fragment, use getView().findViewById(). Neither of these methods will work until onCreateView() returns.
I also notice that both Login and myLog are the same button. You should assign to one variable and call on it when needed. There's no point in a second local variable.
You should also try following Java's syntax guidelines:
Class names use TitleCase
Variable and function names use camelCase
it should be like this
viewroot = inflater.inflate(R.layout.fragment_admin,container,false);
Name = (EditText) viewroot.findViewById(R.id.editText);
Password = (EditText) viewroot.findViewById(R.id.editText2);
Login = (Button) viewroot.findViewById(R.id.button2);
myLog = (Button) viewroot.findViewById(R.id.button2);
You need to use viewroot instead of getActivity() in onCreateView().
Use the following code:
Name = (EditText) viewroot.findViewById(R.id.editText);
Password = (EditText) viewroot.findViewById(R.id.editText2);
Login = (Button) viewroot.findViewById(R.id.button2);
So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my Interface:
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
So I am stuck in the save and list. I am using shared preferences, but I am not able to save and list the URLS. This is the code I wrote:
public class MainActivity extends AppCompatActivity {
public static final String MY_EMP_PREFS = "MyPrefs";
private EditText url;
private Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("save", url.getText().toString());
// Commit the changes
edit.commit();
Toast.makeText(getApplicationContext(), "URL Saved", Toast.LENGTH_SHORT).show();
}
Where am I going wrong? What should I do?
Thanks
You have to add the method reference in your Widget:
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:onClick="save" //HERE
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Also, when you use a SharedPreferences, you are putting a String value using the key "save". So when you click on save button, you are overriding the old value and put a new value in the place.
To solve this issue, I think the best solution is use a Framework to persist the data and list it after.
edit.putString("save", url.getText().toString()); //here you are overriding the vlaue
Im having some issues, i have two Groups of Radiobuttons in my XML which has handling in an activity. It just crashes with nullpoint exception on line 48:
int languangeId = languageGroup.getCheckedRadioButtonId();
I have set a "default" checked button in the XML to one of the buttons in the buttongroup,
So why doesnt it get an valid value?:(
public class FirstTimeSelectMenu extends Activity{
private RadioGroup languageGroup;
private RadioGroup storageGroup;
private Button okButton;
private String getStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_time_run);
languageGroup = (RadioGroup)this.findViewById(R.id.languageGroup);
storageGroup = (RadioGroup)this.findViewById(R.id.storageGroup);
okButton = (Button)findViewById(R.id.okBtn);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int languangeId = languageGroup.getCheckedRadioButtonId();
int storageId = storageGroup.getCheckedRadioButtonId();
RadioButton languageb = (RadioButton)findViewById(languangeId);
RadioButton storageb = (RadioButton)findViewById(storageId);
if(languageb.equals("Norwegian")){
//Need to fix this!
}
if(languageb.equals("English")){
//Need to fix this!
}
if(storageb.equals("SD Card")){
String sdStoragePath = Environment.getExternalStorageDirectory().toString() + "/PictureTalk/";
FileInteraction fi = new FileInteraction();
fi.firstTimeFillPath(getResources(), "PictureTalk/Food", sdStoragePath +"PictureTalk/Food");
fi.firstTimeFillPath(getResources(), "PrivatePictures", Environment.getExternalStorageDirectory().toString() +"PrivatePictures");
Intent intent = new Intent(getApplicationContext(),MainMenuActivity.class);
intent.putExtra("dataStorePath",sdStoragePath);
startActivity(intent);
}
}
});
}}
My XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/languagetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="236dp"
android:text="Choose language" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/languagetext"
android:layout_alignRight="#+id/languagetext"
android:layout_below="#+id/languageGroup">
<RadioButton
android:id="#+id/norwegianRadioBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Norwegian" />
<RadioButton
android:id="#+id/englishRadioBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="English" />
</RadioGroup>
<TextView
android:id="#+id/internal_sd"
android:layout_width="464dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="236dp"
android:text="Do you want to store the data to:" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="#+id/storageGroup">
<RadioButton
android:id="#+id/sdcardRadioBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:checked="true"
android:text="SD card" />
<RadioButton
android:id="#+id/internalRadioBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Internal storage" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:id="#+id/okBtn"
android:layout_gravity="bottom" />
To start off with, what element is assigned the id "#+id/languageGroup" since it doesn't appear to be declared in your XML
I am getting value of EditText e1 in below example as null. So it throws null pointer exception. I wrote below in MainActivity and calling the function calculateSquare upon click on a button. Am i missing something?
public void calculateSquare(View view) {
setContentView( R.layout.activity_main);
EditText e1=(EditText) findViewById(R.id.editText1);
int number = Integer.parseInt(e1.getText().toString());
int square=number * number;
TextView e2=(TextView) findViewById(R.id.textView2);
e2.setText(square);
}
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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="#string/hello_world"
tools:context=".MainActivity" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginLeft="32dp"
android:layout_marginTop="52dp"
android:layout_toLeftOf="#+id/textView1"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="CalculateSquare"
android:onClick="calculateSquare"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/editText1"
android:layout_marginRight="36dp"
android:text="Square"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
You need to pass in a String as a parameter to the setText().
Change your code to:
e2.setText(square+"");
When you call setText(int) the system will look for the String resource by the given id(int), which needs to be supplied from the R class.
e2.setText(R.string.mystring);
About the null pointer, try cleaning your project, and you should move the initiation to the onCreate() method.
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main);
EditText e1=(EditText) findViewById(R.id.editText1);
TextView e2=(TextView) findViewById(R.id.textView2);
}
public void calculateSquare(View view) {
int number;
if (e1.getText().toString().length()>0){
number = Integer.parseInt(e1.getText().toString());
int square=number * number;
e2.setText(square+"");
}
}
You always need to check if you have entered something in the edittext, since an empty string cannot be converted into an int.
i'm doing a cable length calculator, and i'm having trouble with negative numbers.
EditTexts are like this
<EditText android:layout_height="wrap_content" android:layout_weight="1" android:inputType="numberDecimal|numberSigned" android:layout_width="40px" android:id="#+id/rxmax">
</EditText>
Then i use them like this:
final EditText rxmax = (EditText) findViewById(R.id.rxmax);
double RXmax = new Double(rxmax.getText().toString());
After i do a simple calculation:
double OPBmax = TXmax - RXmax;
Somewhere the inputted negative number turns positive. i'm guessing at the toString conversation but i don't find anything on how to prevent this.
Use
android:digits="0123456789"
EX:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="0123456789"
android:gravity="center"
android:inputType="numberSigned"
android:textColor="#color/black"
android:textSize="#dimen/font_size_small" />
I've tried this, and it works...
Activity:
double RXmax;
EditText rxmax;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rxmax = (EditText) findViewById(R.id.rxmax);
tv = (TextView) findViewById(R.id.text);
}
public void click(View v) {
RXmax = new Double(rxmax.getText().toString());
tv.setText(Double.toString(RXmax));
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_weight="1" android:inputType="numberDecimal|numberSigned"
android:layout_width="40px" android:id="#+id/rxmax">
</EditText>
<TextView android:id="#+id/text" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="#string/hello" />
<Button android:layout_height="wrap_content" android:id="#+id/button1"
android:layout_weight="1" android:text="Button" android:layout_width="wrap_content"
android:onClick="click"></Button>
</LinearLayout>
If I type -2, after clicking the TextView displays -2.0
If you're using Eclipse, try Project --> Clean..., and select your project. Maybe this will help.