Heelp me for using viewmodel with radio group,when i rotate it was unchecked - radio-button

FirstPage.java
'viewModel = new ViewModelProvider(requireActivity()).get(PagesVM.class);
radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
checkedId = group.getCheckedRadioButtonId();
invisibleBtn.setVisibility(View.INVISIBLE);
switch (checkedId) {
case 0:
case 1:
case 2:
case 3:
count += 0;
break;
case 4:
count += 1;
break;
}
viewModel.getSelectedValue().observe(getViewLifecycleOwner(),check -> {
radioGroup.setSelected(check);
});
});'
FirstPageVm.java
public class PagesVM extends ViewModel {
MutableLiveData<Boolean> setItem=new MutableLiveData<Boolean>();
LiveData<Boolean> getSelectedValue(){
return setItem;
}
RadioGroup radioGroup;
public void slectItem(){
setItem.setValue(radioGroup.isSelected());
}
}
Error
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8512)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.RadioGroup.isSelected()' on a null object reference
at mening.dasturim.mytest.ui.pages.PagesVM.slectItem(PagesVM.java:21)
at mening.dasturim.mytest.ui.pages.FirstPage.onDestroy(FirstPage.java:115)
at androidx.fragment.app.Fragment.performDestroy(Fragment.java:3219)
at androidx.fragment.app.FragmentStateManager.destroy(FragmentStateManager.java:774)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:350)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
at androidx.fragment.app.FragmentManager.dispatchDestroy(FragmentManager.java:3107)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5587)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5647) 
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5939) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5869) 
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:246) 
at android.app.ActivityThread.main(ActivityThread.java:8512) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130) 
2021-08-14 02:21:59.001 4226-4548/? E/BufferQueueProducer: com.samsung.android.app.cocktailbarservice/com.samsung.android.app.cocktailbarservice.CocktailBarService$_11743#0 disconnect: not connected (req=1)
2021-08-14 02:21:59.011 4900-4900/? E/ndroid.systemu: Invalid ID 0x00000000.

you should omit
RadioGroup radioGroup;
public void slectItem(){
setItem.setValue(radioGroup.isSelected());
}
and run again

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);

Problem with Ignite readThrough when key is BinaryObject and no classes available for key type

I have a usecase where my Ignite cache key/value cannot have corresponding Java class, I am using BinaryObject as key and value type. Below code works fine (without any readthrough).
CacheConfiguration cfg = new CacheConfiguration("cache1");
IgniteCache<BinaryObject, BinaryObject> cache1 = ignite.getOrCreateCache(cfg).withKeepBinary();
cache1.put(createBOKey("mykey", "k1"), createBOVal());
cache1.put(createBOKey("mykey", "k2"), createBOVal());
cache1.put(createBOKey("mykey", "k3"), createBOVal());
Object v1 = cache1.get(createBOKey("mykey", "k1"));
System.out.println("**** cache1 key " + v1); // shows value
Object v2 = cache1.get(createBOKey("mykey", "k10"));
System.out.println("**** cache1 key " + v2); // show null
BinaryObject createBOKey(String k, String v) {
BinaryObjectBuilder builder = ignite.binary().builder("key-type1");
builder.setField(k, v);
return builder.build();
}
BinaryObject createBOVal() {
BinaryObjectBuilder builder = ignite.binary().builder("value-type1");
builder.setField(fieldName("cache1", "f1"), "hello");
builder.setField(fieldName("cache1", "f2"), 10.75);
return builder.build();
}
Now as soon as I enable readThrough for this cache it starts failing for cache miss cases.
cfg.setReadThrough(true);
cfg.setCacheLoaderFactory(new Factory<CacheLoader<BinaryObject, BinaryObject>>() {
#Override
public CacheLoader<BinaryObject, BinaryObject> create() {
return new CacheLoader<BinaryObject, BinaryObject>() {
#Override
public BinaryObject load(BinaryObject obj) throws CacheLoaderException {
System.out.println("**** Loading from backingstore " + obj);
return null;
}
#Override
public Map<BinaryObject, BinaryObject> loadAll(Iterable<? extends BinaryObject> arg0) throws CacheLoaderException {
return null;
}
};
}
});
On cache miss it throw below exceptions and not even reaches cacheloader.load().
Exception in thread "main" javax.cache.CacheException: class org.apache.ignite.IgniteCheckedException: key-type1
at org.apache.ignite.internal.processors.cache.GridCacheUtils.convertToCacheException(GridCacheUtils.java:1317)
at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.cacheException(IgniteCacheProxyImpl.java:2066)
at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.get(IgniteCacheProxyImpl.java:1093)
at org.apache.ignite.internal.processors.cache.GatewayProtectedCacheProxy.get(GatewayProtectedCacheProxy.java:676)
at com.basit.bo.btree.TestBinaryTreeMapKey.main(TestBinaryTreeMapKey.java:74)
Caused by: class org.apache.ignite.IgniteCheckedException: key-type1
at org.apache.ignite.internal.util.IgniteUtils.cast(IgniteUtils.java:7507)
at org.apache.ignite.internal.processors.closure.GridClosureProcessor$2.body(GridClosureProcessor.java:975)
at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: class org.apache.ignite.binary.BinaryInvalidTypeException: key-type1
at org.apache.ignite.internal.binary.BinaryContext.descriptorForTypeId(BinaryContext.java:762)
at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize0(BinaryReaderExImpl.java:1757)
at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize(BinaryReaderExImpl.java:1716)
at org.apache.ignite.internal.binary.BinaryObjectImpl.deserializeValue(BinaryObjectImpl.java:792)
at org.apache.ignite.internal.binary.BinaryObjectImpl.value(BinaryObjectImpl.java:142)
at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinary(CacheObjectUtils.java:176)
at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinaryIfNeeded(CacheObjectUtils.java:67)
at org.apache.ignite.internal.processors.cache.CacheObjectContext.unwrapBinaryIfNeeded(CacheObjectContext.java:136)
at org.apache.ignite.internal.processors.cache.GridCacheContext.unwrapBinaryIfNeeded(GridCacheContext.java:1808)
at org.apache.ignite.internal.processors.cache.GridCacheContext.unwrapBinaryIfNeeded(GridCacheContext.java:1796)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.loadFromStore(GridCacheStoreManagerAdapter.java:314)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.load(GridCacheStoreManagerAdapter.java:293)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.loadAllFromStore(GridCacheStoreManagerAdapter.java:434)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.loadAll(GridCacheStoreManagerAdapter.java:400)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$18.call(GridCacheAdapter.java:2225)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$18.call(GridCacheAdapter.java:2223)
at org.apache.ignite.internal.processors.cache.GridCacheContext$3.call(GridCacheContext.java:1479)
at org.apache.ignite.internal.util.IgniteUtils.wrapThreadLoader(IgniteUtils.java:7005)
at org.apache.ignite.internal.processors.closure.GridClosureProcessor$2.body(GridClosureProcessor.java:967)
... 4 more
Caused by: java.lang.ClassNotFoundException: key-type1
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at org.apache.ignite.internal.util.IgniteUtils.forName(IgniteUtils.java:8828)
at org.apache.ignite.internal.MarshallerContextImpl.getClass(MarshallerContextImpl.java:324)
at org.apache.ignite.internal.binary.BinaryContext.descriptorForTypeId(BinaryContext.java:753)
... 22 more
You should also set storeKeepBinary to true.

Dynamically Displaying data into TableView from Database ERROR IN cellvaluefactory

Can anyone Help?
I want to dynamically display my Database content into TableView in FXML file.
The Code works when I don't have any null Value in any of the column database.
I expected the code should display empty space in TableView of FXML when my database column has a null value.
dateOfIssue.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(2).toString());
}
});
studentID.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(3).toString());
}
});
primary.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(0).toString());
}
});
secondary.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(1).toString());
}
});
I have my secondary column as null at few rows.here is my error.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at library.DatabaseController$4.call(DatabaseController.java:105)
at library.DatabaseController$4.call(DatabaseController.java:103)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:533)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64)
at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
at javafx.scene.control.Control.impl_processCSS(Control.java:872)
at javafx.scene.Node.processCSS(Node.java:9058)
at javafx.scene.Node.applyCss(Node.java:9155)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1964)
at com.sun.javafx.scene.control.skin.VirtualFlow.addTrailingCells(VirtualFlow.java:1344)
at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1197)
at javafx.scene.Parent.layout(Parent.java:1087)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Scene.doLayoutPass(Scene.java:552)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2397)
at com.sun.javafx.tk.Toolkit.lambda$runPulse$29(Toolkit.java:398)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:397)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:424)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:518)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:498)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:491)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$403(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at library.DatabaseController$4.call(DatabaseController.java:105)
at library.DatabaseController$4.call(DatabaseController.java:103)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:533)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64)
at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
at javafx.scene.control.Control.impl_processCSS(Control.java:872)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.control.Control.impl_processCSS(Control.java:868)
at javafx.scene.Node.processCSS(Node.java:9058)
at javafx.scene.Node.processCSS(Node.java:9051)
at javafx.scene.Node.processCSS(Node.java:9051)
at javafx.scene.Node.processCSS(Node.java:9051)
at javafx.scene.Scene.doCSSPass(Scene.java:545)
at javafx.scene.Scene.access$3600(Scene.java:159)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2392)
at com.sun.javafx.tk.Toolkit.lambda$runPulse$29(Toolkit.java:398)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:397)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:424)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:518)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:498)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:491)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$403(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
I assume your issue is at below point. If your value is null, obviously you will get NPE when accessing toString(). Try to do some null checks before calling toString().
param.getValue().get(1).toString()
If one of the ObservableLists contains null, trying to invoke toString for such an object results in the NullPointerException. I recommend using different code to convert to a string, e.g. Objects.toString:
secondary.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(Objects.toString(param.getValue().get(1), ""));
}
});

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

Holo.NoTitleBar & 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