I'm working on a calculator app for my class project in school, but there seem to be some errors behind the scenes that are not syntax-based. I try to run my app it crashes. I have been unable to find my error but it always crashes after I hit the submit button. I haven't had an app just completely refuse to run.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stins.calculator">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="com.example.stins.calculator.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
MainActivity.java
package com.example.stins.calculator;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.example.stins.calculator.Calculator;
import com.example.stins.calculator.CalculatorImpl;
import com.example.stins.calculator.Config;
import com.example.stins.calculator.Constants;
import com.example.stins.calculator.Formatter;
import com.example.stins.calculator.R;
import com.example.stins.calculator.Utils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import me.grantland.widget.AutofitHelper;
public class MainActivity extends SimpleActivity implements Calculator {#BindView(R.id.result)
TextView mResult;#BindView(R.id.formula)
TextView mFormula;
private static CalculatorImpl mCalc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
CalculatorImpl calc = new CalculatorImpl(this);
AutofitHelper.create(mResult);
AutofitHelper.create(mFormula);
}
#OnClick(R.id.btn_plus)
public void plusClicked() {
mCalc.handleOperation(Constants.PLUS);
}
#OnClick(R.id.btn_minus)
public void minusClicked() {
mCalc.handleOperation(Constants.MINUS);
}
#OnClick(R.id.btn_multiply)
public void multiplyClicked() {
mCalc.handleOperation(Constants.MULTIPLY);
}
#OnClick(R.id.btn_divide)
public void divideClicked() {
mCalc.handleOperation(Constants.DIVIDE);
}
#OnClick(R.id.btn_modulo)
public void moduloClicked() {
mCalc.handleOperation(Constants.MODULO);
}
#OnClick(R.id.btn_power)
public void powerClicked() {
mCalc.handleOperation(Constants.POWER);
}
#OnClick(R.id.btn_root)
public void rootClicked() {
mCalc.handleOperation(Constants.ROOT);
}
#OnClick(R.id.btn_clear)
public void clearClicked() {
mCalc.handleClear();
}
#OnLongClick(R.id.btn_clear)
public boolean clearLongClicked() {
mCalc.handleReset();
return true;
}
#OnClick(R.id.btn_equals)
public void equalsClicked() {
mCalc.handleEquals();
}
#OnClick({
R.id.btn_decimal,
R.id.btn_0,
R.id.btn_1,
R.id.btn_2,
R.id.btn_3,
R.id.btn_4,
R.id.btn_5,
R.id.btn_6,
R.id.btn_7,
R.id.btn_8,
R.id.btn_9
})
public void numpadClick(View view) {
numpadClicked(view.getId());
}
public void numpadClicked(int id) {
mCalc.numpadClicked(id);
}
#Override
public void setValue(String value) {
mResult.setText(value);
}
// used only by Robolectric
#Override
public void setValueDouble(double d) {
mCalc.setValue(Formatter.doubleToString(d));
mCalc.setLastKey(Constants.DIGIT);
}
public void setFormula(String value) {
mFormula.setText(value);
}
public CalculatorImpl getCalc() {
return mCalc;
}
}
CalcImpl.java
package com.example.stins.calculator;
public class CalculatorImpl {
private String mDisplayedValue;
private String mDisplayedFormula;
private String mLastKey;
private String mLastOperation;
private Calculator mCallback;
private boolean mIsFirstOperation;
private boolean mResetValue;
private double mBaseValue;
private double mSecondValue;
public CalculatorImpl(Calculator calculator) {
mCallback = calculator;
resetValues();
setValue("0");
setFormula("");
}
public CalculatorImpl(Calculator calculatorInterface, String value) {
mCallback = calculatorInterface;
resetValues();
mDisplayedValue = value;
setFormula("");
}
private void resetValueIfNeeded() {
if (mResetValue) mDisplayedValue = "0";
mResetValue = false;
}
private void resetValues() {
mBaseValue = 0;
mSecondValue = 0;
mResetValue = false;
mLastKey = "";
mLastOperation = "";
mDisplayedValue = "";
mDisplayedFormula = "";
mIsFirstOperation = true;
}
public void setValue(String value) {
mCallback.setValue(value);
mDisplayedValue = value;
}
private void setFormula(String value) {
mCallback.setFormula(value);
mDisplayedFormula = value;
}
private void updateFormula() {
final String first = Formatter.doubleToString(mBaseValue);
final String second = Formatter.doubleToString(mSecondValue);
final String sign = getSign(mLastOperation);
if (sign.equals("√")) {
setFormula(sign + first);
} else if (!sign.isEmpty()) {
setFormula(first + sign + second);
}
}
public void setLastKey(String mLastKey) {
this.mLastKey = mLastKey;
}
public void addDigit(int number) {
final String currentValue = getDisplayedNumber();
final String newValue = formatString(currentValue + number);
setValue(newValue);
}
private String formatString(String str) {
// if the number contains a decimal, do not try removing the leading zero anymore, nor add group separator
// it would prevent writing values like 1.02
if (str.contains(".")) return str;
final double doubleValue = Formatter.stringToDouble(str);
return Formatter.doubleToString(doubleValue);
}
private void updateResult(double value) {
setValue(Formatter.doubleToString(value));
mBaseValue = value;
}
public String getDisplayedNumber() {
return mDisplayedValue;
}
public double getDisplayedNumberAsDouble() {
return Formatter.stringToDouble(getDisplayedNumber());
}
public String getDisplayedFormula() {
return mDisplayedFormula;
}
public void handleResult() {
mSecondValue = getDisplayedNumberAsDouble();
calculateResult();
mBaseValue = getDisplayedNumberAsDouble();
}
public void calculateResult() {
if (!mIsFirstOperation) updateFormula();
switch (mLastOperation) {
case Constants.PLUS:
updateResult(mBaseValue + mSecondValue);
break;
case Constants.MINUS:
updateResult(mBaseValue - mSecondValue);
break;
case Constants.MULTIPLY:
updateResult(mBaseValue * mSecondValue);
break;
case Constants.DIVIDE:
divideNumbers();
break;
case Constants.MODULO:
moduloNumbers();
break;
case Constants.POWER:
powerNumbers();
break;
case Constants.ROOT:
updateResult(Math.sqrt(mBaseValue));
break;
default:
break;
}
mIsFirstOperation = false;
}
private void divideNumbers() {
double resultValue = 0;
if (mSecondValue != 0) resultValue = mBaseValue / mSecondValue;
updateResult(resultValue);
}
private void moduloNumbers() {
double resultValue = 0;
if (mSecondValue != 0) resultValue = mBaseValue % mSecondValue;
updateResult(resultValue);
}
private void powerNumbers() {
double resultValue = Math.pow(mBaseValue, mSecondValue);
if (Double.isInfinite(resultValue) || Double.isNaN(resultValue)) resultValue = 0;
updateResult(resultValue);
}
public void handleOperation(String operation) {
if (mLastKey.equals(Constants.DIGIT)) handleResult();
mResetValue = true;
mLastKey = operation;
mLastOperation = operation;
if (operation.equals(Constants.ROOT)) calculateResult();
}
public void handleClear() {
final String oldValue = getDisplayedNumber();
String newValue = "0";
final int len = oldValue.length();
int minLen = 1;
if (oldValue.contains("-")) minLen++;
if (len > minLen) newValue = oldValue.substring(0, len - 1);
newValue = newValue.replaceAll("\\.$", "");
newValue = formatString(newValue);
setValue(newValue);
mBaseValue = Formatter.stringToDouble(newValue);
}
public void handleReset() {
resetValues();
setValue("0");
setFormula("");
}
public void handleEquals() {
if (mLastKey.equals(Constants.EQUALS)) calculateResult();
if (!mLastKey.equals(Constants.DIGIT)) return;
mSecondValue = getDisplayedNumberAsDouble();
calculateResult();
mLastKey = Constants.EQUALS;
}
public void decimalClicked() {
String value = getDisplayedNumber();
if (!value.contains(".")) value += ".";
setValue(value);
}
public void zeroClicked() {
String value = getDisplayedNumber();
if (!value.equals("0")) addDigit(0);
}
private String getSign(String lastOperation) {
switch (lastOperation) {
case Constants.PLUS:
return "+";
case Constants.MINUS:
return "-";
case Constants.MULTIPLY:
return "*";
case Constants.DIVIDE:
return "/";
case Constants.MODULO:
return "%";
case Constants.POWER:
return "^";
case Constants.ROOT:
return "√";
}
return "";
}
public void numpadClicked(int id) {
if (mLastKey.equals(Constants.EQUALS)) mLastOperation = Constants.EQUALS;
mLastKey = Constants.DIGIT;
resetValueIfNeeded();
switch (id) {
case R.id.btn_decimal:
decimalClicked();
break;
case R.id.btn_0:
zeroClicked();
break;
case R.id.btn_1:
addDigit(1);
break;
case R.id.btn_2:
addDigit(2);
break;
case R.id.btn_3:
addDigit(3);
break;
case R.id.btn_4:
addDigit(4);
break;
case R.id.btn_5:
addDigit(5);
break;
case R.id.btn_6:
addDigit(6);
break;
case R.id.btn_7:
addDigit(7);
break;
case R.id.btn_8:
addDigit(8);
break;
case R.id.btn_9:
addDigit(9);
break;
default:
break;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/calculator_holder"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.stins.calculator.MainActivity">
<TextView
android:id="#+id/formula"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2.1"
android:fontFamily="sans-serif-light"
android:gravity="right|bottom"
android:maxLines="1"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:textSize="#dimen/formula_text_size"/>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.8"
android:fontFamily="sans-serif-light"
android:gravity="center_vertical|right"
android:maxLines="1"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:text="0"
android:textSize="#dimen/display_text_size"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_modulo"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="mod"
android:textAllCaps="false"
android:textSize="#dimen/mod_text_size"/>
<Button
android:id="#+id/btn_power"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="^"/>
<Button
android:id="#+id/btn_root"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="√"/>
<Button
android:id="#+id/btn_clear"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="C"/>
<Button
android:id="#+id/btn_reset"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="AC"
android:visibility="gone"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_7"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7"/>
<Button
android:id="#+id/btn_8"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="8"/>
<Button
android:id="#+id/btn_9"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="9"/>
<Button
android:id="#+id/btn_divide"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="÷"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_4"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4"/>
<Button
android:id="#+id/btn_5"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="5"/>
<Button
android:id="#+id/btn_6"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="6"/>
<Button
android:id="#+id/btn_multiply"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="*"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_1"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1"/>
<Button
android:id="#+id/btn_2"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="2"/>
<Button
android:id="#+id/btn_3"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="3"/>
<Button
android:id="#+id/btn_minus"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="-"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_0"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="0"/>
<Button
android:id="#+id/btn_decimal"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="."/>
<Button
android:id="#+id/btn_equals"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="="/>
<Button
android:id="#+id/btn_plus"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="+"/>
</LinearLayout>
</LinearLayout>
logcat
02-11 14:27:36.485 5006-5006/com.example.stins.calculator E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.stins.calculator, PID: 5006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stins.calculator/com.example.stins.calculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
at me.grantland.widget.AutofitHelper.<init>(AutofitHelper.java:246)
at me.grantland.widget.AutofitHelper.create(AutofitHelper.java:62)
at me.grantland.widget.AutofitHelper.create(AutofitHelper.java:46)
at com.example.stins.calculator.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
If at all possible, would anyone know how to help ?
I included my logcat as well
Check to make sure that you have the annotationProcessor for butterknife setup in your build.gradle. You should have a line under dependencies that looks like this:
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'.
After you add that run build->rebuild project.
Related
I am working on an existing project where tablayout is integrated but the tab items title are not displaying well arranged. Below is screenshot of what it looks like and also a screenshot of how i want it to look like
This is actually how i want the tab item title displaying
This is my xml file code snippet:
<?xml version="1.0" encoding="utf-8"?>
<layout 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=".salesinvoice.fragments.SalesInvoiceInstanceFragment">
<data>
<variable
name="salesRecord"
type="com.mainsoftdc.costoma.salesinvoice.entities.SalesRecord" />
<variable
name="eventHandler"
type="com.mainsoftdc.costoma.salesinvoice.eventhandlers.SalesInvoiceInstanceEventHandler" />
<import type="com.mainsoftdc.costoma.shared.utils.DecimalFormatter" />
<import type="com.mainsoftdc.costoma.shared.utils.MoneyFormatter" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/sales_instance_top_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorGreyLight"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_xs"
android:paddingRight="#dimen/padding_xs"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/btn_edit_sale_instance_customer_name"
style="#style/BtnTextPrimarySmNoPadding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{() -> eventHandler.editCustomerName()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_edit_customer_name"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/text_12sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_close_sale_instance"
style="#style/BtnTextPrimarySmNoPadding"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{() -> eventHandler.closeSaleInstance()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_close_invoice"
android:textColor="#color/colorRed"
android:textSize="#dimen/text_12sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/sales_product_list_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingStart="#dimen/padding_xs"
android:paddingTop="#dimen/padding_xxs"
android:paddingEnd="#dimen/padding_xs"
android:paddingBottom="#dimen/no_padding"
app:layout_constraintTop_toBottomOf="#id/sales_instance_top_layout">
<TextView
android:id="#+id/sales_instance_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_all_items"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="#+id/btn_add_item_to_sales"
style="#style/BtnSecondarySmOutlined"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:gravity="center"
android:minWidth="0dp"
android:minHeight="0dp"
android:onClick="#{() -> eventHandler.addItemToSalesBook()}"
android:padding="#dimen/padding_xs"
android:text="#string/sales_instance_add_item"
android:textSize="#dimen/text_10sp"
app:icon="#drawable/ic_add_circle_black_24dp"
app:iconSize="14dp"
app:iconTint="#color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:id="#+id/sales_instance_product_list"
style="#style/ListPage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="#id/sales_instance_buttons"
app:layout_constraintTop_toBottomOf="#id/sales_product_list_header"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/sales_instance_product_list_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginBottom="#dimen/margin_md"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</LinearLayout>
<LinearLayout
android:id="#+id/sales_instance_sales_summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorGreyLight"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_sm"
android:paddingRight="#dimen/padding_sm"
android:paddingTop="#dimen/padding_xs"
android:paddingBottom="#dimen/padding_xs"
app:layout_constraintBottom_toTopOf="#id/sales_instance_buttons">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="2"
android:orientation="vertical">
<TextView
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sales_instance_total_volume"
android:textColor="#color/colorBlack" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{DecimalFormatter.format(salesRecord.totalProductsSold)}"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/text_16sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="3"
android:orientation="vertical"
android:textColor="#color/colorBlack">
<TextView
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:text="#string/sale_instance_total_value"
android:textColor="#color/colorBlack" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:text="#{MoneyFormatter.format(salesRecord.totalSellingPrice)}"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/text_16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/sales_instance_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:orientation="horizontal"
android:paddingLeft="#dimen/padding_xs"
android:paddingTop="#dimen/no_padding"
android:paddingRight="#dimen/padding_xs"
android:paddingBottom="#dimen/no_padding"
app:layout_constraintBottom_toBottomOf="parent">
<com.google.android.material.button.MaterialButton
android:id="#+id/sale_instance_quote_btn"
style="#style/BtnTextPrimarySm"
android:layout_width="0dp"
android:layout_height="38dp"
android:layout_gravity="start"
android:layout_margin="0dp"
android:layout_marginLeft="#dimen/margin_md"
android:layout_weight="1"
android:background="#drawable/xml_drawable_rectangle_border"
android:onClick="#{() ->eventHandler.saveAsQuote()}"
android:text="#string/sales_instance_quote_btn"
android:textAlignment="viewStart"
android:textColor="#android:color/white"
android:textSize="#dimen/text_14sp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/sale_instance_checkout_print_btn"
style="#style/BtnTextPrimarySm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="0dp"
android:layout_marginRight="#dimen/margin_md"
android:layout_weight="2"
android:background="#drawable/xml_drawable_rectangle_border"
android:onClick="#{() ->eventHandler.captureAmountPaidAndCompleteSales()}"
android:text="#string/sale_instance_proceed_to_checkout"
android:textAlignment="viewEnd"
android:textColor="#android:color/white"
android:textSize="#dimen/text_14sp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
This is my Adapter Code snippet:
public class SalesInvoicePagerAdapter extends FragmentStatePagerAdapter {
private SalesInvoiceViewModel salesInvoiceViewModel;
private List<SalesRecord> activeSalesRecords = new ArrayList<>();
#SuppressLint("UseSparseArrays")
public SalesInvoicePagerAdapter(final Fragment ownerFragment, SalesInvoiceViewModel salesViewModel) {
super(ownerFragment.getChildFragmentManager());
salesInvoiceViewModel = salesViewModel;
salesInvoiceViewModel.getActiveSalesRecords().observe(ownerFragment, new Observer<List<SalesRecord>>() {
#Override
public void onChanged(#Nullable List<SalesRecord> salesRecords) {
activeSalesRecords = salesRecords;
notifyDataSetChanged();
}
});
salesInvoiceViewModel.newSaleAlert.observe(ownerFragment, new Observer<SalesRecord>() {
#Override
public void onChanged(#Nullable SalesRecord salesRecord) {
Log.i("New Alert", String.valueOf(activeSalesRecords.size()));
activeSalesRecords.add(salesRecord);
notifyDataSetChanged();
}
});
salesInvoiceViewModel.saleClosedAlert.observe(ownerFragment, new Observer<Integer>() {
#Override
public void onChanged(Integer instancePosition) {
if(activeSalesRecords.size() > 0) {
activeSalesRecords.remove((int) instancePosition);
notifyDataSetChanged();
}
}
});
salesInvoiceViewModel.saleUpdatedAlert.observe(ownerFragment, new Observer<Pair<Integer, SalesRecord>>() {
#Override
public void onChanged(#Nullable Pair<Integer, SalesRecord> updatedSalesRecordPair) {
if(updatedSalesRecordPair != null) {
activeSalesRecords.remove((int) updatedSalesRecordPair.first);
activeSalesRecords.add(updatedSalesRecordPair.first, updatedSalesRecordPair.second);
notifyDataSetChanged();
}
}
});
}
#Override
public Fragment getItem(int i) {
Log.i("Set Current", String.valueOf(activeSalesRecords.size()));
if (activeSalesRecords.size() > 0) {
Fragment fragment = new SalesInvoiceInstanceFragment();
Bundle bundle = new Bundle();
bundle.putString(IntentExtras.SALES_INSTANCE_GUID, activeSalesRecords.get(i).getGuid());
bundle.putInt(IntentExtras.SALES_INSTANCE_FRAGMENT_POSITION, i);
fragment.setArguments(bundle);
return fragment;
}
return null;
}
#Override
public int getCount() {
return activeSalesRecords.size();
}
// #Nullable
#Override
public CharSequence getPageTitle(int position) {
Log.i("NAME: ", activeSalesRecords.get(position).getCustomerName());
Log.i("Page Title: ", activeSalesRecords.get(position).getCustomerName());
return activeSalesRecords.get(position).getCustomerName();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
This is my Fragment file code snippet:
public class SalesInvoiceFragment extends BaseFragment implements View.OnClickListener {
private static final String LOG_TAG = SalesInvoiceFragment.class.getName();
private FragmentSalesInvoiceBinding dataBinding;
private SalesInvoicePagerAdapter salesInvoicePagerAdapter;
private SalesInvoiceViewModel salesInvoiceViewModel;
private Activity parentActivity;
private AuthorityVerification authorityVerification;
#Inject
public SharedPreferencesRepository sharedPreferencesRepository;
#Inject
public SubscriptionPlanService subscriptionPlanService;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("Tab", "CHECKING...");
daggerComponent.inject(this);
dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_sales_invoice, container, false);
salesInvoiceViewModel = ViewModelProviders.of(this, new CostomaViewModelFactory((CostomaApplication) getActivity().getApplication())).get(SalesInvoiceViewModel.class);
authorityVerification = new AuthorityVerification(requireActivity());
parentActivity = getActivity();
return dataBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dataBinding.salesInvoiceFragmentTabLayout.setupWithViewPager(dataBinding.salesInvoiceFragmentViewPager);
salesInvoicePagerAdapter = new SalesInvoicePagerAdapter(this, salesInvoiceViewModel);
dataBinding.salesInvoiceFragmentViewPager.setAdapter(salesInvoicePagerAdapter);
Log.i("ONCRE", "START");
// for(int i=0; i < salesInvoicePagerAdapter.getCount(); i++) {
// Log.i("DeTitle", "PAGE TITLE");
// Log.i("DeTitle: ", salesInvoicePagerAdapter.getPageTitle(i).toString());
// //dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(i)));
// dataBinding.salesInvoiceFragmentTabLayout.getTabAt(i).setText(salesInvoicePagerAdapter.getPageTitle(i));
// }
if (!subscriptionPlanService.hasActiveSubscription()) {
dataBinding.startSaleBtn.setVisibility(View.GONE);
dataBinding.noActiveSubLabel.setVisibility(View.VISIBLE);
} else {
dataBinding.startSaleBtn.setVisibility(View.VISIBLE);
dataBinding.noActiveSubLabel.setVisibility(View.GONE);
dataBinding.startSaleBtn.setOnClickListener(this);
}
setDisplayedViewsForActiveSalesCount(0);
salesInvoiceViewModel.salesCountChangedAlert.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#NonNull Integer totalActiveSales) {
Log.i("Set Current", String.valueOf(salesInvoicePagerAdapter.getCount()));
if (totalActiveSales > 0) {
// dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(totalActiveSales - 1)));
for(int i=0; i < salesInvoicePagerAdapter.getCount(); i++) {
// Log.i("DeTitle", "PAGE TITLE");
// Log.i("DeTitle: ", salesInvoicePagerAdapter.getPageTitle(i).toString());
//dataBinding.salesInvoiceFragmentTabLayout.addTab(dataBinding.salesInvoiceFragmentTabLayout.newTab().setText(salesInvoicePagerAdapter.getPageTitle(i)));
dataBinding.salesInvoiceFragmentTabLayout.getTabAt(i).setText(salesInvoicePagerAdapter.getPageTitle(i));
}
dataBinding.salesInvoiceFragmentViewPager.setCurrentItem(totalActiveSales - 1);
// if (dataBinding.salesInvoiceFragmentTabLayout.getTabCount() == 2) {
// dataBinding.salesInvoiceFragmentTabLayout.setTabMode(TabLayout.MODE_FIXED);
// } else {
// dataBinding.salesInvoiceFragmentTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// }
}
setDisplayedViewsForActiveSalesCount(totalActiveSales);
setActivityTitle(totalActiveSales);
}
});
}
private void setDisplayedViewsForActiveSalesCount(int activeSalesCount) {
if (activeSalesCount > 0) {
dataBinding.salesInvoiceFragmentViewPager.setVisibility(View.VISIBLE);
dataBinding.salesInvoiceFragmentBlankSales.setVisibility(View.GONE);
} else {
dataBinding.salesInvoiceFragmentViewPager.setVisibility(View.GONE);
dataBinding.salesInvoiceFragmentBlankSales.setVisibility(View.VISIBLE);
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
salesInvoiceViewModel.commitActiveSales();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_sale_btn:
showAddSaleDialog();
break;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.sales_invoice_menu, menu);
boolean currentPdfGenerationValue = sharedPreferencesRepository.getBooleanValue(SharedPreferenceKeys.GENERATE_PDF_FOR_INVOICE);
boolean currentMerchantReceiptValue = sharedPreferencesRepository.getBooleanValue(SharedPreferenceKeys.PRINT_MERCHANT_COPY_FOR_RECEIPT);
menu.findItem(R.id.menu_item_invoice_pdf_generation_setting).setChecked(currentPdfGenerationValue);
menu.findItem(R.id.menu_item_invoice_merchant_copy_receipt).setChecked(currentMerchantReceiptValue);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_item_create_sales_instance:
if (!subscriptionPlanService.hasActiveSubscription()) {
ToastUtils.showLongToast(requireActivity(), "You do not have an active subscription!");
return true;
}
showAddSaleDialog();
break;
case R.id.menu_item_invoice_pdf_generation_setting:
boolean generateInvoice = !item.isChecked();
item.setChecked(generateInvoice);
sharedPreferencesRepository.saveBooleanValue(SharedPreferenceKeys.GENERATE_PDF_FOR_INVOICE, generateInvoice);
break;
case R.id.menu_item_invoice_merchant_copy_receipt:
boolean printMerchantReceipt = !item.isChecked();
item.setChecked(printMerchantReceipt);
sharedPreferencesRepository.saveBooleanValue(SharedPreferenceKeys.PRINT_MERCHANT_COPY_FOR_RECEIPT, printMerchantReceipt);
}
return true;
}
private void showAddSaleDialog() {
NewSaleDialog dialog = new NewSaleDialog();
dialog.setSalesInvoiceViewModel(salesInvoiceViewModel);
dialog.show(getFragmentManager(), NewSaleDialog.FRAGMENT_TAG);
}
private void setActivityTitle(int totalSalesCount) {
if (parentActivity != null) {
if (totalSalesCount > 0) {
parentActivity.setTitle(getString(R.string.menu_item_sales_invoice) + " - " + String.valueOf(totalSalesCount));
} else {
parentActivity.setTitle(R.string.menu_item_sales_invoice);
}
}
parentActivity.getActionBar();
}
}
I have tried everything i can to make it display well but is not working. I will welcome any assistance as i need to get this resolved now.
Thanks in advance....
I am working on a tasks app, for which I created a list view that shows list items consitsting of task names, their priority etc. The data given to the list view is from an sqlite database. I, however, am unable to add more than one item to the list. I have no idea why. I have created a method to do so, but it doesn't seem to work. I don't know if the error is due to the database or my method itself. Even debugging didn't help. Please note that I am using a list adapter since I am using a custom listview.
Code for Activity where list is shown :
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class TaskSummary extends AppCompatActivity {
ListView lvTaskList;
TextView tvBreak, tvBreakAfterEvery, txt1, txt2, text1, hmm;
TextView break_duration_mins;
ArrayList<SubtaskPartTwo> subtaskList = new ArrayList<>();
String subtname;
String pri;
String time;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_summary);
lvTaskList = findViewById(R.id.lvTaskList);
tvBreak = findViewById(R.id.tvBreak);
tvBreakAfterEvery = findViewById(R.id.tvBreakAfterEvery);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
break_duration_mins = findViewById(R.id.break_duration_mins);
text1 = findViewById(R.id.text1);
hmm = findViewById(R.id.hmm);
dbHelper = new DBHelper(this);
subtname = getIntent().getStringExtra("subtaskname");
pri = getIntent().getStringExtra("pri");
time = getIntent().getStringExtra("time");
// Using adapter for listview :
SubtaskDetailAdapter adapter = new SubtaskDetailAdapter(this, subtaskList);
lvTaskList.setAdapter(adapter);
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
double working_hours = getIntent().getIntExtra("working_hours", 1);
double working_minutes = getIntent().getIntExtra("working_minutes", 0);
double without_break_hours = getIntent().getIntExtra("without_break_hours", 1);
double without_break_minutes = getIntent().getIntExtra("without_break_minutes", 0);
double break_duration = getIntent().getIntExtra("break_duration", 20);
String a = working_hours + " h";
txt1.setText(a);
String b = working_minutes + " m";
break_duration_mins.setText(b);
String c = break_duration + " m";
txt2.setText(c);
//Mathematics
double g = working_hours * 100;
double h = g + working_minutes;
double i = h + break_duration;
double j = i / 60;
double p = (int) j;
double q = j - p;
double r = q * 60;
without_break_hours = p;
without_break_minutes = r;
String d = without_break_hours + " h";
String e = without_break_minutes + " m";
text1.setText(d);
hmm.setText(e);
}
}
Code for Adapter Class :
package com.example.taskmasterv3;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskDetailAdapter extends ArrayAdapter<SubtaskPartTwo> {
private final Context context;
private ArrayList<SubtaskPartTwo> values;
public boolean deleted;
public SubtaskDetailAdapter(Context context, ArrayList<SubtaskPartTwo> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.task_summary_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvlolitaskname);
ImageView ivPri = convertView.findViewById(R.id.ivloliPri);
ImageView ivTime = convertView.findViewById(R.id.ivloliTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).getPri() == "h")
{
ivPri.setImageResource(R.drawable.priority_high);
}
if (values.get(position).getPri() == "m")
{
ivPri.setImageResource(R.drawable.priority_med);
}
if (values.get(position).getPri() == "l")
{
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).getTime() == "more")
{
ivPri.setImageResource(R.drawable.time_symbol_more);
}
if (values.get(position).getPri() == "med")
{
ivPri.setImageResource(R.drawable.time_symbol_med);
}
if (values.get(position).getPri() == "less")
{
ivPri.setImageResource(R.drawable.time_symbol_less);
}
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(SubtaskPartTwo newSubTask){
ArrayList<SubtaskPartTwo> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
XML code for listview activity :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context=".TaskSummary">
<!-- hello -->
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/okay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<ListView
android:id="#+id/lvTaskList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Total Working Time (Including Breaks)"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/break_duration_mins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<!-- hello -->
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvWorktimeWithoutBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Work Time Before Each Break"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/hmm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreakAfterEvery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/roboto"
android:text="Break Duration"
android:textColor="#B8AEAE"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="#+id/lvTaskList"
app:layout_constraintEnd_toStartOf="#+id/lvTaskList"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:gravity="center_horizontal"
android:text="30 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="16dp"
android:text="Start" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
EDIT : Database Code
package com.example.taskmasterv3;
public class TaskInfo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
tvTaskName = findViewById(R.id.tvTaskName);
btnProceed = findViewById(R.id.btnProceed);
dbHelper = new DBHelper(this);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
{
tvTaskName.setClickable(false);
}
else
{
tvTaskName.setClickable(true);
}
btnSaveTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
}
});
tvTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
}
});
btnNewSubtask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
// THE DATABASE PART
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = dbHelper.getdata();
while(res != null && res.moveToNext()){
subtname = res.getString(0);
pri = res.getString(1);
time = res.getString(2);
}
if (etWorkingHours.getText().toString().isEmpty())
{
etWorkingHours.setText("0");
}
if (etWorkingMinutes.getText().toString().isEmpty())
{
etWorkingMinutes.setText("0");
}
if (etWorkinghrs.getText().toString().isEmpty())
{
etWorkinghrs.setText("0");
}
if (etWorkingMins.getText().toString().isEmpty())
{
etWorkingMins.setText("0");
}
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
{
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
}
else
{
if (working_hours != 0)
{
if (working_hours > without_break_hours)
{
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_hours == without_break_hours){
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("subtaskname", subtname);
intent.putExtra("pri", pri);
intent.putExtra("time", time);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours < without_break_hours){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours == 0){
if (without_break_hours == 0)
{
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("prihigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (without_break_hours != 0)
{
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
}
}
});
boolean delete = getIntent().getBooleanExtra("deleted", false);
if (delete){
}
}
}
}
}
The problem is that you're creating a new ArrayList while the adapter is left using the old one. That's why notifyDataSetChanged() doesn't work because the adapter's backing list has not changed.
To fix this, update the values list directly
public void addANewSubTask(SubtaskPartTwo newSubTask) {
this.values.add(newSubTask);
notifyDataSetChanged();
}
or, add() through the adapter itself.
public void addANewSubTask(SubtaskPartTwo newSubTask) {
add(newSubTask);
notifyDataSetChanged();
}
Even if I add one item, it shows 2 (both the same)
It seems you're adding the new element twice:
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
Just add via adapter only as it notifies as well. Check other places too for such duplicates.
lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference
and I don't know how to solve it
my class :
public class SimpleCommodityActivity extends BaseActivity {
#BindView(R.id.view_pager_tab)
SmartTabLayout view_pager_tab;
#BindView(R.id.viewpager)
ViewPager viewpager;
#BindView(R.id.img_back)
ImageView img_back;
#BindView(R.id.img_cart)
ImageView img_cart;
#BindView(R.id.txt_badge_shopping_cart)
TextView txt_badge_shopping_cart;
#BindView(R.id.txt_title_commodity)
TextView txt_title_commodity;
#BindView(R.id.layout_loading)
LinearLayout layout_loading;
#BindView(R.id.layout_error)
LinearLayout layout_error;
private String commodityId;
private boolean shouldExecuteOnResume;
#Override
protected int getViewId() {
return R.layout.activity_simple_commodity;
}
#Override
protected void initializeActivity() {
Intent intent = getIntent();
commodityId = intent.getStringExtra("id");
Log.e("id", commodityId);
getData();
getBadge();
shouldExecuteOnResume = false;
txt_title_commodity.setSelected(true);
}
#Override
protected void setupListeners() {
}
#Override
protected void isNetwork(boolean isNetwork) {
}
#Override
protected void onResume() {
super.onResume();
if (shouldExecuteOnResume) {
getData();
getBadge();
} else {
shouldExecuteOnResume = true;
}
}
private void getData() {
layout_loading.setVisibility(View.VISIBLE);
new PakhshiStore().getCommodity(commodityId).subscribe(new DisposableObserver<MainRes<CommodityRes>>() {
#Override
public void onNext(MainRes<CommodityRes> value) {
if (value.getResponseType() != 1) {
showMessage(value.getError());
} else {
CommodityRes commodityRes = value.getData();
if (commodityRes != null) {
//datas = commodityRes;
AppStore.setCommodityData(commodityRes);
setData(commodityRes);
//scrollview.setVisibility(View.VISIBLE);
} else {
layout_loading.setVisibility(View.GONE);
//scrollview.setVisibility(View.GONE);
layout_error.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onError(Throwable e) {
layout_loading.setVisibility(View.GONE);
//scrollview.setVisibility(View.GONE);
layout_error.setVisibility(View.VISIBLE);
}
#Override
public void onComplete() {
layout_loading.setVisibility(View.GONE);
}
});
}
private void setData(CommodityRes commodityRes) {
txt_title_commodity.setText(commodityRes.getTitle());
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(), FragmentPagerItems.with(this)
.add(R.string.buy_commodity, SimpleCommodityFrag.class)
.add(R.string.ommoditi_info, SimpleCommodityFrag.class)
.create());
viewpager.setAdapter(adapter);
view_pager_tab.setViewPager(viewpager);
}
public void getBadge() {
if (AppStore.getToken() != null) {
new PakhshiStore().getCartCount().subscribe(new DisposableObserver<MainRes<Integer>>() {
#Override
public void onNext(MainRes<Integer> value) {
if (value.getResponseType() != 1) {
showMessage(value.getError());
} else {
if (value.getData() != 0) {
txt_badge_shopping_cart.setVisibility(View.VISIBLE);
txt_badge_shopping_cart.setText(String.valueOf(value.getData()));
} else {
txt_badge_shopping_cart.setVisibility(View.GONE);
}
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
});
} else {
txt_badge_shopping_cart.setVisibility(View.GONE);
}
}
public void initSpinnerSize(final int position) {
if (AppStore.getCommodityData().getPackageTiers().size() != 0) {
Bundle bundle = new Bundle();
bundle.putInt("position",position);
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(), FragmentPagerItems.with(this)
.add(R.string.buy_commodity, SimpleCommodityFrag.class,bundle)
.add(R.string.ommoditi_info, SimpleCommodityFrag.class,bundle)
.create());
viewpager.setAdapter(adapter);
view_pager_tab.setViewPager(viewpager);
}
}
}
my ui:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layout_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:layoutDirection="rtl"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/layout_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary">
<ImageView
android:id="#+id/img_back"
android:layout_width="#dimen/_40sdp"
android:layout_height="#dimen/_40sdp"
android:layout_alignParentRight="true"
android:padding="#dimen/_15sdp"
android:rotation="180"
android:src="#drawable/ic_back"
android:tint="#color/white" />
<ImageView
android:id="#+id/img_cart"
android:layout_width="#dimen/_40sdp"
android:layout_height="#dimen/_40sdp"
android:layout_alignParentLeft="true"
android:padding="#dimen/_10sdp"
android:src="#drawable/ic_buy"
android:tint="#color/white" />
<TextView
android:id="#+id/txt_badge_shopping_cart"
android:layout_width="#dimen/_15sdp"
android:layout_height="#dimen/_15sdp"
android:layout_alignRight="#id/img_cart"
android:layout_marginTop="#dimen/_5sdp"
android:background="#drawable/red_circle"
android:gravity="center"
android:text="1"
android:textColor="#color/white"
android:textSize="#dimen/font_size_xxsmall" />
<ImageView
android:id="#+id/img_share"
android:layout_width="#dimen/_40sdp"
android:layout_height="#dimen/_40sdp"
android:layout_toRightOf="#id/img_cart"
android:padding="#dimen/_10sdp"
android:src="#drawable/ic_share"
android:tint="#color/white"
android:visibility="gone" />
<TextView
android:id="#+id/txt_title_commodity"
android:layout_width="wrap_content"
android:layout_height="#dimen/_40sdp"
android:layout_marginLeft="#dimen/_3sdp"
android:layout_marginRight="#dimen/_3sdp"
android:layout_toLeftOf="#id/img_back"
android:layout_toRightOf="#id/img_cart"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:gravity="center"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textColor="#color/white"
android:textSize="#dimen/font_size_small" />
</RelativeLayout>
<com.ogaclejapan.smarttablayout.SmartTabLayout
android:id="#+id/view_pager_tab"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="#dimen/_40sdp"
android:background="#color/colorAccent"
app:stl_clickable="true"
app:stl_customTabTextLayoutId="#layout/custom_tab"
app:stl_customTabTextViewId="#id/txt"
app:stl_defaultTabBackground="?attr/selectableItemBackground"
app:stl_defaultTabTextAllCaps="true"
app:stl_defaultTabTextColor="#color/colorAccent"
app:stl_defaultTabTextHorizontalPadding="16dp"
app:stl_defaultTabTextMinWidth="0dp"
app:stl_defaultTabTextSize="#dimen/font_size_xlarge"
app:stl_distributeEvenly="false"
app:stl_dividerColor="#color/transparent"
app:stl_dividerThickness="#dimen/_1sdp"
app:stl_drawDecorationAfterTab="false"
app:stl_indicatorColor="#color/black_30"
app:stl_indicatorCornerRadius="#dimen/_18sdp"
app:stl_indicatorGravity="center"
app:stl_indicatorInterpolation="smart"
app:stl_indicatorThickness="#dimen/_30sdp"
app:stl_titleOffset="24dp"
app:stl_underlineThickness="1dp" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/layout_title" />
<LinearLayout
android:id="#+id/layout_loading"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_color"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:layout_width="#dimen/_100sdp"
android:layout_height="#dimen/_100sdp"
android:alpha="0.3"
android:src="#drawable/logo" />
<com.github.ybq.android.spinkit.SpinKitView
style="#style/SpinKitView.Large.ThreeBounce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:SpinKit_Color="#color/gray_hint" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_error"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_color"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:layout_width="#dimen/_80sdp"
android:layout_height="#dimen/_80sdp"
android:alpha="0.5"
android:src="#drawable/ic_warning" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_10sdp"
android:gravity="center"
android:text="#string/error_commodity_not_found"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/font_size_normal" />
</LinearLayout>
</RelativeLayout>
error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference
i really dont know what is the error
i remove fragment adapter, again this error show
log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pakhshi.app.pakhshi, PID: 28599
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1623)
at android.view.View.measure(View.java:23297)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:23297)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
at android.view.View.measure(View.java:23297)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23297)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:23297)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23297)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:899)
at android.view.View.measure(View.java:23297)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2837)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1874)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2129)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1743)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7773)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:658)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
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:6949)
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)
There was already someone else with a similar problem, but I couldn't understand the anwser and I wasn't able to add a coment to receive
more informations. So please help me!
This is my main JavaClass
package ch.androidnewcomer.muckenfangfinal;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Date;
import java.util.Random;
public class GameActivity extends Activity implements View.OnClickListener, Runnable{
public static final int DELAY_MILLIS = 1000;
public static final int ZEITSCHEIBEN = 60;
public float massstab;
private int runde;
private int punkte;
private int muecken;
private int gefangeneMuecken;
private int zeit;
private static final long HOECHSTALTER_MS = 2000;
private Random zufallsgenerator = new Random();
private ViewGroup spielbereich;
private Handler handler = new Handler();
private boolean spielLaeuft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
massstab = getResources().getDisplayMetrics().density;
spielbereich = (ViewGroup)findViewById(R.id.spielbereich);
spielStarten();
}
private void spielStarten() {
spielLaeuft = true;
runde = 0;
punkte = 0;
starteRunde();
}
private void bildschirmAktualisieren() {
TextView tvPunkte = (TextView)findViewById(R.id.points);
tvPunkte.setText(Integer.toString(punkte));
TextView tvRunde = (TextView)findViewById(R.id.round);
tvRunde.setText(Integer.toString(runde));
TextView tvTreffer = (TextView)findViewById(R.id.hits);
tvTreffer.setText(Integer.toString(gefangeneMuecken));
TextView tvZeit = (TextView)findViewById(R.id.time);
tvZeit.setText(Integer.toString(zeit/(1000/DELAY_MILLIS)));
FrameLayout flTreffer = (FrameLayout)findViewById(R.id.bar_hits);
FrameLayout flZeit = (FrameLayout)findViewById(R.id.bar_time);
ViewGroup.LayoutParams lpTreffer = flTreffer.getLayoutParams();
lpTreffer.width = Math.round( massstab * 300 * Math.min( gefangeneMuecken,muecken) / muecken);
ViewGroup.LayoutParams lpZeit = flZeit.getLayoutParams();
lpZeit.width = Math.round( massstab * zeit *300 / ZEITSCHEIBEN);
}
private void zeitHerunterzaehlen() {
zeit = zeit - 1;
if(zeit % (1000/DELAY_MILLIS) == 0) {
float zufallszahl = zufallsgenerator.nextFloat();
double wahrscheinlichkeit = muecken * 1.5;
if (wahrscheinlichkeit > 1) {
eineMueckeAnzeigen();
if (zufallszahl < wahrscheinlichkeit - 1) {
eineMueckeAnzeigen();
}
} else {
if (zufallszahl < wahrscheinlichkeit) {
eineMueckeAnzeigen();
}
}
}
mueckenVerschwinden();
bildschirmAktualisieren();
if(!pruefeSpielende()) {
if(!pruefeRundenende()) {
handler.postDelayed(this, DELAY_MILLIS);
}
}
}
private boolean pruefeRundenende() {
if (gefangeneMuecken >= muecken) {
starteRunde();
return true;
}
return false;
}
private void starteRunde() {
runde = runde +1;
muecken = runde *10;
gefangeneMuecken = 0;
zeit = ZEITSCHEIBEN;
bildschirmAktualisieren();
handler.postDelayed(this, DELAY_MILLIS);
}
private boolean pruefeSpielende() {
if(zeit == 0 && gefangeneMuecken < muecken) {
gameOver();
return true;
}
return false;
}
private void gameOver() {
Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.gameover);
dialog.show();
spielLaeuft = false;
}
private void mueckenVerschwinden() {
int nummer=0;
while (nummer < spielbereich.getChildCount()) {
ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
Date geburtsdatum = (Date) muecke.getTag(R.id.geburtsdatum);
long alter = (new Date()).getTime() - geburtsdatum.getTime();
if(alter > HOECHSTALTER_MS) {
spielbereich.removeView(muecke);
}else {
nummer++;
}
}
}
private void eineMueckeAnzeigen() {
int breite = spielbereich.getWidth();
int hoehe = spielbereich.getHeight();
int muecke_breite = (int) Math.round(massstab* 60);
int muecke_hoehe = (int) Math.round(massstab*49);
int links = zufallsgenerator.nextInt(breite - muecke_breite);
int oben = zufallsgenerator.nextInt(hoehe - muecke_hoehe);
ImageView muecke = new ImageView(this);
muecke.setImageResource(R.drawable.muecke);
muecke.setOnClickListener(this);
muecke.setTag(R.id.geburtsdatum, new Date());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(muecke_breite, muecke_hoehe);
params.leftMargin = links;
params.topMargin = oben;
params.gravity = Gravity.TOP + Gravity.LEFT;
spielbereich.addView(muecke,params);
}
#Override
public void onClick(View muecke) {
gefangeneMuecken++;
punkte += 100;
bildschirmAktualisieren();
spielbereich.removeView(muecke);
}
#Override
public void run() {
zeitHerunterzaehlen();
}
}
The FrameLayout, where I'm trying to display the 'muecke - mosquito' is called 'spielbereich' meaning as much as playground.
And this is the LogCat
12-28 16:19:26.449 5302-5302/ch.androidnewcomer.muckenfangfinal E/AndroidRuntime: FATAL EXCEPTION: main
Process: ch.androidnewcomer.muckenfangfinal, PID: 5302
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ImageView
at ch.androidnewcomer.muckenfangfinal.GameActivity.mueckenVerschwinden(GameActivity.java:168)
at ch.androidnewcomer.muckenfangfinal.GameActivity.zeitHerunterzaehlen(GameActivity.java:104)
at ch.androidnewcomer.muckenfangfinal.GameActivity.run(GameActivity.java:218)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
And here is my xmlLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ch.androidnewcomer.muckenfangfinal.GameActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="61dp">
<TextView
android:id="#+id/round"
android:layout_width="136dp"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="21sp"
android:textStyle="bold" />
<TextView
android:id="#+id/points"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="TextView"
android:textSize="21sp"
android:textStyle="bold" />
</FrameLayout>
<FrameLayout
android:id="#+id/spielbereich"
android:layout_width="match_parent"
android:layout_height="332dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/hintergrundlinearlayout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="bottom"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="35dp">
<FrameLayout
android:id="#+id/bar_hits"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:background="#android:color/holo_orange_dark">
</FrameLayout>
<TextView
android:id="#+id/hits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="#string/hits"
android:textSize="15sp"
android:textStyle="bold" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/bar_time"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:background="#android:color/holo_orange_light">
</FrameLayout>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="#string/time" />
</FrameLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
if you need anymore informations, please tell me.
It would be great if you could tell me exactely how I have to change the code, because I'm really a beginner.
you are casting a linear layout to imageview.You are trying to get a child of frame layout which is a linear layout but you casted it to a image view.thats why this error was happened. casting it to the linearlayout will solve this error.
This is your layout with id spielbereich
<FrameLayout
android:id="#+id/spielbereich"
android:layout_width="match_parent"
android:layout_height="332dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/hintergrundlinearlayout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="bottom"
android:orientation="vertical">
And this is the code where you are trying to cast the childView into an ImageView
private void mueckenVerschwinden() {
int nummer=0;
while (nummer < spielbereich.getChildCount()) {
ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
Date geburtsdatum = (Date) muecke.getTag(R.id.geburtsdatum);
long alter = (new Date()).getTime() - geburtsdatum.getTime();
if(alter > HOECHSTALTER_MS) {
spielbereich.removeView(muecke);
}else {
nummer++;
}
}
}
ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
This line is giving you a cast error because nummer = 0 at this point and spielbereich.getChildAt(0) is a LinearLayout
I'm working on my first android app to independently control 20 RGB LED's and I'm just working on the basic GUI structure at the moment. My first pane works almost perfectly (the setPressed method isn't doing what I had hoped that it would and that class isn't optimized yet) but my second pane isn't showing the objects that I created. Here's my code for my first and second panes:
activity_controller.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Controller"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/row1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/buttonBarStyle">
<Button
android:id="#+id/button0"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button0"
android:onClick="toggleButton0"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button1"
android:onClick="toggleButton1"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button2"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button2"
android:onClick="toggleButton2"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button3"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button3"
android:onClick="toggleButton3"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button4"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button4"
android:onClick="toggleButton4"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button5"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button5"
android:onClick="toggleButton5"
style="?android:attr/buttonStyleToggle"/>
</LinearLayout>
<LinearLayout
android:id="#+id/row2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/row1"
style="?android:attr/buttonBarStyle">
<Button
android:id="#+id/button6"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button6"
android:onClick="toggleButton6"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/buttonAll"
android:layout_weight="4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/buttonAll"
android:onClick="selectAll"/>
<Button
android:id="#+id/button7"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button7"
android:onClick="toggleButton7"
style="?android:attr/buttonStyleToggle"/>
</LinearLayout>
<LinearLayout
android:id="#+id/row3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/row2"
style="?android:attr/buttonBarStyle">
<Button
android:id="#+id/button8"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button8"
android:onClick="toggleButton8"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/buttonSet"
android:layout_weight="4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/buttonSet"
android:onClick="setColor"/>
<Button
android:id="#+id/button9"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button9"
android:onClick="toggleButton9"
style="?android:attr/buttonStyleToggle"/>
</LinearLayout>
<LinearLayout
android:id="#+id/row4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/row3"
style="?android:attr/buttonBarStyle">
<Button
android:id="#+id/button10"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button10"
android:onClick="toggleButton10"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/buttonOff"
android:layout_weight="4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/buttonOff"
android:onClick="turnOff"/>
<Button
android:id="#+id/button11"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button11"
android:onClick="toggleButton11"
style="?android:attr/buttonStyleToggle"/>
</LinearLayout>
<LinearLayout
android:id="#+id/row5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/row4"
style="?android:attr/buttonBarStyle">
<Button
android:id="#+id/button12"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button12"
android:onClick="toggleButton12"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/buttonBuiltIn"
android:layout_weight="4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/buttonBuiltIn"
android:onClick="builtIns"/>
<Button
android:id="#+id/button13"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button13"
android:onClick="toggleButton13"
style="?android:attr/buttonStyleToggle"/>
</LinearLayout>
<LinearLayout
android:id="#+id/row6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/row5"
style="?android:attr/buttonBarStyle">
<Button
android:id="#+id/button14"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button14"
android:onClick="toggleButton14"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button15"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button15"
android:onClick="toggleButton15"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button16"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button16"
android:onClick="toggleButton16"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button17"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button17"
android:onClick="toggleButton17"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button18"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button18"
android:onClick="toggleButton18"
style="?android:attr/buttonStyleToggle"/>
<Button
android:id="#+id/button19"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button19"
android:onClick="toggleButton19"
style="?android:attr/buttonStyleToggle"/>
</LinearLayout>
</RelativeLayout>
Controller.java:
package com.example.lightcontrol;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Controller extends Activity {
public final static String SELECTED_BUTTONS = "com.mycompany.myfirstapp.BUTTONS";
public final static boolean[] selectedButtons = new boolean[20];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controller);
int i = 0;
while (i < 20) {
selectedButtons[i]=false;
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_controller, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void toggleButton0(View view) {
if (!selectedButtons[0]) {
view.setPressed(true);
selectedButtons[0] = true;
} else {
view.setPressed(false);
selectedButtons[0] = false;
}
}
public void toggleButton1(View view) {
if (!selectedButtons[1]) {
view.setPressed(true);
selectedButtons[1] = true;
} else {
view.setPressed(false);
selectedButtons[1] = false;
}
}
public void toggleButton2(View view) {
if (!selectedButtons[2]) {
view.setPressed(true);
selectedButtons[2] = true;
} else {
view.setPressed(false);
selectedButtons[2] = false;
}
}
public void toggleButton3(View view) {
if (!selectedButtons[3]) {
view.setPressed(true);
selectedButtons[3] = true;
} else {
view.setPressed(false);
selectedButtons[3] = false;
}
}
public void toggleButton4(View view) {
if (!selectedButtons[4]) {
view.setPressed(true);
selectedButtons[4] = true;
} else {
view.setPressed(false);
selectedButtons[4] = false;
}
}
public void toggleButton5(View view) {
if (!selectedButtons[5]) {
view.setPressed(true);
selectedButtons[5] = true;
} else {
view.setPressed(false);
selectedButtons[5] = false;
}
}
public void toggleButton6(View view) {
if (!selectedButtons[6]) {
view.setPressed(true);
selectedButtons[6] = true;
} else {
view.setPressed(false);
selectedButtons[6] = false;
}
}
public void toggleButton7(View view) {
if (!selectedButtons[7]) {
view.setPressed(true);
selectedButtons[7] = true;
} else {
view.setPressed(false);
selectedButtons[7] = false;
}
}
public void toggleButton8(View view) {
if (!selectedButtons[8]) {
view.setPressed(true);
selectedButtons[8] = true;
} else {
view.setPressed(false);
selectedButtons[8] = false;
}
}
public void toggleButton9(View view) {
if (!selectedButtons[9]) {
view.setPressed(true);
selectedButtons[9] = true;
} else {
view.setPressed(false);
selectedButtons[9] = false;
}
}
public void toggleButton10(View view) {
if (!selectedButtons[10]) {
view.setPressed(true);
selectedButtons[10] = true;
} else {
view.setPressed(false);
selectedButtons[10] = false;
}
}
public void toggleButton11(View view) {
if (!selectedButtons[11]) {
view.setPressed(true);
selectedButtons[11] = true;
} else {
view.setPressed(false);
selectedButtons[11] = false;
}
}
public void toggleButton12(View view) {
if (!selectedButtons[12]) {
view.setPressed(true);
selectedButtons[12] = true;
} else {
view.setPressed(false);
selectedButtons[12] = false;
}
}
public void toggleButton13(View view) {
if (!selectedButtons[13]) {
view.setPressed(true);
selectedButtons[13] = true;
} else {
view.setPressed(false);
selectedButtons[13] = false;
}
}
public void toggleButton14(View view) {
if (!selectedButtons[14]) {
view.setPressed(true);
selectedButtons[14] = true;
} else {
view.setPressed(false);
selectedButtons[14] = false;
}
}
public void toggleButton15(View view) {
if (!selectedButtons[15]) {
view.setPressed(true);
selectedButtons[15] = true;
} else {
view.setPressed(false);
selectedButtons[15] = false;
}
}
public void toggleButton16(View view) {
if (!selectedButtons[16]) {
view.setPressed(true);
selectedButtons[16] = true;
} else {
view.setPressed(false);
selectedButtons[16] = false;
}
}
public void toggleButton17(View view) {
if (!selectedButtons[17]) {
view.setPressed(true);
selectedButtons[17] = true;
} else {
view.setPressed(false);
selectedButtons[17] = false;
}
}
public void toggleButton18(View view) {
if (!selectedButtons[18]) {
view.setPressed(true);
selectedButtons[18] = true;
} else {
view.setPressed(false);
selectedButtons[18] = false;
}
}
public void toggleButton19(View view) {
if (!selectedButtons[19]) {
view.setPressed(true);
selectedButtons[19] = true;
} else {
view.setPressed(false);
selectedButtons[19] = false;
}
}
/** Called when the user clicks the Send button */
public void setColor(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(SELECTED_BUTTONS, selectedButtons);
startActivity(intent);
}
}
activity_display_message.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".DisplayMessageActivity"
android:orientation="horizontal">
<SeekBar
android:id="#+id/redSlider"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="25dp"
android:max="255"/>
<SeekBar
android:id="#+id/greenSlider"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_below="#+id/redSlider"
android:max="255"/>
<SeekBar
android:id="#+id/blueSlider"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_below="#+id/greenSlider"
android:max="255"/>
<TextView
android:id="#+id/colorBox"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
DisplayMessageActivity.java:
package com.example.lightcontrol;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.ArrayList;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
boolean[] buttons = intent.getBooleanArrayExtra(Controller.SELECTED_BUTTONS);
// Create the text view
String message = "";
int i = 0;
for(boolean currButton: buttons) {
if(currButton) {
message += Integer.toString(i) + ",";
}
i++;
}
final SeekBar redSlider = (SeekBar) findViewById(R.id.redSlider);
final SeekBar blueSlider = (SeekBar) findViewById(R.id.blueSlider);
final SeekBar greenSlider = (SeekBar) findViewById(R.id.greenSlider);
ArrayList<SeekBar> seekArray = new ArrayList<SeekBar>();
seekArray.add(redSlider);
seekArray.add(blueSlider);
seekArray.add(greenSlider);
for (SeekBar slider : seekArray) {
slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
#Override
public void onProgressChanged(SeekBar slider, int progresValue, boolean fromUser) {
updateColorBox();
}
#Override
public void onStartTrackingTouch(SeekBar slider) {
}
#Override
public void onStopTrackingTouch(SeekBar slider) {
}
});
}
}
#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);
}
public void updateColorBox() {
SeekBar redSlider = (SeekBar) findViewById(R.id.redSlider);
SeekBar blueSlider = (SeekBar) findViewById(R.id.blueSlider);
SeekBar greenSlider = (SeekBar) findViewById(R.id.greenSlider);
TextView colorBox = (TextView) findViewById(R.id.colorBox);
int redProgress = redSlider.getProgress();
int blueProgress = blueSlider.getProgress();
int greenProgress = greenSlider.getProgress();
String hex = String.format("%02x%02x%02x", redProgress, greenProgress, blueProgress);
colorBox.setBackgroundColor(Color.parseColor(hex));
}
}
Does anyone know why that DisplayMessageActivity pane is blank? It isn't blank in my xml Design preview tab...Thanks!
You are missing a call to setContentView() in onCreate()