Application crash while using spinner - crash

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

Related

How does Object.notify() work with Object.wait()?

I am trying to track a resource which behaves in an asymmetric manner. That is, it responds immediately to a start() request, but finishes processing a cancel() request at a significant delay.
For this purpose, I created an AtomicBoolean flag, with the intent to set it (true) immediately, but clear it (false) via a CountDownTimer.
protected AtomicBoolean mIsAsymmetricMode = new AtomicBoolean(false);
This flag is never set directly by any of the classes involved. It is always set and cleared via a dedicated method.
All callers of this setAsymmetricMode(boolean) method, run on the same thread - the main (UI) thread.
On a different thread I have an operation waiting for this flag to be cleared (false).
The following is a minimal working MainActivity.java that demonstrates the issue:
package com.example.basicactivity;
import static com.example.basicactivity.Log.logE;
import static com.example.basicactivity.Log.logW;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.CountDownTimer;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.basicactivity.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import java.util.concurrent.atomic.AtomicBoolean;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
protected final AtomicBoolean mIsAsymmetricMode = new AtomicBoolean(false);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
/*
logE() waiting for mIsAsymmetricMode set to FALSE
*/
binding.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logW("ASYMMETRIC", "^");
new Thread( () -> {
synchronized(mIsAsymmetricMode) {
while (mIsAsymmetricMode.get()) {
try {
mIsAsymmetricMode.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
logE("ASYMMETRIC", "mIsAsymmetricMode=false");
}
}).start();
logW("ASYMMETRIC", "$");
}
});
}
protected void setAsymmetricMode(boolean is) {
logW("ASYMMETRIC", "^ " + is);
if (is) {
mIsAsymmetricMode.compareAndSet(false, true);
}
else {
new CountDownTimer(100, 50) {
int tickCounter = 0;
public void onTick(long millUntilFinish) {
tickCounter++;
logW("ASYMMETRIC", "tickCounter=" + tickCounter);
}
public void onFinish() {
logW("ASYMMETRIC", "^");
synchronized(mIsAsymmetricMode) {
mIsAsymmetricMode.compareAndSet(true, false);
mIsAsymmetricMode.notifyAll();
}
logW("ASYMMETRIC", "$");
}
}.start();
}
logW("ASYMMETRIC", "$");
}
#Override // TRUE test (immediate)
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
setAsymmetricMode(true);
return true;
}
#Override // FALSE test (delayed)
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
setAsymmetricMode(false);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration) || super.onSupportNavigateUp();
}
}
When run, it presents a screen with two areas triggering listeners in this code:
The code works as expected, that is, when the "envelope button" is touched first, no logE() message is output to Logcat (it is waiting on the mIsAsymmetricMode flag), then when the "settings button" is touched, the logE() message is printed (last one, starting with "16:52:00.607 E T=8382"):
---------------------------- PROCESS STARTED (8121) for package com.example.basicactivity ----------------------------
16:51:22.206 W T=8121 MainActivity.setAsymmetricMode < MainActivity.onCreateOptionsMenu | ^ true
16:51:22.207 W T=8121 MainActivity.setAsymmetricMode < MainActivity.onCreateOptionsMenu | $
16:51:34.163 W T=8121 MainActivity$1.onClick < View.performClick | ^
16:51:34.165 W T=8121 MainActivity$1.onClick < View.performClick | $
16:52:00.504 W T=8121 MainActivity.setAsymmetricMode < MainActivity.onOptionsItemSelected | ^ false
16:52:00.508 W T=8121 MainActivity.setAsymmetricMode < MainActivity.onOptionsItemSelected | $
16:52:00.518 W T=8121 MainActivity$2.onTick < CountDownTimer$1.handleMessage | tickCounter=1
16:52:00.568 W T=8121 MainActivity$2.onTick < CountDownTimer$1.handleMessage | tickCounter=2
16:52:00.606 W T=8121 MainActivity$2.onFinish < CountDownTimer$1.handleMessage | ^
16:52:00.607 W T=8121 MainActivity$2.onFinish < CountDownTimer$1.handleMessage | $
16:52:00.607 E T=8382 MainActivity$1.lambda$onClick$0$com-example-basicactivity-MainActivity$1 < MainActivity$1$$ExternalSyntheticLambda0.run | mIsAsymmetricMode=false
Now... what I am trying to understand is why when I remove the
mIsAsymmetricMode.notifyAll();
statement in onFinish(), that logE() message is never released as it seems that the while loop gets stuck at the
mIsAsymmetricMode.wait();
and never gets to check for the flag and see that it changed to false.
In other words, are there any circumstances in which the while (mIsAsymmetricMode.get()) loop will terminate without issuing the mIsAsymmetricMode.notifyAll() (or mIsAsymmetricMode.notify()) call?
Update: After being helped by the accepted answer, I highly recommend testing the flag before entering the while() loop - despite it being tested by the while() loop anyway. The reason is that it allows placing debug logs as follows:
new Thread( () -> {
synchronized(mIsAsymmetricMode) {
if (mIsAsymmetricMode.get()) {
logD("ASYMMETRIC", "while() loop entered");
while (mIsAsymmetricMode.get()) {
try {
mIsAsymmetricMode.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
else {
logW("ASYMMETRIC", "while() loop NOT entered");
}
}
}).start();
Here is how it works in general:
Thread acquires the lock on the object (mIsAsymmetricMode in your case).
Thread releases the lock on the object and enters the waiting state.
Other thread acquires the lock on the object and make changes to the object.
Other thread releases the lock on the object.
The thread that was waiting is notified via notify() or notifyAll().
The thread wakes up and re-acquires the lock on the object.
The thread checks the object state and exits the loop if the condition is met.
Notice #5 and #6: Without notify() or notifyAll(), there is no chance for the waiting thread of ever knowing that the object state has changed. Therefore it has no chance of exiting the loop via met condition.
This confirms what you are seeing on the code you posted. It works correctly.
If you have more complex code that exhibits a different behavior, a possible explanations could be a race condition, where the value of mIsAsymmetricMode is being changed to false right before the thread enters the wait state.
Also, check whether the AtomicBoolean in your other code is final.

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

NullPointerException in Intelli J javafx CRUD

I am trying to build javafx CRUD model with intellij and when I run the Main.java, Login window pops up. And when I type the correct username and password, another popup window in table so that where data can be created, read, updated and deleted.
After I typed correct password and username, Login window appeared, however, I faced NullPointerException in console as below.
When I hit Login button. I went back to two lines stated;
sortFilterTableView();
searchTextField.textProperty().addListener((observable, oldValue, newValue) -> {
there were no issues found. In other java and fxml files are all error-free. I rebuilt the project and ran it again many times but they didn't work showing me this same error. Any advice where should I begin to examine? Thank you. (Localhost is connected)
screenshot
Error in a console box
/usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java --add-modules
javafx.base,javafx.graphics --add-reads javafx.base=ALL-UNNAMED
--add-reads javafx.graphics=ALL-UNNAMED -javaagent:/snap/intellij-idea-community/232/lib/idea_rt.jar=40981:/snap/intellij-idea-community/232/bin
-Dfile.encoding=UTF-8 -p /usr/share/openjfx/lib/javafx.base.jar:/usr/share/openjfx/lib/javafx.graphics.jar:/home/marie/IdeaProjects/CosmeticsJavaFX/src/out/production/CosmeticsJavaFX:/usr/share/openjfx/lib/javafx.controls.jar:/usr/share/openjfx/lib/javafx.fxml.jar:/usr/share/openjfx/lib/javafx.media.jar:/usr/share/openjfx/lib/javafx.swing.jar:/usr/share/openjfx/lib/javafx.web.jar:/home/marie/Downloads/mariadb-java-client-2.6.0.jar
-m CosmeticsJavaFX/application.Main
wwww
wwww
Password matches
Radio button selected: null
User ID is: 9
Exception in thread "JavaFX Application Thread"
java.lang.NullPointerException at
CosmeticsJavaFX/application.DatabaseController.sortFilterTableView(DatabaseController.java:186)
at
CosmeticsJavaFX/application.DatabaseController.lambda$initialize$4(DatabaseController.java:101)
at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(Native
Method) at
javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at
javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at
javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native
Method) at
javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
at java.base/java.lang.Thread.run(Thread.java:834)
DatabaseController.java:101
#FXML
private void initialize(){
//initialize the tableView with four columns
itemIdColumn.setCellValueFactory(cellData -> cellData.getValue().itemIdProperty());
userIdColumn.setCellValueFactory(cellData -> cellData.getValue().userIdProperty());
labelColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty());
brandColumn.setCellValueFactory(cellData -> cellData.getValue().brandProperty());
setVisibleItems();
Platform.runLater(() -> {
//fill the tableView with data from observableList
try {
System.out.println("User ID is: " + userId);
tableView.setItems(getCosmeticsData());
buildCosmetics();
//line 101 below
sortFilterTableView();
//
observeRadioButtonChanges();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
});
}
DatabaseController.java:186
private void sortFilterTableView() throws SQLException {
FilteredList<Cosmetics> filteredList = new FilteredList<>(getCosmeticsData(), p -> true);
//this is line 186 below
searchTextField.textProperty().addListener((observable, oldValue, newValue) -> {
//
filteredList.setPredicate(cosmetics -> {
//if search text is empty display all cosmetics
if(newValue == null || newValue.isEmpty()){
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (cosmetics.getLabel().toLowerCase().contains(lowerCaseFilter)){
return true; // search string is a match
} else if(cosmetics.getBrand().toLowerCase().contains(lowerCaseFilter)){
return true; // search string is a match
}
return false; //does not match
});
});
SortedList<Cosmetics> sortedList = new SortedList<>(filteredList);
sortedList.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(sortedList);
}
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("AddressScene.fxml"));
Parent root = (Parent) fxmlLoader.load();
// open the login scene
stage.setTitle("Server Address");
stage.setScene(new Scene(root));
stage.show();
}
}
Check the Java variable searchTextField has a corresponding FXML element with a matching fx:id
<TextField fx:id="searchTextField" .........

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.

Robotium test case not Running at all

Am a day old to Robotium. Hence trying to run some apps on Robotium.
I have done a simple calci app and am trying to run it using Robotium.
But the Robotium app is not responding at all. Neither the tests are being done.
I have included the permissions in Manifest file and all. But still the Program never runs.
My Source Code for Robotium Test is like this:
package com.example.demo.project.test;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.EditText;
import android.widget.TextView;
import com.example.demo.project.MainActivity;
import com.example.demo.project.R;
import com.jayway.android.robotium.solo.Solo;
public class SampleQA extends ActivityInstrumentationTestCase2<MainActivity> {
public SampleQA(Class<MainActivity> activityClass) {
super(activityClass);
// TODO Auto-generated constructor stub
}
private Solo solo;
/*public TestMain()
{
super(MainActivity.class);
}*/
#Override
protected void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation(), getActivity());
}
public void testDisplayBlackBox() {
//Enter 10 in first edit-field
solo.enterText(0, "10");
//Enter 20 in first edit-field
solo.enterText(1, "20");
//Click on Multiply button
solo.clickOnButton("Multiply");
//Verify that resultant of 10 x 20
assertTrue(solo.searchText("200"));
}
public void testDisplayWhiteBox() {
//Defining our own values to multiply
float firstNumber = 10;
float secondNumber = 20;
float resutl = firstNumber * secondNumber ;
//Access First value (edit-filed) and putting firstNumber value in it
EditText FirsteditText = (EditText) solo.getView(R.id.EditText01);
solo.enterText(FirsteditText, String.valueOf(firstNumber));
//Access Second value (edit-filed) and putting SecondNumber value in it
EditText SecondeditText = (EditText) solo.getView(R.id.EditText02);
solo.enterText(SecondeditText, String.valueOf(secondNumber));
//Click on Multiply button
solo.clickOnButton("Multiply");
assertTrue(solo.searchText(String.valueOf(resutl)));
TextView outputField = (TextView) solo.getView(R.id.TextView01);
//Assert to verify result with visible value
assertEquals(String.valueOf(resutl), outputField.getText().toString());
}
#Override
protected void tearDown() throws Exception{
try {
solo.finalize();
}
catch (Throwable e)
{
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
}
The Test is not getting executed at all.
Please help me out Folks!!
Thanks.
Can you be more specific on the errors that you are encounter? maybe put some examples?
Your main activity of the application under test it is named MainActivity?
Maybe you should change the constructor from
public SampleQA(Class<MainActivity> activityClass) {
super(activityClass);
// TODO Auto-generated constructor stub
}
to
public SampleQA() {
super(MainActivity.class);
}