setText works differently within different API versions - android

I downloaded latest android SDK which uses api level 19.
When I use setText there is no problem in earlier version of SDK but in the latest version I wrote the same code but when I install the app on my phone it forces to exit. This error occurs when I use setText(). However I use the same code earlier version of SDK but there is no error. I couldn't find the issue. Please help.
Here is my code
Activity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText("Düğme");
}
fragment_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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.yeni.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="104dp"
android:layout_marginTop="62dp"
android:text="TextView" />

Your textView1 is in the fragment layout and not in the activity layout. Activity onCreate() is too early to access it with findViewById() on the activity view hierarchy.
Move the findViewById() and setText() to the PlaceholderFragment onCreateView() and call findViewById() on the inflated rootView there, e.g.
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textView1);
txt.setText("Düğme");

Try this:
Check your logcat: fix the error and then you should do this:
Remove the Import R from your activity which can be found at the top of your activity file, and clean + rebuild your solution.

Related

GLSurfaceView with TextView - null pointer exception on SetText

I've looked over several SO questions and a couple tutorials.
I have tracked the problem, I think, to the context. The solution appears to possibly be editing my xml file, but nothing I find regarding this helps to remedy my problem.
In my main activity with onCreate I try to acquire a reference of my only text view object. This returns a null reference. How do I obtain a valid reference to the textview which I manually placed? I don't know if I have even added this text view correctly; should I have added it via code or something?
Here are both my onCreate and XML.
protected void onCreate(Bundle savedInstanceState) {
Log.i("[DEBUG]", "main activity - started");
super.onCreate(savedInstanceState);
s_textView = (TextView)findViewById(R.id.textView);
m_GLView = new MyGLSurfaceView(this);
setContentView(m_GLView);
s_textView = (TextView)findViewById(R.id.textView);
Log.i("[DEBUG]", "main activity - finished");
}
I have also tried the following line s_textView = (TextView)m_GLView.findViewById(R.id.textView);
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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<merge>
<com.example.a2_1039652.a2_cooper.MyGLSurfaceView />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="20dp" />
</merge>
</RelativeLayout>
I only have added this <com.example.a2_1039652.a2_cooper.MyGLSurfaceView /> line because it was the solution for a similar problem. It hasn't appeared to change anything about my application.
try this
protected void onCreate(Bundle savedInstanceState) {
Log.i("[DEBUG]", "main activity - started");
super.onCreate(savedInstanceState);
m_GLView = new MyGLSurfaceView(this);
setContentView(m_GLView);
RelativeLayout layout = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.activity_main,null);
s_textView = (TextView) layout.findViewById(R.id.textView);
Log.i("[DEBUG]", "main activity - finished");
}
So after a few hours of rest I was able to come up with the correct string of words to find a SO question with a solution. The solution was found in the question itself found here: Drawing Android UI on top of GLSurfaceView
I am unclear of whether there is an answer to my question. However for an end result I needed a text view, and now I have one which I can set text on. This is how I did it.
I removed the text view I manually placed. Here is the subsequent activity_main.xml file:
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
</RelativeLayout>
It is unclear to me how much of that configuration data is needed. Though I removed as much as I could find to be removable.
Next I, for the most part, just took the code line for line from that other SO question. This is what I have for my onCreate method.
protected void onCreate(Bundle savedInstanceState) {
Log.i("[DEBUG]", "main activity - started");
super.onCreate(savedInstanceState);
m_GLView = new MyGLSurfaceView(this);
rl = new RelativeLayout(this);
rl.addView(m_GLView);
tv = new TextView(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.CENTER_VERTICAL);
tv.setLayoutParams(lp);
tv.setBackgroundColor(0xFFFFFFFF);
rl.addView(tv);
s_textView = tv;
setContentView(rl);
Log.i("[DEBUG]", "main activity - finished");
}
For now I will mark this as the solution. If someone comes along and provides an answer for how to properly obtain a reference - for a manually added TextView when the app is using a GLSurfaceView - then I will mark it as the answer, so long as it works.

Android application: "The Application has stopped unexpectedly" - using setText() method [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have a problem with my Android application. If I use setText() method for a textView I have problem like: The Application has stopped unexpectedly. Please try again.
Code of the application:
public class TC1 extends ActionBarActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tc1);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
textView = (TextView)findViewById(R.id.textView);
textView.setText("Hi"); // wrong line
}
...
}
XML fragment:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.tc.TC1$PlaceholderFragment" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="35dp"
android:layout_marginTop="20dp"
android:text="Text" />
</RelativeLayout>
Your TextView is part of the Fragment xml but you try to get it from the Activity layout. Move the findViewById() call to the onCreateView() method of your Fragment.
For future questions:
Please do not quote "The Application has stopped unexpectedly" instead check the LogCat output for error messages and stack traces. The error message you quoted is the default crashed information for the user, nothing that provides any detailed informations for us developers.
add this to your code
View view = inflater.inflate(R.layout.fragment_blank, R.id.container,false);
and change
textView = (TextView)findViewById(R.id.textView);
to this
textView = (TextView)view.findViewById(R.id.textView);
Your code is currently trying to access your main activities view which does not contain your textview. Another option is to access it through your fragment in a similar fashion.
It seems that textview is part of fragment not activity_tc1.
So either use textview in activity_tc1 layout. or use textview in onCreateView method of fragment. where fragment_tc1 will be your fragment name.
For example
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tc1, container,
false);
TextView textView = (TextView) rootView.findViewById(R.id.textView);
textView.setText("Hi");
return rootView;
}

onCreate Null Pointer Exception [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I don't understand why this code does not running:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matchpage);
SeekBar sb1 = (SeekBar) findViewById(R.id.seek1);
sb1.setEnabled(false);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
sb1 will be null.
Why?
I will try to answer one thing from my experience that the error is coming in SeekBar sb1 = (SeekBar) findViewById(R.id.seek1); but what i have noticed android compiles code from bottom so it might happen that the reason is above or somewhere else so what i will suggest replace the code in this manner :-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matchpage);
}
then if it executes then just add SeekBar sb1 = (SeekBar) findViewById(R.id.seek1); below setContentview
its bit big but since you didnt provided the xml and we cant figure out if its package issue or something else so i tried to go really primitive and fundamental...
hope it helps.
You likely are using a Fragment. You should have in your code a class called PlaceHolderFragment, that has an onCreateView method.
In that project you have two xml layout, one named activity_matchpage and other for the fragment, fragment_main. You need to modify the latter and keep the first like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="youor.packaque.MainActivity"
tools:ignore="MergeRootFrame" />
And in fragment_main, you declare your Views.
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.tformacion.finale.MainActivity$PlaceholderFragment" >
<!-- Your Views here -->
</RelativeLayout>
Then, in your Java code, in PlaceHolderFragment, inside of onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
seekBar = (seekBar) rootView.findViewById(R.id.yourSeekBarId);
}
If you want to get rid of the fragment you simply create your XML in activity_matchpage and do not add the fragment, so, remove this:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}

Set fragment contents before or after adding?

I'm basically trying to create this quiz system, where I have a template of questions, and I dynamically change the content of the questions:
For example:
Who directed movie X?
- Incorrect answer director
- Correct answer director
- Incorrect answer director
- Incorrect answer director
I will replace X with some movie that I select from my database.
Following the question will have 4 selectable options (also generated based on question), and the user can only click one of them. The question and answers are all inside a fragment .xml file. I'm trying to change the contents of the fragment before displaying it. I've read the android documents, but this section doesn't seem to have been written in enough detail.
public class QuizTemplate extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_template);
if (savedInstanceState == null) {
PlaceholderFragment firstFragment = new PlaceholderFragment();
// Trying to set question before I commit transaction
// firstFragment.setQuestion("IT WORKS!");
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.add(R.id.container2, firstFragment).commit();
// Tried to execute pending transactions, then find view
manager.executePendingTransactions();
PlaceholderFragment firstFragment = (PlaceholderFragment) manager.findFragmentById(R.id.container2);
RadioButton answer1 = (RadioButton) firstFragment.getView().findViewById(R.id.answer1);
RadioButton answer2 = (RadioButton) firstFragment.getView().findViewById(R.id.answer2);
RadioButton answer3 = (RadioButton) firstFragment.getView().findViewById(R.id.answer3);
RadioButton answer4 = (RadioButton) firstFragment.getView().findViewById(R.id.answer4);
TextView question = (TextView) firstFragment.getView().findViewById(R.id.question);
question.setText("test");
answer1.setText("test");
// ... and so on
}
}
Fragment Class
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_quiz_template,
container, false);
return rootView;
}
public void setQuestion(String text){
TextView textView = (TextView) getView().findViewById(R.id.question);
textView.setText(text);
}
}
(layout) fragment_quiz_template.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.moviequiz.QuizTemplate$PlaceholderFragment" >
<TextView
android:id="#+id/question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:text="#string/hello_world" />
<RadioButton
android:id="#+id/answer2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/answer3"
android:layout_below="#+id/answer3"
android:layout_marginTop="28dp"
android:onClick="changeQuestion"
android:text="#string/hello_world" />
<RadioButton
android:id="#+id/answer3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/answer4"
android:layout_below="#+id/answer4"
android:layout_marginTop="17dp"
android:onClick="changeQuestion"
android:text="#string/hello_world" />
<RadioButton
android:id="#+id/answer4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/answer1"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:onClick="changeQuestion"
android:text="#string/hello_world" />
<RadioButton
android:id="#+id/answer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/answer4"
android:layout_below="#+id/question"
android:layout_marginTop="40dp"
android:onClick="changeQuestion"
android:text="#string/hello_world" />
</RelativeLayout>
None of my approaches have worked, as my app crashes upon reaching the quiz (Nothing in the log?). Any ideas what could be going wrong?
EDIT: Fixed my log, it now tells me:
Unable to start activity ComponentInfo: java.lang.NullPointerException
So my guess is when I call something like
RadioButton answer1 = (RadioButton) firstFragment.getView().findViewById(R.id.answer1);
answer1 is null. But why is this the case if I execute pending transactions?
Your code that generates the UI in the fragment takes time to execute. I believe that even though you are committing the transactions, the UI is still not ready when you are trying to access it. Don't forget that your fragment lifecycle is linked to your activity lifecycle yet you are expecting to access the fragment UI in the OnCreate method of your activity.
Consider instead using the callback pattern to communicate between your activities and fragments.
http://developer.android.com/training/basics/fragments/communicating.html
Using this pattern, you can call your activity code when you are sure the UI is complete and available.

ANDROID STUDIO Can't access objects in fragment_main.xml

I have a simple Android app. The layout folder shows an activity_main.xml file and a fragment_main.xml file. In that fragment.xml file I have placed a button that I've named buttonTest.
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.snapvest.thunderbird.app.MainActivity$PlaceholderFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TEST"
android:id="#+id/buttonTest"
android:layout_gravity="center_horizontal" />
</LinearLayout>
in the MainActivity.java file I'm trying to gain access to that buttonTest.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
// Get access to the buttons
final Button buttonTest = (Button)findViewById(R.id.buttonTest);
}
It compiles just fine. But when I run it the buttonTest variable comes back as a null pointer.
Why is it not finding the buttonTest object?
I think I found the solution. MainActivity.java sets up the activity_main.xml which then uses fragment_main.xml as its (initially) single, primary fragment. That's why we are supposed to actually put all of our UI for the activity primarily in fragment_main.xml (and actually put NOTHING in activity_main.xml).
Near the bottom of MainActivity.java there is a section that initializes the fragment_main.xml. And it is THERE that I need to gain access to the buttons and other objects of the UI for the fragment. Such as:
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get access to the buttons
final Button buttonAvailableOptions = (Button)rootView.findViewById(R.id.buttonAvailableOptions);
return rootView;
}
}
Most of that, above, is automatically added by Android Studio. The part starting with "Get access to the button" is mine and is where you set up any access to or processing of the buttons and other UI objects.
The reason why findViewById() is failing to find the button is because setContentView() primes findViewById() to only look in the layout.xml file you gave to setContentView(), and your button is not located in R.layout.activity_main. If your button is located in the Fragment (which it appears to be) then you should be accessing and manipulating it from the Fragment, not the Activity. This ensures that your Activity and Fragment logic stay decoupled, allowing you to re-use the Fragment with different Activities.
You can use like this.
final Button buttonAvailableOptions = getActivity().findViewById(R.id.buttonAvailableOptions);

Categories

Resources