Programmatically get hint text value in android Edittext [duplicate] - java

This question already has answers here:
EditText getHint() returns null when using design support library
(4 answers)
Closed 6 years ago.
I have to change theTypeface of EditText dynamically and also process the hint text if the Typeface changed. I simply do as following:
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_textBox"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/textBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_date" />
</android.support.design.widget.TextInputLayout>
And my code snippet is as follow:
EditText textBox = (EditText) findViewById(R.id.textBox);
Typeface tf = Typeface.createFromAsset(this, "myfont.ttf");
textBox.setTypeface(tf);
String hintText = textBox.getHint().toString(); //Got NullPointerException here....
String newText = processText(hintText); //This will process the hint text;
textBox.setHint(newText);
When I runt the program, I got the following exception:
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
Please help me to solve this problem.

We need to look at your_layout.xml first to determine that, but you're probably using the design support lib.
If so, you can get your hints as follows:
((TextInputLayout)textBox.getParent()).getHint();
Note
This has already been answered here. (Although we needed to make sure that you were using the design support lin to mark your question as duplicate)

Related

creating android library from fragment [duplicate]

This question already has answers here:
how to get a fragment added in an XML layout
(5 answers)
Closed last year.
i'm having a fragment that i want to use it as a library in other projects.
i created a library module and copy-paste all my fragment code and resources to library mode and then to use that library module i'm writing the following code in activity's xml
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="com.dhirunand.meter.MeterFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
and in java file
MeterFragment meterFragment = new MeterFragment();
String selectedNumber = meterFragment.getSelectedNumber();
visually library mudule is working fine but i'm not able to fetch data from the library module
project github url https://github.com/dhirunand/meter--number-picker
when you are using new MeterFragment() line then you are creating NEW fragment, not using one attached to FragmentContainerView. this NEW one isn't visible on screen, its just created in memory, not shown (as you haven't posted attaching code), so getSelectedNumber() will return default value instead this set in MeterFragment attached to FragmentContainerView
you should obtain this "real" existing and visible instance from XML by
FragmentContainerView fcv = (FragmentContainerView) findViewById(R.id.fragmentContainerView);
MeterFragment meterFragment = (MeterFragment) fcv.getFragment();

Getting NullPointerException first time when Activity loads but working fine second time

I am starting EditCardActivity from MainActivity.
The app crashes first time and Android system shows an alert to "Open App Again".
When I reopen the app, it works as expected.
I have seen many answers on this site and I have done following according to those answers but it didn't work.
I have called the setContentView() inside onCreate() method before calling findViewByID().
I have verified that the ID I am passing in findViewByID() is spelled correctly.
I also tried to make the EditText a class member too and initialize it in onCreate() method.
I also tried using onStart(), onPostCreate() methods too.
I feel that the View has not been loaded when I am trying to call it and thus findViewByID() returns null. Hence I tried using Thread.sleep(1000) to give it 1 second to load but still same issue.
Here's the part of code that is having problem.
// MainActivity.java
public void editCard(View v) {
Intent i = new Intent(this, EditCardActivity.class);
startActivity(i);
}
<!--activity_edit_card.xml-->
...
<EditText
android:id="#+id/add_card_category_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin"
android:ems="10"
android:hint="#string/add_card_category_et_hint"
android:inputType="text"
android:textSize="#dimen/font_size" />
...
// EditCardActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_card);
showContents();
}
private void showContents() {
EditText editCardCategoryET = findViewById(R.id.add_card_category_et);
editCardCategoryET.setText(currentCard.getCategory()); // This line is throwing NullPointerException
}
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Edit:
I got what was causing the error.
I was referring to the add_card_category_et instead of edit_card_category_et.
The former view belonged to the different layout file of another Activity of my application.
I am sorry I couldn't catch this small error.
Although small, it made me stuck for 3 days.
Anyway thanks for your answers and comments.
Because editCardCategoryET cant find any value. So it throws Exception. It can be solve by add extra character by adding " " . Then app will not crush. editCardCategoryET.setText(" "+currentCard.getCategory()); .
Also you can handle it in a try(), catch() method.

Why I can't enforce EditTextPreference to take just numbers?

GOAL: Use EditTextPreference to take a number input from an user.
PROBLEM: I'm using support.v7.preference and, from what I've understood, this library bring problems to creates a custom DialogPreference (HowTo use support.v7.preference with AppCompat and potential drawbacks). Anyway I tried to create a NumberPickerPreference extending DialogPreference but I got ClassCastException.
Also I found another approach: programmatically set the input type of an EditTextPreference object like below:
EditTextPreference pref = (EditTextPreference) findPreference("pref_edit_text");
if (pref != null) {
pref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
}
No way, I always get a ClassCastException .
Last approach I tried : modify the xml
android:inputType="numberDecimal"
android:digits="0123456789"
or android:numeric="integer"
No way again, on the Dialog I get the full keyboard, so the user can write everything.
Is there a way to properly enforce EditTextReference to take just number input?
You can do it by adding android: inputType = "numberPassword" to your XML file
Then you can set your custom keyboard programmatically in your java like this:
yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
The next thing you could do is to create a custom class:
private class YourNumericKeyboardMethod extends PasswordTransformationMethod {
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
The last step is to implement it to your EditText in order to make it display only the numbers:
yourEditText.setTransformationMethod(new YourNumericKeyboardMethod());
After all this steps you should get a keyboard that has only numbers from 0 to 9 on it
Try one of these:
android:inputType="numberSigned"
android:inputType="phone"
EDIT:
android:inputType="numberDecimal|numberSigned"
android:digits="0123456789"
EDIT:
There´s this lib that is supposed to make it work, if you´re willing to try:
https://github.com/Gericop/Android-Support-Preference-V7-Fix
Reading their github page you can find examples of custom inputs and their example code that looks similar to what you are doing now:
"The sample app shows an example of setting (via XML) and querying (programmatically) the input type of the EditTextPreference:
<EditTextPreference
android:inputType="phone"
android:key="edit_text_test" />
EditTextPreference etPref = (EditTextPreference) findPreference("edit_text_test");
if (etPref != null) {
int inputType = etPref.getEditText().getInputType();
// do something with inputType
}
Try to set inputType as the number.
android:inputType="number"

Android Button OnClickListener Null Pointer [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
Within my onCreate method:
add = (Button)findViewById(R.id.add);
add.setOnClickListener(new MyOnClickListener()); //null pointer here
public class MyOnClickListener implements OnClickListener
{
#Override
public void onClick(View v)
{
//send information to database
}
}
XML File
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/hello"
android:layout_alignBottom="#+id/hello"
android:layout_alignRight="#+id/id"
android:layout_marginRight="72dp"
android:text="Add" />
I know there are two ways to do it one using the XML attribute and the other way is the one I chose using setOnClickListener. I read another post and it said to clean the project however I am still getting a null pointer exception. What is wrong?
If you using Eclipse, try to clean project, maybe your R.java auto generated file is broken.

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I have the following layout (virtually empty):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/set_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="content desc"
android:orientation="vertical" >
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
</LinearLayout>
The Activity class contains the following:
public class TestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
}
When I run this on my mobile device I get the following error:
SpannableStringBuilder
SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
I have tried this with and without the TextView and the error still remains, I must be doing something fundamentally wrong for such a basic layout to cause this.
Does anyone have any ideas on how I can get this to load without the error?
I have run into the same error entries in LogCat. In my case it's caused by the 3rd party keyboard I am using. When I change it back to Android keyboard, the error entry does not show up any more.
Because the error you're getting is not related to an EditText, then it's not related to your keyboard.
The errors you are getting are not a result of your code; you probably are testing on a Samsung device that has Samsung's TouchWiz.
I had the same errors, then I tested on a Nexus S (also by Samsung, but pure Android OS without TouchWiz) and I didn't get this error.
So, in your case, just ignore these errors while testing on a device! :)
Looking at your code, I'm not sure why you're getting that error, but I had this same error but with EditText fields.
Changing android:inputType="text" (or any of the other inputType text variations) to android:inputType="textNoSuggestions" (or android:inputType="textEmailAddress|textNoSuggestions", for example) fixed it for me.
You can also set this in Code with something like
mInputField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
Looks like Android assumes by default that EditText fields will have suggestions. When they don't, it errors. Not 100% confident in that explanation, but the above mentioned changes fixed it for me.
http://developer.android.com/reference/android/text/Spanned.html#SPAN_EXCLUSIVE_EXCLUSIVE
Hope this helps!
On your android phone go to:
settings -> application manager -> all -> samsung keyboard and then click on "clear cache"
(delete all data collected by this application).
Try using the default Android keyboard it will disappear
Make clear you have pass a value in your MainAcitivity for the following methods onCreateOptionsMenu and onCreate
In some cases, the developer deletes the "return super.onCreateOptionsMenu(menu)" statement and changed to "return true".
This worked for me...on every device
<EditText
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="15sp"
android:layout_centerVertical="true"
android:textColor="#000"
android:id="#+id/input_search"
android:background="#null"
android:inputType="text"
android:hint="Enter Address, City or Zip Code"
android:imeOptions="actionSearch"
/>
In Java code:
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
//execute our method for searching
}
return false;
}
});
I had the same warning and found that removing an unused #id got rid of the warning. For me it was obvious as the #id was associated with a growing list of textViews linked to a database, so there was a warning for each entry.
Masood Moshref is right, this error occur because the option menu of Menu is not well prepared by lacking "return super.onCreateOptionsMenu(menu)" in onCreate() method.
To try to debug this error, first go to your android terminal / console and execute this command:
ps | grep THE_ERROR_PID_YOU_GET_(IT_IS_A_NUMBER)
then if the output comes out as your app... it is your app causing the error. Try to look for empty Strings that you pass into the layout.
I had this exact same problem and it was my fault as I was passing an empty String into my layout. After changing the "" to " " this error went away.
If you don't get your app from the console output, then it is something else causing it (probably, as others said, the android keyboard)
I have faced the same issue. I almost wasted almost couple of weeks to resolved this issue.
Finally I had on doubt on myself and tried to create another project by copy and paste some startup files like SplashScreen & LoginScreen.
But with the same code still i was getting SPAN_EXCLUSIVE_EXCLUSIVE.
Then i have removed the handler code from splash screen and tried again and Wow its working.
I am not getting SPAN_EXCLUSIVE_EXCLUSIVE issue in logcat.
I wondering, why it is? till the time did not get any other solution but by removing handler from splash screen it is working.
Try and update here if it is resolved or not.
Check if you have any element such as button or text view duplicated (copied twice) in the screen where this encounters. I did this unnoticed and had to face the same issue.
I ran into this problem too when I copied some text from the Internet. My solution is to trim the text/remove formatting before doing any further processing.
I had the same problem but with a listView.... i solved it because i was using a wrong R.id.listView that list View needed to have a value, in my case it was strings that i saved on listView2... so the right code was R.id.listView2
I had the same problem then i fixed it by following code!
text = (EditText)findViewById(R.id.TextVoiceeditText);
text.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
this error also occurs due to changed API URL. try hitting the URL you are using in postman and c if it's working properly.
rechecking the APIs solved my problem
try avoiding use of view in xml design.I too had the same probem but when I removed the view. its worked perfectly.
like example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="number"
android:textColor="#fff" />
<view
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f9d7db" />
also check and try changing by trial and error android:inputType="number" to android:inputType="text" or better not using it if not required .Sometimes keyboard stuck and gets error in some of the devices.
In my case, the EditText fields with inputType as text / textCapCharacters were casing this error. I noticed this in my logcat whenever I used backspace to completely remove the text typed in any of these fields.
The solution which worked for me was to change the inputType of those fields to textNoSuggestions as this was the most suited type and didn't give me any unwanted errors anymore.
in my case i click on recent apps shortcut on my cell phone and close all apps. This solution always work for me, because this error not related to code.
**DONT PUT SET TEXT IN TEXT WATCHER**etSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
visibleResultList = false
if (s.toString().length != 0) {
getSearchSuggetion(no_of_rec, 0, s.toString())
} else {
// etSearch.setText("")
}
Log.e("text_change","============"+s.toString())
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
})
To solve this problem just add android:usesCleartextTraffic="true" in your AndroidManifest.xml file which is at ..\app\src\main\AndroidManifest.xml just like bellow...

Categories

Resources