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.
Related
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();
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.
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)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When I launch my app this problem shows. This is my Java code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
ImageView imageView = new ImageView(this);
imageView.setBackgroundColor(Color.WHITE);
SVG svg = SVGParser.getSVGFromResource(getResources(), raw.canel);`
imageView.setImageDrawable(svg.createPictureDrawable());
setContentView(imageView);
}
This is the line where the exception is thrown:
SVG svg = SVGParser.getSVGFromResource(getResources(), raw.canel);
There are two possibilities: either SVGParser is null and therefore has no getSVGFromResource, or raw is null and has no canel member.
If your error is that SVGParser is null, then the problem is that you did not import SVGParser. In this case the solution is to import the package which contains SVGParser, since it is a class and it was not imported, therefore the compiler thinks it is a variable and has not been initialized.
If your error is that raw is null, then the solution is to initialize it. In this case you have missed the part where the variable is being initialized. It is quite possible that you initialize it correctly, but after onCreate is being called, therefore the member is not initialized yet when you try to use it.
We need more information about the problem to give you a more specific solution.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
-edit 2. Tested this on my mobile works as intended. Stupid android avd
I am getting a error and i am not quite sure how to fix it. I could remove the need for caching the image but that would increase the bandwidth needed for the application.
My current code should work but it is throwing a NullPointerException
here is the error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference
at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:232)
at com.program.programmy.application.FileCache.<init>(FileCache.java:18)
and this is the code causing the problem is the one surrounded by ** line 18
public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"ParseListViewImgTxt");
else
**cacheDir = context.getCacheDir();**
if (!cacheDir.exists())
cacheDir.mkdirs();
}
if someone could help out with this one little thing my program should work no problem. cheers
-Edit
This is only when i try to leave the list intent to look at a single object. Here is some more code from the area that prompts the error
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SingleItemView.class);
context.startActivity(intent);
}
});
Also here is a link to something similar that i am doing except no one is having the problem i am
Whenever your constructor is called, you are not sending any object in context.
Exception occurred as context object is null, and you are calling getCacheDir() method on it.
If you have problem in getting context object. Please read top voted answer in following link:
Static way to get 'Context' on Android?