Width of ImageView still 0 in onResume? - android

I have a TextView and ImageView which should stretch over the available width:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="TextView" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#drawable/ic_launcher" />
</LinearLayout>
I am trying to get the width of the imgageview to fill it with the optimal sized image. But it is 0, also in onResume.
The activity and fragment:
package com.example.getmap;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
TextView text = (TextView) rootView.findViewById(R.id.textView1);
text.setText("This is just some text\nin two lines");
ImageView map = (ImageView) rootView.findViewById(R.id.imageView1);
int mMeasuredWidth = map.getMeasuredWidth();
int mWidth = map.getWidth();
Toast.makeText(getActivity(), "width: " + mWidth + "\nmMeasuredWidth: " + mMeasuredWidth , Toast.LENGTH_SHORT).show();
return rootView;
}
}
}
I tried to use OnGlobalLayoutListener, but that does not work, because I have several instances of this fragment.
Any advice?
Solution:
Finally I got it resolved with:
text.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

Related

Newbie app error displaying sensor info

Still a newbie and cannot solve my problem. Here is a simple app displaying the light sensor value. But when trying to run the app I am getting a error.
Main Activity:
package za.co.litedata.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.widget.TextView;
import android.content.Context;
import android.os.Build;
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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
SensorManager mySensorManager;
Sensor myLightSensor;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView Text1 = (TextView)rootView.findViewById(R.id.lightsensor);
mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
myLightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (myLightSensor == null){
Text1.setText("No Light Sensor!");
}else{
//Text1.setText(myLightSensor.getName());
Text1.setText("Have Sensor");
}
return rootView;
}
}
}
Here is the Fragment:
<LinearLayout 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$PlaceholderFragment">
<TextView
android:id="#+id/lightsensor"
android:layout_width="fill_parent"
android:layout_height="49dp"
/>
</LinearLayout>
ok, it seems I found the problem) cut and paste TextView's init text in fragment's OnCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView Text1 = (TextView)rootView.findViewById(R.id.lightsensor);
mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
myLightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (myLightSensor == null){
Text1.setText("No Light Sensor!");
}else{
//Text1.setText(myLightSensor.getName());
Text1.setText("Have Sensor");
}
return rootView;
}

Problems with the event treatment of a Button

Something very weird is happening in my program. I try to use the button with the first program below (using an emulator) and the program did not even open. So I changed to the second version, using the android:OnClick, and it did not work either (the program opened, but in the click it crashed). Then I tried the third program, using android:onCLick and the instanciation of the EditText in the treatment function, and the program worked.
Can someone explain to me why the first two programs did not worked?
Edit: I noticed now that LogCat is pointing to the following error: error opening trace file: No such file oor directory (2), what is that? Can it have any relation to this error?
And if I comment the definition of the onClickListener to b1 the program do not crash anymore.
First code:
package app.projetnf33;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
status.setText("Connect");
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
return rootView;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Second code
package app.projetnf33;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void treatment_connect(View v){
status.setText("Connect");
}
public void treatment_persons(View v){
status.setText("Persons");
}
public void treatment_lecture(View v){
status.setText("Lecture");
}
public void treatment_execute(View v){
status.setText("Execute");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
return rootView;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Third code (which worked):
package app.projetnf33;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#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();
}
}
public void treatment_connect(View v){
status = (EditText) findViewById(R.id.text);
status.setText("Connect");
}
public void treatment_persons(View v){
status.setText("Persons");
}
public void treatment_lecture(View v){
status.setText("Lecture");
}
public void treatment_execute(View v){
status.setText("Execute");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
return rootView;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Fragment_layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tex_status" />
<EditText
android:id="#+id/text"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par1" />
<EditText
android:id="#+id/par1"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par2" />
<EditText
android:id="#+id/par2"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par3" />
<EditText
android:id="#+id/par3"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_usb"
android:gravity="center_vertical"
android:text="#string/connect"
android:onClick="treatment_connect" />
<Button
android:id="#+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_computer"
android:gravity="center_vertical"
android:text="#string/read"
android:onClick="treatment_lecture" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_accept"
android:gravity="center_vertical"
android:text="#string/execution"
android:onClick="treatment_execution" />
<Button
android:id="#+id/b4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_warning"
android:gravity="center_vertical"
android:text="#string/disconnect"
android:onClick="treatment_disconnect" />
</LinearLayout>
</LinearLayout>
In the first and seconds layout you tried to call
status = (EditText) findViewById(R.id.text);
b1 = (Button) findViewById(R.id.b1);
before
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
So you tried to reference a Button and EditText contained in the PlaceholderFragment layout before you created the fragment.
The views are in the fragment layout. It only becomes a part of the activity view hierarchy after the fragment transaction has been run. Your pending fragment transaction is executed in activity super.onStart() which comes only after onCreate(). In essence, you're calling findViewById() too early in the first two versions. The third version works because the findViewById() is in the click handler and gets invoked when the fragment is attached to the activity.
Usually you'd call findViewById() to set up listeners and so on at the earliest possibility in fragment onCreateView(), just after the fragment layout is inflated.

Android findViewById is returning Null in Eclipse generated project

I created a new Android project in Eclipse with one Blank Activity. In the fragment, I added a TextView called textHello. All I want to do for this test is to modify textHello's text value. But I'm my findViewById is giving me null.
Here is the fragment code:
<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.gcuitest.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textHello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Here is the MainActivity.java
package com.example.gcuitest;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
private TextView helloText;
#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();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, new PlaceholderFragment());
fragmentTransaction.commit();
}
helloText = (TextView) findViewById(R.id.textHello);
helloText.setText("Gerard");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
return rootView;
}
}
}
Why is findViewById giving me null? Is it in the right place? I've looked at other code samples, and they place findViewById in onCreate, after setContentView, which is what this does. What did I miss? Thanks.
Why is findViewById giving me null?
Because textHello TextView is inside PlaceholderFragment layout instead of Activity which is activity_main.
if you want to access TextView from Fragment layout then use onCreateView as :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
helloText = (TextView)view. findViewById(R.id.textHello);
helloText.setText("Gerard");
return view;
}

Android app stop when is being to run

I'm new to android and java. this is my first app. an example of a book. I did all steps according the book. the app is going to increase the number by click on + button
this is my Java file :
package com.example.myprayercounter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
int counter;
TextView tView;
Button btn;
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
tView.setText(" " + counter);
}
});
return rootView;
}
}
}
xml file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fbfbdd"
android:gravity="center_horizontal"
android:orientation="vertical"
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.myprayercounter.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/txt_textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="تعداد ذکرهای من"
android:textColor="#763f05"
android:textSize="20dp" />
<TextView
android:id="#+id/txt_textTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#763f05"
android:textSize="40dp" />
<Button
android:id="#+id/btn_buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#763f05"
android:text="+"
android:textColor="#fbfbdd"
android:textSize="40dp" />
</LinearLayout>
I got this error at first run of the app :
What is my mistakes? and how i can fix them?
Thanks in advance
change:
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
to ( getActivity() --> rootView)
tView = (TextView)rootView.findViewById(R.id.txt_textTwo);
btn = (Button)rootView.findViewById(R.id.btn_buttonOne);
in PlaceholderFragment, your View is rootView and you need find your view from that

get null pointer error when trying to getText

I am new to Android, so please forgive my ignorance. I have tried searching the forums, but haven't been able to find anything to get this to work. I am trying to use .getText().toString() (see below), but get a java.lang.NullPointerException error. I changed my setContentView so that it would look at the fragment_main.xml, but still returns a null for my different components. The goal of this is very simple, just to change the text on the TextView, since I am just getting started. Any help would be appreciated.
package com.example.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Button changeTxt = (Button) findViewById(R.id.btnChangeText);
final TextView textView = (TextView) findViewById(R.id.txtMessage);
changeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = textView.getText().toString();
if (text.contains("World")) {
textView.setText("Hello Android!");
}
else {
textView.setText(("Hello World!"));
}
}
});
}
public void onStart(){
super.onStart();
}
public void onResume(){
super.onResume();
}
public void onPause(){
super.onPause();
}
public void onStop(){
super.onStop();
}
public void onDestroy(){
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
return rootView;
}
}
}
Here is the xml:
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/txtMessage"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/btnChangeText"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Fllo, updated code:
XML fragment_main.xml
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/txtMessage1"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/btnChangeText1"
android:layout_gravity="center" />
</FrameLayout>
</LinearLayout>
main activity
package com.example.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void onStart(){
super.onStart();
}
public void onResume(){
super.onResume();
}
public void onPause(){
super.onPause();
}
public void onStop(){
super.onStop();
}
public void onDestroy(){
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 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);
Button changeTxt = (Button) findViewById(R.id.btnChangeText);
final TextView textView = (TextView) findViewById(R.id.txtMessage);
changeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String text = textView.getText().toString();
if (text.contains("World"))
{
textView.setText("Hello Android!");
}
else
{
textView.setText(("Hello World!"));
}
}
});
return rootView;
}
}
}
The NullPointerException occurs because, it seems that you have the same layout for your Activity and your Fragment:
// Activity
setContentView(R.layout.fragment_main);
// Fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
You need to check if your views (TextView & Button) are in the right layout and not into aonther (I guess activity_main).
Two solutions:
Copy/past your views inside fragment_main to activity_main and change setContentView(R.layout.activity_main).
Or let your views inside fragment_main and use the following code to find your view inside your Fragment, as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button changeTxt = (Button) rootView.findViewById(R.id.btnChangeText);
final TextView textView = (TextView) rootView.findViewById(R.id.txtMessage);
changeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = textView.getText().toString();
if (text.contains("World")) {
textView.setText("Hello Android!");
}
else {
textView.setText(("Hello World!"));
}
}
});
return rootView;
}
Hope this helps.
UPDATE:
1 . Remove your FrameLayout inside fragment_main. Create a new layout named activity_main and add the FrameLayout into it (with an id) as:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container" />
2 . Set this layout in onCreate method into your Activity like:
// onCreate method Activity
setContentView(R.layout.activity_main);
3 . Then, remove static in your Fragment declaration, this should be:
public class PlaceholderFragment ... { }
4 . Finally, when you try to find ids elements inside onCreateView method, you ALWAYS MUST to use the inflated view as:
rootView.findViewById(R.id.some_id_example);
Voila! This should work now.

Categories

Resources