Holo.NoTitleBar & NullPointerException - nullpointerexception

I have android application with 3.0 and an activity with tab and swipe. I want to remove the title bar, but when write android:theme="#android:style/Theme.NoTitleBar, and run my application, the log cat says one NullPointerException check me, and when i remove this line, the application run very well.
This is my code:
public class Estructura extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the three primary sections of the app. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
CollectionPagerAdapter mCollectionPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will display the
* object collection.
*/
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_estructura);
// Create an adapter that when requested, will return a fragment
// representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must
// use
// getSupportFragmentManager.
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is
// no hierarchical
// parent.
// actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener
// for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select
// the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if
// we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mCollectionPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the primary sections of the app.
*/
public class CollectionPagerAdapter extends FragmentPagerAdapter {
final int NUM_ITEMS = 6; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.inicio);
break;
case 1:
tabLabel = getString(R.string.fotos);
break;
case 2:
tabLabel = getString(R.string.videos);
break;
case 3:
tabLabel = getString(R.string.visitas);
break;
case 4:
tabLabel = getString(R.string.cursos);
break;
case 5:
tabLabel = getString(R.string.contacto);
break;
}
return tabLabel;
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
// #Override
// public View onCreateView(LayoutInflater inflater, ViewGroup
// container,
// Bundle savedInstanceState) {
//
// Bundle args = getArguments();
// int position = args.getInt(ARG_OBJECT);
//
// int tabLayout = 0;
// switch (position) {
// case 0:
// tabLayout = R.layout.tab1;
// break;
// case 1:
// tabLayout = R.layout.tab2;
// break;
// case 2:
// tabLayout = R.layout.tab3;
// break;
// case 3:
// tabLayout = R.layout.tab4;
// break;
// case 4:
// tabLayout = R.layout.tab5;
// break;
// case 5:
// tabLayout = R.layout.tab6;
// break;
// }
//
// View rootView = inflater.inflate(tabLayout, container, false);
//
// return rootView;
// }
}
}
and the log cat:
06-14 12:31:55.960: E/AndroidRuntime(21882): FATAL EXCEPTION: main
06-14 12:31:55.960: E/AndroidRuntime(21882): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lirioandroid.museocaldemoron/com.lirioandroid.museocaldemoron.Estructura}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
06-14 12:31:55.960: E/AndroidRuntime(21882): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
06-14 12:31:55.960: E/AndroidRuntime(21882): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
06-14 12:31:55.960: E/AndroidRuntime(21882): at android.app.ActivityThread.access$600(ActivityThread.java:127)
06-14 12:31:55.960: E/AndroidRuntime(21882): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
06-14 12:31:55.960: E/AndroidRuntime(21882): at android.os.Handler.dispatchMessage(Handler.java:99)
06-14 12:31:55.960: E/AndroidRuntime(21882): at android.os.Looper.loop(Looper.java:137)
06-14 12:31:55.960: E/AndroidRuntime(21882): at android.app.ActivityThread.main(ActivityThread.java:4441)
06-14 12:31:55.960: E/AndroidRuntime(21882): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 12:31:55.960: E/AndroidRuntime(21882): at java.lang.reflect.Method.invoke(Method.java:511)
06-14 12:31:55.960: E/AndroidRuntime(21882): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-14 12:31:55.960: E/AndroidRuntime(21882): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-14 12:31:55.960: E/AndroidRuntime(21882): at dalvik.system.NativeStart.main(Native Method)
06-14 12:31:55.960: E/AndroidRuntime(21882): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
06-14 12:31:55.960: E/AndroidRuntime(21882): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229)
06-14 12:31:55.960: E/AndroidRuntime(21882): at com.lirioandroid.museocaldemoron.Estructura.onCreate(Estructura.java:35)

See your code at com.lirioandroid.museocaldemoron.Estructura.onCreate(Estructura.java:35), I assume it's anything that touches the actionBar variable here:
final ActionBar actionBar = getActionBar();
When you set noTitleBar, that actionBar doesn't exist anymore! You might want to try Blank title in action bar

Related

Android: crash from IndexOutOfBoundsException: length=36; index=-1

I have a RecyclerView list of CardViews. A click on the CardView loads a DetailsActivity for that CardView, using its position in the RecyclerView list. Recently a click on CardView crashed the app with an ArrayIndexOutOfBoundsException. I did click on the CardView quickly after returning to the Recycler list UI, so might this be some type of asynchronous error. Any thoughts on how to fix?
Code for the item click in the RecyclerView's CardsAdapter:
public List<Card> mListItems;
...
public Card getItem(int position) {
**return mListItems.get(position); // line 102**
}
ClickListener code in the CardsAdapter to handle the item click:
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.item_todo, parent,false);
final ItemHolder itemHolder = new ItemHolder(itemView);
itemHolder.cardView.setOnClickListener(view -> {
**Card adapterItem = CardsAdapter.this.getItem(itemHolder.getBindingAdapterPosition()); // line 639**
int adapPos = itemHolder.getBindingAdapterPosition();
if (adapPos == RecyclerView.NO_POSITION || recyclerItemClickListener == null) {
return;
}
recyclerItemClickListener.onItemClick(itemHolder.cardView, adapterItem, adapPos);
});
...
}
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.todo.quickcards, PID: 10677
java.lang.ArrayIndexOutOfBoundsException: length=36; index=-1
at java.util.ArrayList.get(ArrayList.java:439)
at com.todo.quickcards.adapter.CardsAdapter.getItem(CardsAdapter.java:102)
at com.todo.quickcards.adapter.CardsAdapter.lambda$onCreateViewHolder$0$com-todo-quickcards-adapter-CardsAdapter(CardsAdapter.java:639)
at com.todo.quickcards.adapter.CardsAdapter$$ExternalSyntheticLambda0.onClick(Unknown Source:4)
at android.view.View.performClick(View.java:6897)
at android.view.View$PerformClick.run(View.java:26101)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
If you are gonna call getItem(itemHolder.getBindingAdapterPosition()) then better call it after/inside the Condition check . Which checked for invalid position .
int adapPosition = itemHolder.getBindingAdapterPosition();
if (adapPos == RecyclerView.NO_POSITION || recyclerItemClickListener == null) {
return;
}
Card adapterItem = CardsAdapter.this.getItem(adapPosition);
recyclerItemClickListener.onItemClick(itemHolder.cardView, adapterItem, adapPos);

Recylerview in fragment doesnt populate with items

Sorry for this noob questons, but I am starting to learn Firebase UI and 2 days in a row I am stuck with populating a RecyclerView in a fragment.
I tried to move my code around in onViewCreated , onCreateView methods but I think that is not the problem, in log it just throws one error:
2020-02-18 15:08:26.730 4467-4467/com.social.voteup E/RecyclerView: No adapter attached; skipping layout
Double checked everything is linking with the xml file.
Here is my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
On View Created method
mRecyclerView = view.findViewById(R.id.posts_recyclerview);
mSwipeRefreshLayout = view.findViewById(R.id.refreshLayout);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
setupAdapter();
// Refresh Action on Swipe Refresh Layout
mSwipeRefreshLayout.setOnRefreshListener(() -> mAdapter.refresh());
I use the adapter inside the fragment as shown here:
private void setupAdapter() {
// Init Paging Configuration
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(2)
.setPageSize(10)
.build();
// Init Adapter Configuration
FirestorePagingOptions<Post> options = new FirestorePagingOptions.Builder<Post>()
.setLifecycleOwner(this)
.setQuery(mQuery, config, Post.class)
.build();
// Instantiate Paging Adapter
mAdapter = new FirestorePagingAdapter<Post, PostViewHolder>(options) {
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.item_post, parent, false);
return new PostViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull PostViewHolder viewHolder, int i, #NonNull Post post) {
// Bind to ViewHolder
viewHolder.bind(post);
}
#Override
protected void onError(#NonNull Exception e) {
super.onError(e);
Log.e("MainActivity", Objects.requireNonNull(e.getMessage()));
}
protected void onLoadingStateChanged(#NonNull LoadingState state) {
switch (state) {
case LOADING_INITIAL:
case LOADING_MORE:
mSwipeRefreshLayout.setRefreshing(true);
break;
case LOADED:
mSwipeRefreshLayout.setRefreshing(false);
break;
case ERROR:
mSwipeRefreshLayout.setRefreshing(false);
break;
case FINISHED:
mSwipeRefreshLayout.setRefreshing(false);
break;
}
}
};
// Finally Set the Adapter to mRecyclerView
mRecyclerView.setAdapter(mAdapter);
}
Here is the full source file on pastebin:https://pastebin.com/YkzKRuUD
Add this line of code in the On View Created method.
You have created an adapter but you haven't attached the adapter to the recyclerView
mRecyclerView = view.findViewById(R.id.posts_recyclerview);
mSwipeRefreshLayout = view.findViewById(R.id.refreshLayout);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setAdapter(new setupAdapter());
// Refresh Action on Swipe Refresh Layout
mSwipeRefreshLayout.setOnRefreshListener(() -> mAdapter.refresh());

Java.Lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference occurred

I have a view pager setup with 1 fragment initially, the fragment will populate a linear recycle view for user to perform selection
public class NoAccessPanelActivity : MasterActivity
{
#region Properties
Fragments.NoAccessListFragment _sysNoAccessFragment;
Fragments.CameraFragment _cameraFragment;
Adapters.NoAccessPanelFragmentsAdapter _adapter;
ViewPager viewPager;
TabLayout tabLayout;
private bool _isCameraFragementRemove = false;
#endregion
#region Activity Override
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.NoAccessPanel);
ComingFrom = Intent.GetStringExtra("ComingFrom");
InitPanel();
}
protected override void OnResume()
{
base.OnResume();
BindHandlers();
}
protected override void OnPause()
{
UnbindHandlers();
base.OnPause();
}
public override void OnBackPressed()
{
if (ProceedDiscardCapturedImage())
OnBack();
}
#endregion
#region Events
private void _sysNoAccessFragment_OnViewNewFragment(ButtonInListClickedButtonListArgs e)
{
ShowLoadingPanel("");
switch (e.ButtonName)
{
case "AddCamera":
if (_cameraFragment == null)
{
_cameraFragment = new Fragments.CameraFragment();
_adapter.AddFragment(_cameraFragment, "Camera");
//_adapter.AddFragmentWithoutTitle(_cameraFragment);
_adapter.NotifyDataSetChanged();
}
break;
case "ShowCamera":
var cameraIndex = _adapter.GetItemIndex(_cameraFragment);
viewPager.SetCurrentItem(cameraIndex, true);
break;
case "RemoveCamera":
if (_cameraFragment != null)
{
_cameraFragment.DeleteAllImages();
_adapter.RemoveFragment(_cameraFragment, "Camera");
_adapter.NotifyDataSetChanged();
_cameraFragment.Dispose();
_cameraFragment = null;
}
break;
}
}
#endregion
#region Helpers
private void InitPanel()
{
viewPager = (ViewPager)FindViewById(Resource.Id.viewpager);
SetupViewPager(viewPager);
tabLayout = (TabLayout)FindViewById(Resource.Id.tabs);
tabLayout.SetupWithViewPager(viewPager);
}
private void SetupViewPager(ViewPager viewPager)
{
_sysNoAccessFragment = new Fragments.NoAccessListFragment();
_adapter = new Adapters.NoAccessPanelFragmentsAdapter(SupportFragmentManager);
_adapter.AddFragment(_sysNoAccessFragment, "No Access");
viewPager.Adapter = _adapter;
viewPager.AdapterChange += ViewPager_AdapterChange;
}
private void BindHandlers()
{
NextButton.Click += NextButton_Click;
_sysNoAccessFragment.OnViewNewFragment += _sysNoAccessFragment_OnViewNewFragment;
tabLayout.TabSelected += TabLayout_TabSelected;
}
private void UnbindHandlers()
{
NextButton.Click -= NextButton_Click;
_sysNoAccessFragment.OnViewNewFragment -= _sysNoAccessFragment_OnViewNewFragment;
tabLayout.TabSelected -= TabLayout_TabSelected;
}
#endregion
}
When user select item from recycle view, view pager will add or remove new fragment based on which item user select
#region Events
private void _sysNoAccessFragment_OnViewNewFragment(ButtonInListClickedButtonListArgs e)
{
switch (e.ButtonName)
{
case "AddCamera":
if (_cameraFragment == null)
{
_cameraFragment = new Fragments.CameraFragment();
_adapter.AddFragment(_cameraFragment, "Camera");
//_adapter.AddFragmentWithoutTitle(_cameraFragment);
_adapter.NotifyDataSetChanged();
}
break;
case "ShowCamera":
var cameraIndex = _adapter.GetItemIndex(_cameraFragment);
viewPager.SetCurrentItem(cameraIndex, true);
break;
case "RemoveCamera":
if (_cameraFragment != null)
{
_cameraFragment.DeleteAllImages();
_adapter.RemoveFragment(_cameraFragment, "Camera");
_adapter.NotifyDataSetChanged();
_cameraFragment.Dispose();
_cameraFragment = null;
}
break;
}
}
First selection, view pager adapter add camera fragment successfully. Second selection, view pager need to remove camera fragment due to item selected from the list,my code run into break mode with message "Java.Lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference occurred"
What make things worse is i cant find any code that trigger this exception, below is the information i can find on device log cat

RecyclerView.Adapter get ItemView through position

In my Adapter, I call LayoutManager.ChildAt(position) to get the itemview, but the view I get is not the matched itemview, and when i call notifyItemChanged(position), app crashes:
E/AndroidRuntime: FATAL EXCEPTION: mainProcess: com.paicaifu.riches, PID: 8502
Java.lang.IllegalArgumentException: Called attach on a child which is not detached: ViewHolder{adb21588 position=0 id=-1, oldPos=-1, pLpos:-1}
at Android.support.v7.widget.RecyclerView$5.attachViewToParent(RecyclerView.java:654)
at android.support.v7.widget.ChildHelper.attachViewToParent(ChildHelper.java:239)
at android.support.v7.widget.RecyclerView.addAnimatingView(RecyclerView.java:1107)
at android.support.v7.widget.RecyclerView.animateChange(RecyclerView.java:3270)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3088)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2917)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)
…
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
Thanks,this is my code in the adapter:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,
final int position) {
if (holder instanceof CardHolder) {
final CardHolder cardHolder = (CardHolder) holder;
cardHolder.rootview.setOnClickListener(this);
cardHolder.rootview.setTag(position);
cardHolder.rootview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get last itemview in adapter,but preView isnot match the
//position,it is the visibable views on screen
View preView = mLinearLayoutManager.getChildAt(preIndex);
//change the datasource
mData.getResult().getCardList().get(preIndex).setOpen(false);
//update item
notifyItemChanged(preIndex);//when the item is out of screen,
//this line will cause crashes
preIndex = position;
}
});
}
I just want find the last item and change it's state(open or close),when the item is out of screen,notifyItemChanged(int position) will appear problem.
This is probably a bit too late, but the crash "Called attach on a child which is not detached" typically happens when you do NOT create a new view in onCreateViewHolder and instead return a cached view that's already inflated and attached.

Application crash while using spinner

This method is to get the inputs that includes three EditText boxes and one spinner which is populated from string-array.The click of the button is the trigger for undertaking the calculations. While the OnClick method is pressed the application crashes. The code is as follows
package biz.avksons.siddharth.hydro_basic_calc;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class UoE extends AppCompatActivity {
// Define variables for Spinner here
Spinner spinner_1;
String spin_select;
boolean dbug=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uoe);
}
// ************************************************************************************
// Start the method to calculate the units of electricity here
public void onUoECalc_ButtonClick(View v) {
/* Define Custom method for calculating the Units of electricity on clicking the Calculate button*/
//Processing variable for count
boolean flag = false; // Used to check if the inputs done in the EditText are valid or not, else there will an exception which would lead to application crash
/* Initiate the Variables here*/
//-----------------------------------------------------
//Allocate the ids of EditText to the variables for further use
EditText et_capacity = (EditText) findViewById(R.id.et_uoe_capacity);
EditText et_plf = (EditText) findViewById(R.id.et_uoe_plf);
EditText et_availability = (EditText) findViewById(R.id.et_uoe_availability);
EditText et_energy = (EditText) findViewById(R.id.et_uoe_mus);
//Variable for deciding Timeperiod
Double time_period = 365.00;
//---DEBUG <code></code>
if (dbug)
{
Toast.makeText(this, "Spiner selection : " + spin_select, Toast.LENGTH_SHORT).show();
}
//Set flag to true only if the inputs in the two edittext, discharge and head are sensible inputs
if (checkedittext(et_capacity) && checkedittext(et_plf) && checkedittext(et_availability)) {
flag = true;
} else {
//If the inputs in discharge are not sensible then display the message to input a sensible input before moving further
Toast.makeText(this, "Please enter valid inputs", Toast.LENGTH_LONG).show();
// Set the EditText box of the output to blank if the inputs are not valid as tested in the above statements
et_capacity.setText("");
}
// do this operation only if the flag is set to true which are tested above
if (flag == true) {
//-------Initiating Spinner here
addListenerOnSpinnerItemSelection();
// Set selection default for Spinner here
// spinner_1.setSelection(1);
//--------Allocation of Spin Button Here-------------
if (dbug)
{
Toast.makeText(this, "Spin_select"+ spin_select, Toast.LENGTH_SHORT).show();
}
switch (spin_select) {
case "1 yr":
time_period = 365.00;
case "6 mon":
time_period = 180.00;
case "3 mon":
time_period = 90.00;
}
//-------End of Spin Button--------------
//Assign the values here
Double d_capacity = Double.parseDouble(et_capacity.getText().toString());
Double d_plf = Double.parseDouble(et_plf.getText().toString());
Double d_availability = Double.parseDouble(et_availability.getText().toString());
//-DEBUG Code----
if(dbug)
{
Toast.makeText(this, "Time Period selected" + time_period.toString(), Toast.LENGTH_SHORT).show();
}
Double d_energy = Double.valueOf((d_capacity * 1000 * 24 * time_period * d_plf * d_availability) / 1000000);
et_energy.setText(Double.toString(Math.round(d_energy))); // In MW
// capacity.setText(String.format(".2%f",Double.toString(C)));
}
}
//Method to check for validity of contents in edittext
public boolean checkedittext(EditText edtxt) {
if (edtxt.getText().toString().matches("")) {
return false;
} else {
return true;
}
}
//--------Method to get the selected option from Spinner
public void addListenerOnSpinnerItemSelection() {
//------Declare a variable on Spinner and allocate the id here
spinner_1 = (Spinner) findViewById(R.id.spin_uoe_period);
spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
spin_select = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void onHelp_UoE(View v)
{
Toast.makeText(this,"Please enter valid figures in the boxes mentioned and select the period you are interested in; from the dropdown menu before pressing calculate",Toast.LENGTH_LONG).show();
}
}
The error in Logcat is as follows
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4240) 
at android.view.View$PerformClick.run(View.java:17721) 
at android.os.Handler.handleCallback(Handler.java:730) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at biz.avksons.siddharth.hydro_basic_calc.UoE.onUoECalc_ButtonClick(UoE.java:84)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4240) 
at android.view.View$PerformClick.run(View.java:17721) 
at android.os.Handler.handleCallback(Handler.java:730) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
I tried to find the NullPointerException error which as per the code suggests that the spinner_select variable is not initialized. My understanding tells me that the spinner_select variable should be initialized every time the method is called.
Request for assistance..Thank You
I hope you have missed
break;
in switch case statement