I have this error nullpointerexception, when i do getText().toString() from EditTex:
public class SendMessActivity extends SherlockFragmentActivity {
private EditText tEmail;
private Button sendButton;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_mess_layout);
tEmail = (EditText)findViewById(R.id.editEmailTo);
sendButton = (Button)findViewById(R.id.btn_sendmess);
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String textEmail = tEmail.getText().toString(); //nullpointerexception
Editable textEmail1Editable = tEmail.getText(); //nullpointerexception
String textEmail = textEmail1Editable.toString()
Log.d(DEBUGTAG, "SENDING START:::::::: " + textEmail);
}
});
}}
Please, tell me how to do it
UPDATE Q
David, thank you, for your surmise,the problem was really in the my tangled Layouts
I had all 4 levels of nesting LinearLayouts.
After I left the simplified scheme and only 2 levels I have, all began to work
You need to call setContentView(your_layout.xml) so it knows what layout to use. Without setting the layout, all of your calls to findViewById(...) that try to find the views in your layout will return null.
public class SendMessActivity extends SherlockFragmentActivity {
private EditText tEmail;
private Button sendButton;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(your_layout.xml); //set your activity layout here.
tEmail = (EditText)findViewById(R.id.editEmailTo);
sendButton = (Button)findViewById(R.id.btn_sendmess);
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String textEmail = tEmail.getText().toString(); //nullpointerexception
Log.d(DEBUGTAG, "SENDING START:::::::: " + textEmail);
}
});
}}
If you have no assigned text then I would assume that the EditText retrieval of the text would be a null entry and you are attempting to make a string of that null entry.
Related
can i know pls why the input variable why it's giving me error always, thank you so much.
This is my code below:
public class MainActivity extends AppCompatActivity {
public TextView textView;
public EditText editText;
public Button btn;
public int input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);
editText = findViewById(R.id.editText);
btn = findViewById(R.id.btn);
` input= Integer.parseInt(editText.getText().toString());`
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(input );
}
});
}
}
The error is happening as the String cant be cast to an integer. This could be because your editText is empty or that you have characters that are not integers in there (E.g. Letters). Therefor you should use try and catch to catch the error.
Currently you are trying to parse the input string from editText in onCreate() as soon as the view is created. This will try to parse the default text associated with the editText. I think what you want is to parse the input at the time of clicking button. In that case move the input parsing code inside onClick(). Also it is better to catch NumberFormatException when calling parseInt() if you cannot guarantee that the text entered in the EditText is always an integer.
#Override
public void onClick(View v) {
android.util.Log.i("MyActivity", "onClick: edit text = " + editText.getText());
input= Integer.parseInt(editText.getText().toString());
textView.setText(input );
}
I have a ViewPager with 3 fragments in it, each fragment has a next and prev. button, and you can also swipe left and right to navigate through fragments. and although I'm able to get the input from each fragment when the next button is clicked, I sill can't figure out a way to get the input when the user scrolls between fragments.
this is the code in my first fragment:
public class signupfrag1 extends Fragment {
private TextInputEditText fName, lName;
public Spinner spncountry, spncity;
private Button next1;
private String vfName, vlName, vcountry, vcity;
private String method;
signupfrag1Listener activityCommander;
public interface signupfrag1Listener{
public void getDataFromFrag1(String fName, String lName, String countryName, String cityName);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (signupfrag1Listener) context;
}catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.signupfrag1, container, false);
fName = (TextInputEditText) view.findViewById(R.id.edtFName);
lName = (TextInputEditText) view.findViewById(R.id.edtLName);
spncountry = (Spinner) view.findViewById(R.id.cmbCountry);
spncity = (Spinner) view.findViewById(R.id.cmbCities);
next1 = (Button) view.findViewById(R.id.btnNext2);
next1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vfName = fName.getText().toString();
vlName = lName.getText().toString();
if(vfName.equals("") || vfName.length()==1){
fName.setError("please enter a correct first name!");
}
else if(vlName.equals("") || vlName.length()==1){
lName.setError("Please enter a correct first name!");
}
else
startFrag2(view);
}
});}
public void startFrag2(View view){
activityCommander.getDataFromFrag1(vfName, vlName, vcity, vcountry);
}
this is the code from my main activity:
public class Main2Activityforfragments extends AppCompatActivity implements signupfrag1.signupfrag1Listener, signupfrag2.signupfrag2Listener {
private ViewPager fragsViewPager;
private SectionsPagerAdapter1 sectionsPagerAdapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2_activityforfragments);
fragsViewPager = (ViewPager) findViewById(R.id.fragsViewPager);
sectionsPagerAdapter1 = new SectionsPagerAdapter1(getSupportFragmentManager());
fragsViewPager.setAdapter(sectionsPagerAdapter1);
}
//this get called when the next button is clicked
#Override
public void getDataFromFrag1(String fName, String lName, String cityName, String countryName) {
if(fragsViewPager.getCurrentItem() == 0){
fragsViewPager.setCurrentItem(1);}
}
if you are in the first fragment then create ref. of interface and call its method and pass the values on Click what you want and it is needed to implement Two interface in SecondFragment. call its method in the First Fragment. you can create interface Two in SecondFragment
Two Second=new SecondFragment(); // it will be called on click of firstFragment which pass the value.
Second.two("Value one","Value two");
interface Two{
void two(String value,String value); // implement this inteface in SecondFragment and call it in FirstFragment
}
When you reach to second you get the value from the first fragment and continue with the third fragment as same.
signup screen with of two different modules driver and customer
Hi everyone I am working in android from past one year but now I am creating an app in which am using fragments instead of activity even after serching from so many sites and blogs am unable to implement what I want.
My requirement is as you see on the image two radio button one for customer and one for driver so when user click on any one of options then signup screen appears which is on fragment and one button is there at bottom which is on activity so I want how to get all edittext value on button click so that i can send these values to the server. My main problem is getting the values of edittext fields on button click.
So any help will be appriciated.
thanks in advance
Try like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
this.initViews(rootView);
selectProfessionsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
whta_you_want_on_button_click();
}
});
}
private void initViews(View view) {
//define your edittext like FirstNameEditText = (EditText) view.findViewById(R.id.FirstNameEditText);
}
now define the whta_you_want_on_button_click() method
in your activity, put below code in your button's click event.
try {
Fragment rg = getSupportFragmentManager().findFragmentByTag("YourFragmentTag");
if (rg != null) {
EditText et = (EditText) ((YourFragment) rg).getView().findViewById(R.id.edittext);
String etValue = et.getText().toString();
}
} catch (Exception e) {
}
Your context will change from getApplicationContext() to getActivity.getApplicationContext() when you are referencing a fragment instead of an activity
You have to create your edittext in this fashion
While assigning the layout you need to assign in this way.
View view = inflater.inflate(R.layout.fragmentlayout,container,false);
And while assigning edittext you need to take it as below
EditText edt = (EditText) view.findViewById(R.id.yourid);
String str = edt.getText().toString();
So on button click you can get the edittext string easily from onClick method with above code.
You can use static keyword make all edittext static so you will get all edittext values in activity on button click.
in your fragment suppose MyFragment.java
public class MyFragment extends Fragment{
View rootView;
public static EditText edt;
public MyFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
init();
return rootView;
}
protected void init(){
edt = (EditText) rootView.findViewById(R.id.edt);
}
}
in your activity suppose MainActivity.java
public class MainActivity extends Activity{
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewByid(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String value = MyFragment.edt.getText().toString().trim();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
});
}
}
I am creating button dynamically in linearlayout horizontalscrollview and on click i get selected button position.
I want to know how to change text color of selected button?
Here is my code.
String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT", "SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"};
private LinearLayout ll;
Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);
for(int i = 0; i < categories.length; i++) {
btn = new Button(this);
btn.setText(categories[i]);
btn.setBackgroundColor(Color.parseColor("#ffffff"));
btn.setOnClickListener(buttonClick);
ll.addView(btn);
int idx = ll.indexOfChild(btn);
btn.setTag(Integer.toString(idx));
// btn.setId(idx);
}
}
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
//(String)v.getTag();
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};
check the type and assign the text color
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
if(v instanceof Button){
((Button)v).setTextColor(Color.parseColor("#000000"));
}
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};
try this
Edited Answer
((Button)view).setTextColor(Color.parseColor("#000000"));
please check the following answer here and here .
as you can see you can do it programmatically and through xml by creating a style file for all of the states of the button .
Hope that helps
This works:
button.setTextColor(getColor(R.color.blue))
I just check all already posted solutions. No one works.
They also produce error like this
btnjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setTextColor(int)' on a null object reference
Real Solution :
Step-1: When you try to change setTextColor then always use try/catch, to prevent app from Crash.
Step-2: No matter you define your Button already, define(like R.id.btnId) again before setTextColor code line.
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.btnId);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use try/catch for handle any kind of error
try {
Button btnForTextColorChange= (Button) findViewById(R.id.btnId);
// must define Button again before setTexColor code line
btnForTextColorChange.setTextColor(getResources().getColor(R.color.white));
} catch (Exception e){
Log.e(TAG, "Error:"+e);
}
}
});
}
[sorry for bad english]
Happy Coding :)
This worked for me:
btnItem.setTextColor(ContextCompat.getColor(context, R.color.black))
I have found a very good solution to my problem on another post (Save entered text in editText via button)
however when I implement this code, my application crashes. Any advice would be appreciated, the error I receive is that the "String or" in the method makeTag() is not used. Please have a look
private Button savenotebutton1;
private SharedPreferences savednotes;
private EditText editText1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.x1);
savenotebutton1 = (Button) findViewById(R.id.savenotebutton1);
editText1 = (EditText) findViewById(R.id.noteEditText1);
savednotes = getSharedPreferences("notes",MODE_PRIVATE);
editText1.setText(savednotes.getString("tag", "Default Value")); //add this line
savenotebutton1.setOnClickListener(saveButtonListener);
}
private void makeTag(String tag){
String or = savednotes.getString(tag, null);
SharedPreferences.Editor preferencesEditor = savednotes.edit();
preferencesEditor.putString("tag",tag); //change this line to this
preferencesEditor.commit();
}
public OnClickListener saveButtonListener = new OnClickListener(){
#Override
public void onClick(View v) {
if(editText1.getText().length()>0){
makeTag(editText1.getText().toString());
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText1.getWindowToken(),0);
}
}
};
}
You should replace this
String or = savednotes.getString(tag, null);
With
String or = savednotes.getString("tag", "Default Value")
Under your makeTag() function
Update: Error is about you are not register your activity into manifest.xml file.