I want to have a SearchView on the ActionBar. But if I add a OnQueryTextListener a NullPointerException appears. Furthermore I'm unable to show the searchView in the Bar.
MainActivity.java
public class MainActivity extends ActionBarActivity implements OnQueryTextListener {
#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.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#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 boolean onQueryTextChange(String arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
}
menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="de.group42.todo.MainActivity" >
<item
android:id="#+id/action_search"
android:title="Search"
android:icon="#drawable/abc_ic_search"
android:showAsAction="always"
android:actionViewClass="android.support.v7.widget.SearchView"
/>
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"/>
</menu>
I have no clue what I did wrong. May someone help me?
EDIT: LogCat says
06-11 23:13:10.755: E/AndroidRuntime(17723): FATAL EXCEPTION: main
06-11 23:13:10.755: E/AndroidRuntime(17723): java.lang.NullPointerException
06-11 23:13:10.755: E/AndroidRuntime(17723): at de.group42.todo.MainActivity.onCreateOptionsMenu(MainActivity.java:42)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.app.Activity.onCreatePanelMenu(Activity.java:2578)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.support.v7.app.ActionBarActivityDelegateICS.onCreatePanelMenu(ActionBarActivityDelegateICS.java:146)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.support.v7.app.ActionBarActivity.onCreatePanelMenu(ActionBarActivity.java:199)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onCreatePanelMenu(ActionBarActivityDelegateICS.java:293)
06-11 23:13:10.755: E/AndroidRuntime(17723): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:507)
06-11 23:13:10.755: E/AndroidRuntime(17723): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:934)
06-11 23:13:10.755: E/AndroidRuntime(17723): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:292)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.view.Choreographer.doCallbacks(Choreographer.java:591)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.view.Choreographer.doFrame(Choreographer.java:560)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.os.Handler.handleCallback(Handler.java:730)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.os.Looper.loop(Looper.java:176)
06-11 23:13:10.755: E/AndroidRuntime(17723): at android.app.ActivityThread.main(ActivityThread.java:5419)
06-11 23:13:10.755: E/AndroidRuntime(17723): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 23:13:10.755: E/AndroidRuntime(17723): at java.lang.reflect.Method.invoke(Method.java:525)
06-11 23:13:10.755: E/AndroidRuntime(17723): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
06-11 23:13:10.755: E/AndroidRuntime(17723): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
06-11 23:13:10.755: E/AndroidRuntime(17723): at dalvik.system.NativeStart.main(Native Method)
Line 42 is adding the listener. Hope you may help me.
Thanks :)
It seem your searchView gets assigned a null
I found this question that might help you:
MenuItemCompat.getActionView always returns null
Try with changing namespace from android:actionViewClass to app:actionViewClass
Related
Error occurs when I place a function inside onCreateView in menu1_Fragment.java. Sorry in advance as I will be placing my logs in as well so it might make my post a bit big so I will tell you the layout. I am new sorry for the loads of questions.
The code works perfectly if I just don't put the function setClick() inside my fragment. quick note the function basically makes my image in menu1_layout.xml a 3 way button aka start stop reset where when you reset, it pops up a toast of exact time you got
1) menu1_Fragment.java
public class menu1_Fragment extends Fragment {
Chronometer mChronometer;
int loop = 0;
double startTime;
double millis;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
setClick();
return rootview;
}
Button button;
public void setClick() {
mChronometer = (Chronometer) getActivity().findViewById(R.id.aChronometer);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
}
View.OnClickListener mStartListener = new View.OnClickListener() {
public void onClick(View v) {
if (loop == 0) {
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
startTime = System.currentTimeMillis();
loop++;
} else if (loop == 1) {
mChronometer.stop();
millis = System.currentTimeMillis()-startTime;
loop++;
} else if (loop == 2) {
mChronometer.setBase(SystemClock.elapsedRealtime());
Context context = getActivity().getApplicationContext();
CharSequence text = "Your Time is: " + (millis/1000);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
loop = 0;
}
}
};
}
2) LOGS
10-28 16:52:26.552 2912-2912/app.z0nen.menu D/AndroidRuntime: Shutting down VM
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: FATAL EXCEPTION: main
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Process: app.z0nen.menu, PID: 2912
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{app.z0nen.menu/app.z0nen.slidemenu.MyActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.setClick(menu1_Fragment.java:39)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.onCreateView(menu1_Fragment.java:26)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Fragment.performCreateView(Fragment.java:2220)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.BackStackRecord.run(BackStackRecord.java:793)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentController.execPendingActions(FragmentController.java:325)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Activity.performStart(Activity.java:6252)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 16:52:28.662 2912-2912/? I/Process: Sending signal. PID: 2912 SIG: 9
3) MyActivity.Java
public class MyActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new menu1_Fragment();
break;
case 1:
objFragment = new menu2_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.my, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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 {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
4) Menu1_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<Chronometer
android:id="#+id/aChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:textColor="#111111"
android:layout_marginTop="27dp"
android:layout_below="#+id/stopWatch"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/stopWatch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/stopwatch2"
android:layout_marginTop="38dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
You can't use getActivity() from onCreateView() as the fragment's activity has not been created yet. You should use not use getActivity() until onActivityCreated() is called, or better yet, use the rootview you inflated to do your findViewByID() calls.
Also, you are initializing your button three times. You should get rid on two of them :)
Change
button = (Button) getActivity().findViewById(R.id.stopWatch);
to this:
button = (Button) findViewById(R.id.stopWatch);
Your button is inside your fragment's layout, not the activity's.
EDIT:
Make your button a member variable, so that you could access it from the onCreateView & setClick methods:
private Button mButton;
And we need to save a reference of your button in the onCreateView method to this: (rootview is your fragment's inflated layout)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
mButton = rootview.findViewById(R.id.stopWatch);
setClick();
return rootview;
}
and in the setClick method put this instead :
mButton.setOnClickListener(mStartListener);
I have popupMenu and CheckBox. I need make write status CheckBox to boolean.
This code not working:
MenuItem fast_result;
boolean fast=false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.FastResult:
fast_result = item.getSubMenu().getItem(R.id.FastResult);//This is 182 line
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
}
}
It is errors:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.alexvsalex.HelpforMath.RootsActivity.onOptionsItemSelected(RootsActivity.java:182)
at android.app.Activity.onMenuItemSelected(Activity.java:2502)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:950)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:163)
at android.widget.AdapterView.performItemClick(AdapterView.java:292)
at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
at android.widget.AbsListView$1.run(AbsListView.java:3168)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
What to do?
The problem is solved:
case R.id.FastResult:
fast_result = item; //There was an error
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
im making a simple calories calculator and it gives me that error, i already reviewed the code and searched here for the solution but im not able to see why is not running.
I thought it was because i had not initialized the variable, so i did it and still got the same error, maybe is something with the spinners, im new on using spinners
here is the code:
public class CaloriesCalculator extends ActionBarActivity {
EditText etAge, etWeight, etHeight;
Button btnCalculate;
TextView tvResult;
Spinner spinnerGender, spinnerActivity;
String itemGender, itemActivity;
int Height=0;
int Weight=0;
int Age=0;;
double bmr=0.0;
double tdee=0.0;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.caloriescalculator);
spinnerGender=(Spinner)findViewById(R.id.spinnerGender);
spinnerActivity=(Spinner)findViewById(R.id.spinnerActivity);
etAge=(EditText)findViewById(R.id.etAge);
etWeight=(EditText)findViewById(R.id.etWeight);
etHeight=(EditText)findViewById(R.id.etHeight);
tvResult=(TextView)findViewById(R.id.tvResult);
List<String> list = new ArrayList<String>();
list.add("Male");
list.add("Female");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
List<String> list2 = new ArrayList<String>();
list.add("Sedentary");
list.add("Lightly Active");
list.add("Moderalety Active");
list.add("Very Active");
list.add("Extremely Active");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list2 );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerActivity.setAdapter(dataAdapter2);
btnCalculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
spinnerGender.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
spinnerActivity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
itemGender=String.valueOf(spinnerGender.getSelectedItem());
itemActivity=String.valueOf(spinnerActivity.getSelectedItem());
if(itemGender=="Male"){
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.9;
}
}
else if(itemGender=="Female") {
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.9;
}
}
result=Double.toString(tdee);
tvResult.setText(result);
}
});
}
#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);
}
}
logcat:
11-28 17:20:05.501: E/AndroidRuntime(1455): FATAL EXCEPTION: main
11-28 17:20:05.501: E/AndroidRuntime(1455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Looper.loop(Looper.java:137)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:20:05.501: E/AndroidRuntime(1455): at dalvik.system.NativeStart.main(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): Caused by: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:67)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:20:05.501: E/AndroidRuntime(1455): ... 11 more
11-28 17:24:42.341: D/AndroidRuntime(1507): Shutting down VM
11-28 17:24:42.341: W/dalvikvm(1507): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-28 17:24:42.371: E/AndroidRuntime(1507): FATAL EXCEPTION: main
11-28 17:24:42.371: E/AndroidRuntime(1507): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Looper.loop(Looper.java:137)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:24:42.371: E/AndroidRuntime(1507): at dalvik.system.NativeStart.main(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): Caused by: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:70)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:24:42.371: E/AndroidRuntime(1507): ... 11 more
Yout btnCalculate is null, you should initialize before doing the onclickListener:
btnCalculate = (Button)findViewById(R.id.btnCalculate); //your id
Also note that you are initializing the dataAdapter2 but actually you are using dataAdapert, and list2 dont have any elements, because you declare it but u are filling always list1
I have a very very simple project in which what I am trying to achieve is to that when a user click on the button it display the text. But in the ADB it says unfortunately showtext stop working. What is the reason behind this?
I had tried but not got any result. My code is fine but not working. Below is java code for it. I omitted xml code as it contain only the button and a text view not so complex.
public class MainActivity extends Activity {
Button ShowText;
TextView DisplayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShowText=(Button)findViewById(R.id.bShowText);
}
void ShowMeText(View view){
DisplayText=(TextView)findViewById(R.id.tvShowText);
DisplayText.setVisibility(View.VISIBLE);
}
}
Try solve my this little issue. Thanks in Advance.
As someone asked for logcat error here is it -
06-11 06:51:32.376: E/AndroidRuntime(1223): FATAL EXCEPTION: main
06-11 06:51:32.376: E/AndroidRuntime(1223): java.lang.IllegalStateException: Could not find a method ShowMeText(View) in the activity class com.mylearning.showtext.MainActivity for onClick handler on view class android.widget.Button with id 'bShowText'
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.view.View$1.onClick(View.java:3620)
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.view.View.performClick(View.java:4240)
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.view.View$PerformClick.run(View.java:17721)
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.os.Handler.handleCallback(Handler.java:730)
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.os.Looper.loop(Looper.java:137)
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.app.ActivityThread.main(ActivityThread.java:5103)
06-11 06:51:32.376: E/AndroidRuntime(1223): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 06:51:32.376: E/AndroidRuntime(1223): at java.lang.reflect.Method.invoke(Method.java:525)
06-11 06:51:32.376: E/AndroidRuntime(1223): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
06-11 06:51:32.376: E/AndroidRuntime(1223): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-11 06:51:32.376: E/AndroidRuntime(1223): at dalvik.system.NativeStart.main(Native Method)
06-11 06:51:32.376: E/AndroidRuntime(1223): Caused by: java.lang.NoSuchMethodException: ShowMeText [class android.view.View]
06-11 06:51:32.376: E/AndroidRuntime(1223): at java.lang.Class.getConstructorOrMethod(Class.java:423)
06-11 06:51:32.376: E/AndroidRuntime(1223): at java.lang.Class.getMethod(Class.java:787)
06-11 06:51:32.376: E/AndroidRuntime(1223): at android.view.View$1.onClick(View.java:3613)
06-11 06:51:32.376: E/AndroidRuntime(1223): ... 11 more
You need to add android:onClick="ShowMeText" in your Button in your Layout. like so
<Button .............
android:onClick="ShowMeText"
......... />
and used lower case for method creation as Java naming Convention . like so showmetext
and also defined your ShowMeText(...) method as Public
ShowMeText(View v) has to be public.
Btw. start function names with lower case characters as specified by Java code style.
<Button
android:id="#+id/tvShowText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="ShowMeText" />
in java code
public void ShowMeText(View v){
DisplayText=(TextView)findViewById(R.id.tvShowText);
DisplayText.setVisibility(View.VISIBLE);
}
public class MainActivity extends Activity implements OnClickListener {
Button ShowText;
TextView DisplayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShowText = (Button) findViewById(R.id.bShowText);
DisplayText = (TextView) findViewById(R.id.tvShowText);
ShowText.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == ShowText.getId())
// need to check ID because from which view has fire event soo we can handle appropriate
DisplayText.setVisibility(View.VISIBLE);
}
}
// Try this way,hope this will help you to solve your problem.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="#+id/bShowText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ShowText"
android:onClick="ShowMeText"/>
<TextView
android:id="#+id/tvShowText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:visibility="gone"
android:text="TextView With Some Text"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private TextView tvShowText;
private Button bShowText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvShowText = (TextView)findViewById(R.id.tvShowText);
bShowText = (Button)findViewById(R.id.bShowText);
}
public void ShowMeText(View v){
if(v.getId() == bShowText.getId()) {
if(tvShowText.getVisibility() == View.VISIBLE){
tvShowText.setVisibility(View.GONE);
}else{
tvShowText.setVisibility(View.VISIBLE);
}
}
}
}
Try this:
public class MainActivity extends Activity {
Button ShowText;
TextView DisplayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShowText=(Button)findViewById(R.id.bShowText);
DisplayText=(TextView)findViewById(R.id.tvShowText);
DisplayText.setVisibility(View.Gone);
ShowText.setonClickListener(this);
}
public void ShowMeText(View view){
DisplayText.setVisibility(View.VISIBLE);
DisplayText.setText("Show your Text");
}
}
When I try to send some text over to the next Activity the program crashes saying "null pointer exception unable to start activity" but without using Intent Extra the Intent works fine.
Main Activity
public class MainActivity extends Activity implements OnClickListener{
EditText et;
public final static String KEY="com.example.myprotrial";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
Button btn =(Button)findViewById(R.id.button1);
btn.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 void onClick(View arg0) {
Intent i = new Intent(MainActivity.this,MyActivity.class);
i.putExtra(KEY, et.getText().toString());
startActivity(i);
}
}
MyActivity
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Intent intent=getIntent();
String a = intent.getStringExtra(MainActivity.KEY);
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(a);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
}
LogCat
12-09 13:58:33.115: E/AndroidRuntime(1588): FATAL EXCEPTION: main
12-09 13:58:33.115: E/AndroidRuntime(1588): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myprotrial/com.example.myprotrial.MyActivity}: java.lang.NullPointerException
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.os.Handler.dispatchMessage(Handler.java:99)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.os.Looper.loop(Looper.java:137)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-09 13:58:33.115: E/AndroidRuntime(1588): at java.lang.reflect.Method.invokeNative(Native Method)
12-09 13:58:33.115: E/AndroidRuntime(1588): at java.lang.reflect.Method.invoke(Method.java:525)
12-09 13:58:33.115: E/AndroidRuntime(1588): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-09 13:58:33.115: E/AndroidRuntime(1588): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-09 13:58:33.115: E/AndroidRuntime(1588): at dalvik.system.NativeStart.main(Native Method)
12-09 13:58:33.115: E/AndroidRuntime(1588): Caused by: java.lang.NullPointerException
12-09 13:58:33.115: E/AndroidRuntime(1588): at com.example.myprotrial.MyActivity.onCreate(MyActivity.java:18)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.Activity.performCreate(Activity.java:5133)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-09 13:58:33.115: E/AndroidRuntime(1588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-09 13:58:33.115: E/AndroidRuntime(1588): ... 11 more
The problem is that your LogCat doesn't tell on which line the NPE occurs.
From your code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Intent intent=getIntent();
String a = intent.getStringExtra(MainActivity.KEY);
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(a);
}
The if the NPE is occurring on intent.getStringExtra then your intent is null. If it's on tv.setText(a) then most likely the activity_my layout doesn't have textView1 in it. Step through it in the debugger and watch the instance variables.