This question already has answers here:
Can not find a View with findViewById()
(4 answers)
Closed 5 years ago.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String test = "test";
TextView text = (TextView) findViewById(R.id.textView);
text.setText(test);
setContentView(R.layout.activity_main);
}
The problem started in a fragment, I tried all StackOverflow solutions to no avail so I made a fresh build and now I'm just trying to make it work in MainActivity. Can someone please explain why this code does not update the textView, and why it is caushing a crash.
Note: I have tried making my own setText() methods, i've tried using strings and char arrays from other safer locations, I've moved the code before and after setContentView(), and if its just another way of coding the above^ in a different way, I've probably tried it. Pretty much each thing I try leads to the same result. This leads me to believe the solution isn't just in the code above, but something else overlooked, and probably a simple fix. Thanks!
EDIT: Here is my xml, my freshman CS senses tingle seeing the android:text="" line.
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
Try this code You must call the setcontentView method before calling findViewById method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String test = "test";
TextView text = (TextView) findViewById(R.id.textView);
text.setText(test);
}
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 2 years ago.
I am new to android programming and I can't figure out what i'm doing wrong.
My code:
Every time I run the code, the emulator works just fine, but when I try to open the app it show the error message.
Please help. Thanks.
first you must inflate your layout by setContentView method .
second in onCreate method , bind your view .
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
TextView tf1 = (TextView) findViewById(R.id.tf0);
tf1.setText("Hello World!");
}
You must call setContentView before calling findViewById.
void onCreate() {
super.onCreate()
setContentView(R.layout.my_activity_layout)
TextView tf1 = findViewById(R.id.tf0)
tf1.setText("hello")
}
You need SetContentView(R.layout.your_layout) before calling findViewById.
For example:
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
tf1 = findViewById(R.id.tf0);
tf1.setText("text")
I suspect tf1 is null because the layout hasnt been inflated yet also setContentView(view) is required to be called in onCreate to inflate the view. Also at the point you are declaring the tf1 (outside onCreate) the reference will be null.
Try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tf1 = (TextView) findViewById(R.id.tf0);
tf1.setText("Hello World!");
}
I'm very new to Android and Java coding in general, so bear with me if I don't understand basic concepts.. This is just a test to see if something works, so It might not initially make any sense.
I have two activities, Main and Other.
the Other Activity has an imageButton with visibility initially set to invisible.
When MainActivity is created, it should look for that imageButton in the Other activity, and set it's view to visible.
Though when debugging, all I get is a nullPointerException, because the button has null as value. How can I make it reference the button?
Part of Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pstep();
}
public void pstep() {
int pstep = 0;
ImageButton panfav = (ImageButton) findViewById(R.id.favpancake);
panfav.setVisibility(View.VISIBLE);
}
Part of Other Activity:
public class navfav extends AppCompatActivity {
ImageButton panfav = (ImageButton) findViewById(R.id.favpancake);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navfav);
}
public void fab(View v){
ImageButton panfav = (ImageButton) findViewById(R.id.favpancake);
panfav.setVisibility(View.VISIBLE);
}
XML linked to Other Activity:
<ImageButton
android:id="#+id/favpancake"
android:layout_width="wrap_content"
android:layout_height="137dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/imageView3"
android:background="#android:color/background_dark"
android:contentDescription="#string/nav_cook_dish"
android:onClick="fab"
android:scaleType="centerCrop"
android:src="#drawable/dishpancake"
android:visibility="invisible" />
Log:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ImageButton.setVisibility(int)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.ImageButton.setVisibility(int)' on a null object reference
at com.p2.rookie.MainActivity.pstep(MainActivity.java:23)
at com.p2.rookie.MainActivity.onCreate(MainActivity.java:16)
Shoot if I'm missing anything you need to use, I'll provide as much as i can :)
Best
The visibility of the buttons are always "VISIBLE", please give me the log
and in the navFav activity the "fab" method are not in the onCreate
you are getting nullPointerException because ImageButton with id favpancake is not present in MainActivity layout activity_main
public class navfav extends AppCompatActivity {
public static List<String> recipes;
// other code here
}
and then when you want to add recipe to shown in Other Activity listView,
recipes = new ArrayList<String>();
recipes.add(recipe);
Now when you open the other Activity all those recipes will be available in list name "recipes". which you can use to show in your listView.
One Activity can and should not reference elements in other Activities.
If you call 'setContentView' with a layout file, you can only reference the views in that layout file.
Try and tell us what you're trying to achieve and we might be able to help you out in improving your code.
(Posted on behalf of the OP).
Just read a bunch of other stuff elsewhere, and I think something made sense now! Instead of creating new intents and startActivity'ies when changing layout/pages, I just setContentView to new layouts/pages, and gather all methods from different activities in one activity - That's how basic this fail was I think? ;)
Then all views and methods can reference each other.
The xml code: -->Also tried with ImageView and buttonView, Picker, and so on, it won't read data from this xml.
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is a textview."
android:background="#f00"></TextView>
Java code where i set the view to the activity containing this XML.
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
Now, what i SHOULD see is this:
What i REALLY see is this:
Also i have declared the java in the android Manifest.
maybe it'll help but This activity is reached by pressing 2 buttons from 2 different activities, I've tested the same logic with a new project and it works, but it doesn't work on my main project.
Make sure that the part where you start your activity with Intents is right.
It should be something like this :
Intent i = new Intent(context, YourActivity.class):
startActivity(i);
if there's no problem with that, try checking your layout's name for any chance of conflict.
At the last try changing your OnCreate to :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
Looks like there is no problem in your XML, but also check the root of your layout.
ANSWER: There was some weird bug i myself don't understand, i removed the java code and re-added it again, and now it suddenly works, Thanks for suggestions everyone.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I do not get any errors but when I run the app it crashes:
public class MainActivity extends AppCompatActivity {
ImageButton Nr1 = (ImageButton) findViewById(R.id.ImageButton1);
public void machwas(View v) {
Nr1.setImageResource(R.drawable.x);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This here is wrong:
public class MainActivity extends AppCompatActivity {
ImageButton Nr1 = (ImageButton)findViewById(R.id.ImageButton1);
because findViewById() should be called INSIDE the onCreate method, the reason is that after that are layouts inflated and you are ready to get the views and initialize the widgets...
so what you are doing is initializing the ImageButton wrongly, probably will be null after that line and then this here
public void machwas(View v){
Nr1.setImageResource(R.drawable.x);
}
is going to explode with a NullPointer Exception...
but this is only an inference because you dont post the LogCat...
For more info please take a look to the Activity lifeCycle and the Official Android Documentation
findViewById() searches the view that is set by setContentView(). In your code findViewById() is called before onCreate() so there's no view set yet and due to that all finds will fail and you will always get null there.
BTW: consider using helpers like ButterKnife
You have to call findViewById after view created.
public class MainActivity extends AppCompatActivity {
ImageButton Nr1 ;
public void machwas(View v){
Nr1.setImageResource(R.drawable.x);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Nr1 = (ImageButton)findViewById(R.id.ImageButton1);
machwas(0);
}
}
i'm still porting a J2ME app to Android and now my problem is with the GUI.
For what i've seen, Android's Activities are great, but my J2ME is filled with the classic:
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
Display display = getDisplay();
if (alert == null)
display.setCurrent(nextDisplayable);
else
display.setCurrent(alert, nextDisplayable);
}
I just can't make every Displayable to an Activity, so i thought about replacing them with View. I tried that but it just doesn't works, the app doesn't changes the screen.
Update:
Thanks for answering, but placed al vews inside FrameLayout and still nothing. This is the core of my test code, so you can check it out:
public class TestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView t = (TextView)findViewById(R.id.text); // Shows "Hi"
showDialog(); // it just shows a dialog asking if the user wants to change screen
}
showDialog() {
// in OnClick()... i do the following, and here is where it fails, i tried so far:
TestView testv= new MarcoLoco(MFActivity.this);
setContentView(testv);
testv.invalidate();
testv.requestFocus();
testv.showMeSomething();
}
public class TestView extends View{
private Context context;
TextView tv;
public TestView(Context context) {
super(context);
this.context=context;
}
public void showMeSomething() {
tv = (TextView)findViewById(R.id.tessto); // it should show "Bye"
}
}
After the OnClick the "Hi" dissapears from the screen but nothing appears, no "Bye".
Why, oh, why!?
I don't have any expirience with Java ME, but this might help you
Put your Views inside a FrameLayout, then you can use
mViewA.setVisibility(View.VISIBLE);
mViewB.setVisibility(View.GONE);
mViewA.requestFocus();
to switch between diffrent views
EDIT:
Here is a short example program that toggles between 2 textviews:
public class test extends Activity {
boolean showTV1 = true;
OnClickListener ocl = new OnClickListener() {
#Override
public void onClick(View v) {
showTV1= !showTV1;
if (showTV1){
tv1.setVisibility(View.VISIBLE);
tv2.setVisibility(View.GONE);
tv1.requestFocus();
} else {
tv2.setVisibility(View.VISIBLE);
tv1.setVisibility(View.GONE);
tv2.requestFocus();
}
}
};
private TextView tv1, tv2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.TextView01);
tv2 = (TextView) findViewById(R.id.TextView02);
tv1.setOnClickListener(ocl);
tv2.setOnClickListener(ocl);
}
}
and main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frameLayout01" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:id="#+id/TextView01" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#0f0"
android:text="Hi" />
<TextView android:id="#+id/TextView02" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#f00"
android:text="Bye" android:visibility="gone"/>
</FrameLayout>
I am not sure I fully understand your questions, but try looking at ViewAnimator and ViewFlipper - perhaps these can help
PS. just out of curiosity... have you tried any of automatic converters?
Why are you porting from J2ME to Android on your own, instead of using a conversion tool ?
Quicker, no need to learn and excel with Android, no need to debug and maintain 2 code bases... Give it a try at www.UpOnTek.com. Thanks.