Null Pointer Exception - Getting EditText Value - android

This is my first question on here I will apologize in advance if I didn't ask this question very well. I have looked at my other questions similar to my problem, but I have not found a good solution to satisfy what is going on in my program.
So my problem is I am trying to assign a value to a variable called, num1 from my EditText field called, num1TextField, but I am not having any luck so far.
The segment inside my java file that throws the exception is:
EditText num1Field = (EditText)v.findViewById(R.id.num1TextField);
num1 = num1Field.getText().toString();
I appreciate every contribution to this problem in advance.
Here is my fragment_compute.xml file:
<?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"
android:orientation="vertical" >
<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="14dp"
android:text="#string/compute_activity"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:text="#string/num_1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/num1TextField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="number"
android:gravity="center" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/num2TextField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/num1TextField"
android:layout_below="#+id/textView3"
android:ems="10"
android:inputType="number"
android:layout_centerHorizontal="true"
android:gravity="center" >
</EditText>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/num2TextField"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="#string/result"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/num1TextField"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="#string/num_2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp" />
<Button
android:id="#+id/compute_multiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/num2TextField"
android:layout_below="#+id/result"
android:layout_marginTop="40dp"
android:text="#string/multiply" />
<Button
android:id="#+id/compute_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/compute_multiply"
android:layout_alignBottom="#+id/compute_multiply"
android:layout_alignLeft="#+id/num2TextField"
android:text="#string/add" />
</RelativeLayout>
Here is my ComputeFragment.java code:
public class ComputeFragment extends Fragment {
String num1;
String num2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_compute, parent, false);
// Add Button
Button addButton = (Button)v.findViewById(R.id.compute_add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ERROR STARTS HERE!
EditText num1Field = (EditText)v.findViewById(R.id.num1TextField);
num1 = num1Field.getText().toString(); // Null Pointer Exception is thrown here!
EditText num2Field = (EditText)v.findViewById(R.id.num2TextField);
num2 = num2Field.getText().toString();
// ERROR ENDS HERE!
Intent i = new Intent(getActivity(), AddActivity.class);
i.putExtra("x", num1);
i.putExtra("y", num2);
startActivityForResult(i,0);
}
});
return v;
}
}

The parameter v in EditText num1Field = (EditText)v.findViewById(R.id.num1TextField); is your button, not the whole view.
You should declare the variable in onCreateView:
final EditText num1Field = (EditText)v.findViewById(R.id.num1TextField);
And use it to get the value in onClick
num1 = num1Field.getText().toString();

The parameter view is the button. If the button is on the same parent as the editTexts you could also do:
View parentView = (View) view.getParent();
EditText num1TextField = (EditText)parentView.findViewById(R.id.num1TextField);

Try this code -
#Override
public void onClick(View view) {
EditText num1Field = (EditText)v.findViewById(R.id.num1TextField);
if(num1Field.getText().length() > 0) {
num1 = num1Field.getText().toString();
}
}

Related

How to use one button to getText and setText to 3 different EditTexts and TextViews

It's quite simple. I have a button that has an onClickListener which takes a text from EditText, hides it and sets it to TextView which it shows in the same place.
Now, i want to do that to 2 more different edit texts and text views with the same button. Code below.
XML with my buttons:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context = ".profil"
android:orientation = "vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="230dp"
android:background="#color/pozadina"
android:id="#+id/rltv">
<ImageView
android:id="#+id/slikaProfil"
android:layout_width="130dp"
android:layout_height="160dp"
android:src="#drawable/profilna"
android:layout_centerInParent="true"/>
<TextView
android:id="#+id/textProfil1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/userProfil"
android:layout_below="#+id/slikaProfil"
android:layout_centerInParent="true"
android:textSize="20sp"
android:textStyle="bold"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#+id/rltv">
<TextView
android:id="#+id/imeProfil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Account info"
android:textSize="30sp"
android:textStyle="bold"
android:layout_marginLeft="50dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ime i prezime"
android:layout_marginLeft="70dp"
android:drawableLeft="#drawable/profil"
android:drawablePadding="5dp"
android:id="#+id/imeProfil1"
android:textSize="16sp"
android:layout_below="#+id/imeProfil"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Upisite ime i prezime"
android:layout_marginTop="-5dp"
android:layout_marginLeft="70dp"
android:id="#+id/imeProfil2"
android:textSize="16sp"
android:background="#null"
android:layout_below="#+id/imeProfil1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Telefon"
android:layout_marginLeft="70dp"
android:drawableLeft="#drawable/telefon"
android:drawablePadding="5dp"
android:id="#+id/telefonProfil1"
android:textSize="16sp"
android:layout_below="#+id/imeProfil2"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Upisite broj telefona"
android:layout_marginTop="-5dp"
android:layout_marginLeft="70dp"
android:id="#+id/telefonProfil2"
android:textSize="16sp"
android:background="#null"
android:layout_below="#+id/telefonProfil1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E-mail"
android:layout_marginLeft="70dp"
android:drawableLeft="#drawable/mail"
android:drawablePadding="5dp"
android:id="#+id/mailProfil1"
android:textSize="16sp"
android:layout_below="#+id/telefonProfil2"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Upisite e-mail"
android:layout_marginTop="-5dp"
android:layout_marginLeft="70dp"
android:id="#+id/mailProfil2"
android:textSize="16sp"
android:background="#null"
android:layout_below="#+id/mailProfil1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Adresa"
android:layout_marginLeft="70dp"
android:drawableLeft="#drawable/adresa"
android:drawablePadding="5dp"
android:id="#+id/adresaProfil1"
android:textSize="16sp"
android:layout_below="#+id/mailProfil2"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Upisite adresu"
android:layout_marginTop="-5dp"
android:layout_marginLeft="70dp"
android:id="#+id/adresaProfil2"
android:textSize="16sp"
android:background="#null"
android:layout_below="#+id/adresaProfil1"
/>
<Button
android:id="#+id/prihvati"
android:layout_width="150dp"
android:layout_height="70dp"
android:layout_below="#+id/adresaProfil2"
android:layout_marginLeft="70dp"
android:text="#string/submit"
android:onClick="zamijeni"/>
</RelativeLayout>
</RelativeLayout>
My java file:
public class profil extends Fragment {
private Button dugme4;
private TextView text1;
private EditText text2;
public profil(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.activity_profil, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
text1 = view.findViewById(R.id.imeProfil1);
text2 = view.findViewById(R.id.imeProfil2);
dugme4 = view.findViewById(R.id.prihvati);
text2.setVisibility(View.INVISIBLE);
dugme4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tekst = text2.getText().toString();
if (text1.getVisibility()== View.VISIBLE){
text1.setVisibility(View.INVISIBLE);
text2.setVisibility(View.VISIBLE);
}else if (text2.getVisibility() == View.VISIBLE){
text2.setVisibility(View.INVISIBLE);
text1.setVisibility(View.VISIBLE);
text1.setText(tekst);
}
}
});
}
}
So as you see i have an if function that on click gets the text, makes the edit text invisible and text visible and at the end sets the text to the textView.
Should i do a few more if functions or should it be done differently.
You should implement the same logic to access the text from EditText and display it in the TextView, you can make a function which should be called on the click of this button.
You can achive this more efficiently by use only a edittext.. no need to use text view.. I am giving a sample demo below
public class profil extends Fragment {
private Button dugme4;
//private TextView text1;
private EditText text2;
public profil(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.activity_profil, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// text1 = view.findViewById(R.id.imeProfil1);
text2 = view.findViewById(R.id.imeProfil2);
dugme4 = view.findViewById(R.id.prihvati);
// text2.setVisibility(View.INVISIBLE);
dugme4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text2.isEnabled()){
//make it not editable and non focusable
text2.setEnable(false);
text2.setCursorVisible(false);
//for clearing underline of editText so that it looks like textview
text2.setBackgroundResource(android.R.color.transparent);
}else{
text2.setEnabled(true);
text2.setCursonVisible(true);
// set any color what you want as underline
text2.setBackgroundResource(android.R.color.black);
}
}
});
}
}
Try it.hope it will solve your problem by reducing extra element and complexity.

Getting error while calling Intent from fragment (User Login)

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);

Cannot access resources in a layout in a PopupWindow, Objects are null referenced

I have an android application when clicked on an option from a side bar it goes to a fragment, and then into another fragment which has clickable radio buttons. When clicked on these it will create a popup window with some text fields in it.
Basically this is how the flow goes,
Activity --> Fragment 1 --> Fragment 2 --> PopupWindow
When i try to access the resources inside this popupWindow, in example:
damageComponenetAutoCompleteTextview = (AutoCompleteTextView) findViewById(R.id.popup_damage_component_item);
damageComponenetAutoCompleteTextview.requestFocus();
in the line damageComponenetAutoCompleteTextview.requestFocus(); it gives me an error,
Attempt to invoke virtual method on a null object reference
I believe it's due to a wrong view i'm referring when calling on the Resources. Hope someone could point me to what i'm doing wrong. Thanks in Advance.
This is the method i'm using to create the popupWindow.
public void showDamagedItemEntryPopup(RadioButton radioButton, View view){
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup viewG = ((ViewGroup)view.findViewById(R.id.damaged_comp_popup));
//I tried passing the root view to inflate() method instead of passing it null. Didn't work.
//View popupView = layoutInflater.inflate(R.layout.component_selection_popup, null);
View popupView = layoutInflater.inflate(R.layout.component_selection_popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setAnimationStyle(R.style.popupAnimation);
//I tried setting the content view manually but didnt work
//popupWindow.setContentView(view.findViewById(R.id.damaged_comp_popup));
Button buttonClose = (Button)popupView.findViewById(R.id.close_add_component_btn);
// Close button damaged item popop window
buttonClose.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
originalAmount = (EditText)this.findViewById(R.id.popup_add_component_original_amount);
customerContribution = (EditText)this.findViewById(R.id.popup_percentage);
quantity = (EditText)this.findViewById(R.id.popup_quantity);
finalAmount = (EditText)this.findViewById(R.id.popup_add_component_final_amount);
remarks = (EditText)this.findViewById(R.id.popup_add_component_remarks);
// Item Spinner
itemSpinnerArray = new ArrayList<String>();
itemSpinnerArray.add("Select Item");
// Status Spinner
ArrayList<String> statusSpinnerArray = new ArrayList<String>();
statusSpinnerArray.add("MR");
statusSpinnerArray.add("DR");
statusSpinnerArray.add("SP");
// Error comes at this point initially. When these Resource access line codes are commented, the popup works fine.
damageComponenetAutoCompleteTextview = (AutoCompleteTextView) findViewById(R.id.popup_damage_component_item);
damageComponenetAutoCompleteTextview.requestFocus();
ArrayAdapter<String> itemSpinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemSpinnerArray);
damageComponenetAutoCompleteTextview.setThreshold(1);
damageComponenetAutoCompleteTextview.setAdapter(itemSpinnerArrayAdapter);
damageComponenetAutoCompleteTextview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//int index = cityNames.indexOf(actvCity.getText().toString());
itemSpinnerValue = (String) parent.getItemAtPosition(position);
Log.d("SK-->", "----------------------------------------------------------");
Log.d("SK-->","itemSpinnerValue: " + itemSpinnerValue);
}
});
statusSpinner = (Spinner)this.findViewById(R.id.popup_status_spinner);
ArrayAdapter<String> statusSpinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, statusSpinnerArray);
statusSpinner.setAdapter(statusSpinnerArrayAdapter);
//Creating a text Watcher
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
//here, after we introduced something in the EditText we get the string from it
//String answerString = originalAmount.getText().toString();
if (originalAmount.getText().toString().trim().equals("") || customerContribution.getText().toString().trim().equals("")
|| quantity.getText().toString().trim().equals("")) {
// Error , one or more editText are empty
}
else
{
calculateFinalAmount();
}
//and now we make a Toast
//modify "yourActivity.this" with your activity name .this
//Toast.makeText(yourActivity.this,"The string from EditText is: "+answerString,0).show();
}
};
// Adding Text Watcher to our text boxes
originalAmount.addTextChangedListener(textWatcher);
customerContribution.addTextChangedListener(textWatcher);
quantity.addTextChangedListener(textWatcher);
// Show the popup
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
This is the XML i'm using for the popup.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/damaged_comp_popup"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/popup_wire">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="2dp"
android:background="#color/popup_background">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/popup_damage_component_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:hint="#string/damaged_componenet_item_string"/>
<Spinner
android:id="#+id/popup_status_spinner"
android:layout_width="122dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/popup_damage_component_item"
android:layout_marginLeft="10dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="5dp"
android:layout_marginRight="5dp" />
<EditText
android:id="#+id/popup_add_component_original_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/popup_damage_component_item"
android:layout_alignParentRight="true"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="22dp"
android:layout_toRightOf="#+id/popup_status_spinner"
android:ems="10"
android:hint="#string/original_amount_string"
android:inputType="number" />
<EditText
android:id="#+id/popup_percentage"
android:layout_width="52dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/popup_status_spinner"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="2dp"
android:layout_marginTop="22dp"
android:ems="10"
android:hint="#string/percentage_string"
android:inputType="number" />
<TextView
android:id="#+id/popup_percentageMark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/popup_percentage"
android:layout_toRightOf="#+id/popup_percentage"
android:text="#string/percentage_string"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="1dp"
android:layout_marginRight="0dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<EditText
android:id="#+id/popup_quantity"
android:layout_width="46dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/popup_percentage"
android:layout_alignBottom="#+id/popup_percentage"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="6dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/popup_percentageMark"
android:ems="10"
android:hint="#string/quantity_string"
android:inputType="number" />
<EditText
android:id="#+id/popup_add_component_final_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/popup_quantity"
android:layout_alignBottom="#+id/popup_quantity"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/popup_quantity"
android:ems="10"
android:hint="#string/final_amount_string"
android:inputType="number" />
<EditText
android:id="#+id/popup_add_component_remarks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/popup_percentage"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="22dp"
android:ems="10"
android:hint="#string/remarks_string"
android:inputType="text|textMultiLine" />
<Button
android:id="#+id/add_component_btn"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="200dp"
android:layout_below="#+id/popup_add_component_remarks"
android:background="#drawable/correct"
android:layout_marginBottom="15dp"
android:onClick="onSaveItem"/>
<Button
android:id="#+id/close_add_component_btn"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_below="#+id/popup_add_component_remarks"
android:layout_toRightOf="#+id/add_component_btn"
android:layout_marginLeft="10dp"
android:background="#drawable/cancel"/>
</RelativeLayout>
</LinearLayout>
It seems your damageComponenetAutoCompleteTextview belongs to the popupWindow which you inflated at top.
So try changing
damageComponenetAutoCompleteTextview = (AutoCompleteTextView) findViewById(R.id.popup_damage_component_item);
To
damageComponenetAutoCompleteTextview = (AutoCompleteTextView) popupView.findViewById(R.id.popup_damage_component_item);
And other relevant elements as well.

getCheckedRadioButtonId just gives me nullpoint exception

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

Getting error while accessing textfield in Android application

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.

Categories

Resources