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.
Related
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.
I'm having trouble with this part of my application:
_btnSubmit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something...
}
});
I get the "Unfortunately [app] has stopped working" error.I can't find the problem.
Here's my 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.droidone.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/txtAppTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:text="#string/app_title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/lblInputHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lblInputWeight"
android:layout_below="#+id/lblInputWeight"
android:layout_marginTop="34dp"
android:text="#string/input_height"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/lblInputHeight"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="#string/btn_getBMI" />
<EditText
android:id="#+id/txtInputHeightFt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtInputHeightIn"
android:layout_alignBottom="#+id/txtInputHeightIn"
android:layout_toLeftOf="#+id/txtInputHeightIn"
android:ems="3"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lblInputHeight"
android:layout_alignRight="#+id/txtInputHeightIn"
android:layout_below="#+id/btnSubmit"
android:layout_marginTop="59dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/lblInputWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtAppTitle"
android:layout_marginTop="60dp"
android:layout_toLeftOf="#+id/btnSubmit"
android:text="#string/input_weight"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtInputWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/lblInputHeight"
android:layout_toLeftOf="#+id/txtInputHeightIn"
android:ems="3"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtInputHeightIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btnSubmit"
android:layout_alignParentRight="true"
android:ems="3"
android:inputType="numberDecimal" />
</RelativeLayout>
and activity:
package com.example.droidone;
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.EditText;
import android.widget.TextView;
import android.os.Build;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity {
Button _btnSubmit;
EditText _txtInputWeight;
EditText _txtInputHeightFt;
EditText _txtInputHeightIn;
TextView _txtResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
setUpOnClick();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
private void setUpView()
{
_btnSubmit = (Button)findViewById(R.id.btnSubmit);
_txtInputWeight = (EditText)findViewById(R.id.txtInputWeight);
_txtInputHeightFt = (EditText)findViewById(R.id.txtInputHeightFt);
_txtInputHeightIn = (EditText)findViewById(R.id.txtInputHeightIn);
_txtResult = (TextView)findViewById(R.id.txtResult);
}
private void setUpOnClick() {
_btnSubmit = (Button)findViewById(R.id.btnSubmit);
_btnSubmit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something...
}
});
}
#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;
}
}
}
I bet the layout xml is related to the Fragment and not the Activity, try to move both setUpView() and setUpOnClick() into the PlaceholderFragment, like this:
public static class PlaceholderFragment extends Fragment {
Button _btnSubmit;
EditText _txtInputWeight;
EditText _txtInputHeightFt;
EditText _txtInputHeightIn;
TextView _txtResult;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setUpView(rootView);
setUpOnClick(rootView);
return rootView;
}
private void setUpView(View rootView)
{
_btnSubmit = (Button)rootView.findViewById(R.id.btnSubmit);
_txtInputWeight = (EditText)rootView.findViewById(R.id.txtInputWeight);
_txtInputHeightFt = (EditText)rootView.findViewById(R.id.txtInputHeightFt);
_txtInputHeightIn = (EditText)rootView.findViewById(R.id.txtInputHeightIn);
_txtResult = (TextView)rootView.findViewById(R.id.txtResult);
}
private void setUpOnClick(View rootView) {
_btnSubmit = (Button)rootView.findViewById(R.id.btnSubmit);
_btnSubmit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something...
}
});
}
}
And just as a piece of advice, try looking into ButterKnife, makes life much easier dealing with injecting views and handling button clicks.
Edit:
Seeing the other answer, I failed to spot that the xml actually is related to the activity. I do think that it is preferred to have all the layout contained in fragments nowadays though. In your case, not doing so leaves the PlaceholderFragment of no use and could might as well be removed entirely.
OK you have the elements in your activity_main.xml layout
but when you do a transaction to PlaceholderFragment() it loads fragment_main.xml and the reference of that elements doesn´t exist!
change your PlaceholderFragment class to:
public static class PlaceholderFragment extends Fragment {
Button _btnSubmit;
EditText _txtInputWeight;
EditText _txtInputHeightFt;
EditText _txtInputHeightIn;
TextView _txtResult;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setUpView(rootView);
setUpOnClick(rootView);
return rootView;
}
private void setUpView(View rootView){
_btnSubmit = (Button)rootView.findViewById(R.id.btnSubmit);
_txtInputWeight = (EditText)rootView.findViewById(R.id.txtInputWeight);
_txtInputHeightFt = (EditText)rootView.findViewById(R.id.txtInputHeightFt);
_txtInputHeightIn = (EditText)rootView.findViewById(R.id.txtInputHeightIn);
_txtResult = (TextView)rootView.findViewById(R.id.txtResult);
}
private void setUpOnClick(View rootView) {
_btnSubmit = (Button)rootView.findViewById(R.id.btnSubmit);
_btnSubmit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something :)
}
});
}
}
The problem is that you are trying to add a fragment to R.id.container in the onCreate() method. Your layout does not have this element in it. Remove that code and it should do the trick.
This question already has answers here:
setOnClickListener crashs my android app
(3 answers)
Closed 8 years ago.
I don't know why but I can't seem to figure out what is wrong with my code. As soon as I add an onclickListener the app crashes. I really need help. Also I looked at other threads but I can't seem to find out what I'm doing wrong. Thanks
The code is below:
package com.example.medrec;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
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.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements OnClickListener{
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
login = (Button)findViewById(R.id.w_login);
//Crashes when I add this line.
login.setOnClickListener(this);
}
#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
}
}
My activity_main.xml
<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="com.example.medrec.MainActivity"
tools:ignore="MergeRootFrame" />
My 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.medrec.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/w_number_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="118dp"
android:text="#string/w_number" />
<Button
android:id="#+id/w_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/w_number_edit_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="#string/w_login_text" />
try below code:-
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);
login = (Button)rootView.findViewById(R.id.w_login);
//Crashes when I add this line.
login.setOnClickListener(this);
return rootView;
}
}
I'm assumging it's crashing because your login is null, the reason it's null because w_login doesn't exist in your activity layout. Try this (rootView from your fragment),
login = (Button) rootView.findViewById(R.id.w_login);
login.setOnClickListener(this);
Your app crashed it's because your button w_login belong to your fragment_main.xml and you have to set activity_main.xml layout to your Activity.
At code
login = (Button) rootView.findViewById(R.id.w_login);
login.setOnClickListener(this);
You should reference this Button in your Fragment onCreateView(......)
assign on click listener in onCreateView
login = (Button) rootView.findViewById(R.id.w_login);
//Crashes when I add this line.
login.setOnClickListener(this);
Your app crashes showing NullPointerException while searching the Button in your activity_main.xml but it doesn't find there. Rather you should add the button code in your PlaceholderFragment fragment.
Delete the following line from your MainActivity
login = (Button)findViewById(R.id.w_login);
//Crashes when I add this line.
login.setOnClickListener(this);
Add the following to your PlaceholderFragment
public static class PlaceholderFragment extends Fragment implements OnClickListener{
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button login = (Button)rootView.findViewById(R.id.w_login);
login.setOnClickListener(this);
return rootView;
}
}
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
I am using Android studio for android development.I am creating onclick button activity.I am getting no errors but when I click the button on the app it shows "Unfortunately the app has stopped."
Below is my code for fragment_main.xml and MainActivity.java.
Please guide.
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: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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/texthaiku"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/editText"
android:onClick="OnLoveButtonClicked"/>
<TextView
android:text="#string/haiku"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:visibility="invisible"
android:layout_alignParentLeft="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
MainActivity.java
package com.AndroidLove;
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.TextView;
import android.widget.Button;
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();
}
}
public void onLoveButtonClicked(View view) {
TextView textView =(TextView) findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
}
#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.
switch (item.getItemId()) {
case 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;
}
}
}
Try this..
It'll give NPE because textView is inside fragment_main.xml then your initilize that textview inside click function that's wrong . use that textView in global
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
textView =(TextView) rootView.findViewById(R.id.textView);
return rootView;
}
and
public void onLoveButtonClicked(View view) {
textView.setVisibility(View.VISIBLE);
}
where did you create container, in xml which you have shown i don't see any container layout.
without R.id.container
you have not initialized your TextView on onCreateView()
so add this line on onCreateView()
textView =(TextView) rootView.findViewById(R.id.textView);
EDIT
initialize your button also.
btn = (Button) rootView.findViewById(R.id.button);