Android simple program - SeekBar not being created - java

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

Related

Combine use of OnClickListener and OnLong Click Listener

Actually I created a pdf viewer and i jus want to create a longclicklistener to open my new activity and as u can see here
Screenshot
And there is already a click listener assigned with this button and i also want to combine longclicklistener so when i long click that button then automatically launch my second activity
public void actionButtonClick(View view) {
if (pageCount == 0) {
Toast.makeText(getApplicationContext(), getString(R.string.no_selected_pdf), Toast.LENGTH_LONG).show();
return;
}
final BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
dialog.setContentView(R.layout.bottom_sheet);
dialog.setCanceledOnTouchOutside(true);
NumberPicker numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
if (numberPicker != null) {
numberPicker.setMaxValue(pageCount);
numberPicker.setValue(pdfView.getCurrentPage() + 1);
numberPicker.setOnValueChangedListener((picker, oldVal, newVal) -> {
pdfView.jumpTo(newVal - 1, true);
});
}
dialog.show();
}
public void openButtonClick(View view) {
launchPicker();
}
private void startAnimation(int state) {
actionLayout.animate()
.translationY(state == 0 ? actionLayout.getHeight() : 0)
.alpha(state == 0 ? 0 : 1.0f)
.setDuration(300).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
menu.findItem(R.id.hide_or_show_button).setChecked(state != 1);
super.onAnimationEnd(animation);
}
});
}
private void hideOrShowActionButton() {
if (actionLayout.getAlpha() == 1.0)
startAnimation(0);
else
startAnimation(1);
}
private void showSnackBar(#NonNull String msg, boolean isError) {
Snackbar snackbar = Snackbar
.make(findViewById(R.id.main_layout), msg, Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()),
isError ? R.color.err_color : R.color.main_color));
snackbar.setTextColor(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()), R.color.white));
snackbar.show();
}
#Override
public void loadComplete(int nbPages) {
pageCount = nbPages;
warningLayout.setVisibility(View.GONE);
PdfDocument.Meta meta = pdfView.getDocumentMeta();
detailsMap.clear();
detailsMap.add(meta.getTitle());
detailsMap.add(meta.getAuthor());
detailsMap.add(meta.getSubject());
detailsMap.add(meta.getKeywords());
detailsMap.add(meta.getCreator());
detailsMap.add(meta.getProducer());
detailsMap.add(dateFormatter(meta.getCreationDate()));
detailsMap.add(dateFormatter(meta.getModDate()));
}
private String dateFormatter(String data) {
if (!data.isEmpty()) {
String date = data.substring(2);
String y = date.substring(0, 4);
String m = date.substring(4, 6);
String d = date.substring(6, 8);
return y + "/" + m + "/" + d;
} else {
return data;
}
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber.setText(String.valueOf(page + 1));
}
#Override
public void onPageError(int page, Throwable t) {
showSnackBar(getString(R.string.page_not_loaded) + page, true);
}
}
Xml File
This Is Xml File if needed
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".MainActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdf_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
app:layout_anchor="#+id/warning"
app:layout_anchorGravity="center">
<Button
android:id="#+id/button"
android:layout_width="42dp"
android:layout_height="11dp"
android:layout_below="#id/textView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="518dp"
android:text="open activity 2" />
</com.github.barteksc.pdfviewer.PDFView>
<LinearLayout
android:id="#+id/warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/no_selected_pdf"
android:textColor="#color/secondary_text_color"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_open_pdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:focusable="true"
android:onClick="openButtonClick"
android:padding="10dp"
android:text="#string/click_to_select_pdf"
android:textColor="#color/main_color"
android:textSize="18sp" />
</LinearLayout>
<FrameLayout
android:id="#+id/action_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:contentDescription="#string/action_btn_description"
android:onClick="actionButtonClick"
app:backgroundTint="#color/main_color"
app:borderWidth="0dp"
app:tint="#color/white" />
<TextView
android:id="#+id/tv_page_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:elevation="16dp"
android:text="x"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white"
android:textSize="16sp" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
There is an onClick and onLongClick listener for each view :
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
FloatingActionButton actionButton = findViewById(R.id.actionButton);
actionButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// start your activity from here
return true;
}
});
}

Tab item title in tablayout displaying not well arranged

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....

Migrate my normal RecyclerView to RecyclerView Databinding

I have issue when I change some value, example delete comment in my recyclerview it's doesn't update automatically, Google says use LiveData DataBinding RecyclerView, is anyone ever to make RecyclerView LiveData databinding please help me out
This is my MainActivity.java
public class TabDetailHotActivity extends AppCompatActivity {
//GLOBAL
public static MainActivity mainActivity_;
TextView TVGameDate;
TextView TVGameTitle;
ImageView IMGGameImage;
TextView TVSeenCounter;
TextView TVCommentCounter;
TextView TVLikeCounter;
ImageView IMGSeenView;
ImageView IMGCommentView;
ImageView IMGLikeView;
ImageView ICONHotTrendingNewsSaving;
//EVENT BUS
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredMessageTrending event) {
getMessageTrendingMainActivity(event.SendMessageUrutan, event.SendTotalThread, event.SendMessageIDComment, event.SendMessageComment, event.SendMessageEntryTime, event.SendMessageisEdited, event.SendMessageEditTime);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredMessageTrendingLogin event) {
getMessageTrendingLoginMainActivity(event.SendMessageUrutan, event.SendTotalThread, event.SendMessageIDComment, event.SendMessageComment, event.SendMessageEntryTime, event.SendMessageisEdited, event.SendMessageEditTime, event.SendMessageEditable);
}
public void getMessageTrendingMainActivity(int ReceivedMessageUrutan, int ReceivedTotalThread, String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime){
Toast.makeText(this, "Load Comment Not Login :( >> ReceivedMessageComment:"+ReceivedMessageComment+", Toast.LENGTH_LONG).show();
}
public void getMessageTrendingLoginMainActivity(int ReceivedMessageUrutan, int ReceivedTotalThread, String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime, int ReceivedMessageEditable){
Toast.makeText(this, "Load Comment Login :) >> ReceivedMessageComment:" + ReceivedMessageComment, Toast.LENGTH_LONG).show();
createDummyDataComment(ReceivedMessageUrutan, ReceivedTotalThread, ReceivedMessageIDComment, ReceivedMessageComment, ReceivedMessageEntryTime, ReceivedMessageEdited, ReceivedMessageEditTime, ReceivedMessageEditable);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitydetail_tabhot);
ToolbarX = findViewById(R.id.toolbar);
setSupportActionBar(ToolbarX);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("");
Intent intent = getIntent();
mDummyIDContent = intent.getStringExtra("DummyIDContentPKG");
mDummyTitle = intent.getStringExtra("DummyTitlePKG");
mDummyPublishTime = intent.getStringExtra("DummyPublishTimePKG");
mDummyImageOriPKG = intent.getStringExtra("DummyImageOriPKG");
mDummyShortDescription = intent.getStringExtra("DummyShortDescriptionPKG");
mDummySeen = intent.getIntExtra("DummySeenPKG", 0);
mDummyComment = intent.getIntExtra("DummyCommentPKG", 0);
mDummyLike = intent.getIntExtra("DummyLikePKG", 0);
mDummyisComment = intent.getIntExtra("DummyisCommentPKG", 0);
mDummyisLike = intent.getIntExtra("DummyisLikePKG", 0);
mDummyisBookmark = intent.getIntExtra("DummyisBookmarkPKG", 0);
date_Behaviour = findViewById(R.id.date_behavior);
IMGGameImage = findViewById(R.id.backdrop);
TVGameDate = findViewById(R.id.date);
TVGameTitle = findViewById(R.id.title);
TVSeenCounter = findViewById(R.id.TV_SeenCounter);
TVCommentCounter = findViewById(R.id.TV_CommentCounter);
TVLikeCounter = findViewById(R.id.TV_LikeCounter);
RequestOptions requestOptions = new RequestOptions();
requestOptions.error(UtilsNews.getRandomDrawbleColor());
TVGameDate.setText(mDummyPublishTime);
TVGameTitle.setText(mDummyTitle);
TVSeenCounter.setText(String.valueOf(mDummySeen));
TVCommentCounter.setText(String.valueOf(mDummyComment));
TVLikeCounter.setText(String.valueOf(mDummyLike));
Glide.with(this)
.load(mDummyImageOriPKG)
.apply(requestOptions)
.transition(DrawableTransitionOptions.withCrossFade())
.into(IMGGameImage);
/* initWebView(mUrl);*/
ImageButton BTNSendMessageDetailHotTrendingNews = findViewById(R.id.BTN_SendMessageDetailHotTrendingNews);
final TextView ETSendMessageDetailHotTrendingNews = findViewById(R.id.ET_SendMessageDetailHotTrendingNews);
BTNSendMessageDetailHotTrendingNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String TheMessage = ETSendMessageDetailHotTrendingNews.getText().toString();
if(!TheMessage.equals("")){
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("SendComment", mDummyIDContent, TheMessage);
}
}else{
Toast.makeText(TabDetailHotActivity.this, "You don't send anything", Toast.LENGTH_SHORT).show();
}
ETSendMessageDetailHotTrendingNews.setText("");
}
});
//
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("LoadComment", mDummyIDContent, "");
}
}
private void initWebView(String url) {
WebView webView = findViewById(R.id.webView);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url);
}
ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments = new ArrayList<ModelDetailHotTrendingNewsComment>();
AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener listenerDetailHotTrendingNewsComment;
public void createDummyDataComment(int ReceivedMessageUrutan, int ReceivedTotalThread, final String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime, int ReceivedMessageEditable) {
modelDetailHotTrendingNewsComments.add(new ModelDetailHotTrendingNewsComment(ReceivedMessageIDComment,ReceivedMessageComment,ReceivedMessageEntryTime,ReceivedMessageEditable,ReceivedMessageEditTime));
if(ReceivedMessageUrutan == ReceivedTotalThread-1){
listenerDetailHotTrendingNewsComment = new AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener(){
#Override
public void onRowDetailHotTrendingNewsContainerClick(View view, int position) {
}
#Override
public void onRowMessageEditClick(View view, int position) {
}
#Override
public void onRowMessageDeleteClick(View view, final int position) {
String[] YOURCHOICE = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(TabDetailHotActivity.this);
builder.setTitle("Do you want to delete this comment?");
builder.setItems(YOURCHOICE, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Toast.makeText(TabDetailHotActivity.this, "Deleted Successfully!", Toast.LENGTH_SHORT).show();
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("DeleteComment", modelDetailHotTrendingNewsComments.get(position).getIdcontent(), "");
}
}else if(which == 1){
Toast.makeText(TabDetailHotActivity.this, "You don't delete the Comment", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
}
};
RecyclerView RVDetailHotTrendingNewsComment = findViewById(R.id.RVDetail_HotTrendingNewsComment);
RVDetailHotTrendingNewsComment.setHasFixedSize(true);
AdapterDetailHotTrendingNewsComment adapterDetailHotTrendingNewsComment = new AdapterDetailHotTrendingNewsComment(this, modelDetailHotTrendingNewsComments, listenerDetailHotTrendingNewsComment);
RVDetailHotTrendingNewsComment.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RVDetailHotTrendingNewsComment.setAdapter(adapterDetailHotTrendingNewsComment);
//Optimized
RVDetailHotTrendingNewsComment.setHasFixedSize(true);
RVDetailHotTrendingNewsComment.setItemViewCacheSize(20);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
supportFinishAfterTransition();
}
//EVENTBUS
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
}
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true"
android:background="#color/darkgrey"
tools:context=".TabDetailHotActivity">
<androidx.core.widget.NestedScrollView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:background="#color/darkgrey"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:background="#color/darkgrey"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:textColor="#color/colorWhite"
android:textStyle="bold"
android:fontFamily="sans-serif-light"
android:textSize="19sp"
android:text="Title of News"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_below="#id/title"
android:textColor="#color/colorWhite"
android:layout_marginTop="10dp"
android:maxLines="1"
android:drawablePadding="10dp"
android:singleLine="true"
android:ellipsize="end"
android:text="a time ago" />
<ImageView
android:id="#+id/IMG_SeenView"
android:src="#drawable/watch"
android:layout_marginLeft="8dp"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/TV_SeenCounter"
android:paddingTop="2dp"
android:layout_marginTop="1dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_SeenCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/IMG_CommentView"
android:text="999"
android:layout_marginTop="2dp"
android:textSize="14dp"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
<ImageView
android:id="#+id/IMG_CommentView"
android:src="#drawable/comment_off"
android:layout_toLeftOf="#id/TV_CommentCounter"
android:layout_alignParentBottom="true"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_CommentCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/IMG_LikeView"
android:layout_marginTop="2dp"
android:text="999"
android:textSize="14dp"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
<ImageView
android:id="#+id/IMG_LikeView"
android:src="#drawable/heart_off"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/TV_LikeCounter"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_LikeCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_alignParentEnd="true"
android:text="999"
android:textSize="14dp"
android:layout_alignParentBottom="true"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkgrey">
<ProgressBar
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/progress_bar"
android:layout_marginTop="50dp"
android:layout_marginBottom="70dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/RL_Bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#FFFFFF"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/ET_SendMessageDetailHotTrendingNews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:hint="Type a comment..."
android:layout_toLeftOf="#id/BTN_SendMessageDetailHotTrendingNews"
android:layout_centerVertical="true"/>
<ImageButton
android:id="#+id/BTN_SendMessageDetailHotTrendingNews"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_send_black_24dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkgrey">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/RVDetail_HotTrendingNewsComment"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<FrameLayout
android:id="#+id/date_behavior"
app:layout_anchor="#+id/appbar"
app:behavior_autoHide="true"
android:adjustViewBounds="true"
app:layout_anchorGravity="right|end|bottom"
android:clickable="false"
android:background="#drawable/round_white"
android:layout_width="wrap_content"
android:padding="5dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="410dp"
android:layout_height="wrap_content"
tools:ignore="UnusedAttribute">
<ImageView
android:src="#drawable/ic_date"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<TextView
android:textColor="#606060"
android:id="#+id/date"
android:layout_marginLeft="27dp"
android:layout_marginRight="10dp"
android:text="01 January 1990"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is AdapterComment.java
public class AdapterDetailHotTrendingNewsComment extends RecyclerView.Adapter {
private Context mContext;
private ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments;
private AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener;
public AdapterDetailHotTrendingNewsComment(Context mContext, ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments, AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener) {
this.mContext = mContext;
this.modelDetailHotTrendingNewsComments = modelDetailHotTrendingNewsComments;
this.mListener = mListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemdetail_hottrendingnewscomment, null);
return new DetailHotTrendingNewsViewHolder(v, mListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final DetailHotTrendingNewsViewHolder detailHotTrendingNewsViewHolder = (DetailHotTrendingNewsViewHolder) holder;
final ModelDetailHotTrendingNewsComment modelDetailHotTrendingNewsCommentX = modelDetailHotTrendingNewsComments.get(position);
Glide.with(mContext).load(modelDetailHotTrendingNewsCommentX.getMessageimage()).into(detailHotTrendingNewsViewHolder.IMGMessageImage);
detailHotTrendingNewsViewHolder.TVMessageUsername.setText(modelDetailHotTrendingNewsCommentX.getMessageusername());
detailHotTrendingNewsViewHolder.TVMessageDescription.setText(modelDetailHotTrendingNewsCommentX.getMessagedescription());
detailHotTrendingNewsViewHolder.TVMessageDate.setText(modelDetailHotTrendingNewsCommentX.getMessagedate());
}
#Override
public int getItemCount() {
int itemCount = modelDetailHotTrendingNewsComments.size();
return itemCount;
}
public class DetailHotTrendingNewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView IMGMessageImage;
TextView TVMessageUsername;
TextView TVMessageDescription;
TextView TVMessageDate;
private RelativeLayout ROWDetailHotTrendingNewsContainer;
TextView TVMessageEdit;
ImageView IMGMessageDelete;
private AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener;
public DetailHotTrendingNewsViewHolder(View itemView, AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener listener) {
super(itemView);
IMGMessageImage = itemView.findViewById(R.id.IMG_MessageImage);
TVMessageUsername = itemView.findViewById(R.id.TV_MessageUsername);
TVMessageDescription = itemView.findViewById(R.id.TV_MessageDescription);
TVMessageDate = itemView.findViewById(R.id.TV_MessageDate);
ROWDetailHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_DetailHotTrendingNewsContainer);
TVMessageEdit = itemView.findViewById(R.id.TV_MessageEdit);
IMGMessageDelete = itemView.findViewById(R.id.IMG_MessageDelete);
mListener = listener;
ROWDetailHotTrendingNewsContainer.setOnClickListener(this);
TVMessageEdit.setOnClickListener(this);
IMGMessageDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ROW_DetailHotTrendingNewsContainer:
mListener.onRowDetailHotTrendingNewsContainerClick(ROWDetailHotTrendingNewsContainer, getAdapterPosition());
break;
case R.id.TV_MessageEdit:
mListener.onRowMessageEditClick(TVMessageEdit, getAdapterPosition());
break;
case R.id.IMG_MessageDelete:
mListener.onRowMessageDeleteClick(IMGMessageDelete, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowDetailHotTrendingNewsContainerClick(View view, int position);
void onRowMessageEditClick(View view, int position);
void onRowMessageDeleteClick(View view, int position);
}
}
This is ModelComment.java
public class ModelDetailHotTrendingNewsComment {
private String idcontent;
private String messageimage;
private String messageusername;
private String messagedescription;
private String messagedate;
private int messageisedit;
private String messageedittime;
private String messageedit;
private String messagedelete;
public ModelDetailHotTrendingNewsComment(String idcontent, String messagedescription, String messagedate, int messageisedit, String messageedittime) {
this.idcontent = idcontent;
this.messagedescription = messagedescription;
this.messagedate = messagedate;
this.messageisedit = messageisedit;
this.messageedittime = messageedittime;
}
public String getIdcontent() {
return idcontent;
}
public void setIdcontent(String idcontent) {
this.idcontent = idcontent;
}
public String getMessageimage() {
return messageimage;
}
public void setMessageimage(String messageimage) {
this.messageimage = messageimage;
}
public String getMessageusername() {
return messageusername;
}
public void setMessageusername(String messageusername) {
this.messageusername = messageusername;
}
public String getMessagedescription() {
return messagedescription;
}
public void setMessagedescription(String messagedescription) {
this.messagedescription = messagedescription;
}
public String getMessagedate() {
return messagedate;
}
public void setMessagedate(String messagedate) {
this.messagedate = messagedate;
}
public String getMessageedittime() {
return messageedittime;
}
public void setMessageedittime(String messageedittime) {
this.messageedittime = messageedittime;
}
public String getMessageedit() {
return messageedit;
}
public void setMessageedit(String messageedit) {
this.messageedit = messageedit;
}
public String getMessagedelete() {
return messagedelete;
}
public void setMessagedelete(String messagedelete) {
this.messagedelete = messagedelete;
}
}

How to save the old state of a checkbox?

I want to save the old state of checkbox With checkbox I want to update my data in database. When user changes the activity I lose his checked checkbox and when he again comes to that activity then every checkbox is unchecked and when he click to save with new values it will not saved because I set date as primary key in database. If I update the data with new values I lost my old data....
CheckBoxActivity.java
package com.example.shakeelmughal.assanislam;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NamazCounterActivity extends AppCompatActivity {
DatabaseHelper mydb;
CheckBox cb1,cb2,cb3,cb4,cb5;
Button B1,B2,B3;
int vcb1=0,vcb2=0,vcb3=0,vcb4=0,vcb5=0,vet=0;
Date date = new Date();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namaz_counter);
mydb = new DatabaseHelper(this);
SharedPreferences settings = getSharedPreferences("mysettings", 0);
SharedPreferences.Editor editor = settings.edit();
cb1 = findViewById(R.id.namaz1);
cb2 = findViewById(R.id.namaz2);
cb3 = findViewById(R.id.namaz3);
cb4 = findViewById(R.id.namaz4);
cb5 = findViewById(R.id.namaz5);
B1 = findViewById(R.id.result);
B2 = (Button) findViewById(R.id.dateee);
B3 = findViewById(R.id.sumr);
c_date();
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertingData();
}
});
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor cr = mydb.getAllData();
if(cr.getCount() == 0)
{
showData("Error","No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (cr.moveToNext())
{
buffer.append("ID: "+cr.getString(0)+ "\n");
buffer.append("Fajar: "+cr.getString(1)+ "\n");
buffer.append("Zohr: "+cr.getString(2)+ "\n");
buffer.append("Asr: "+cr.getString(3)+ "\n");
buffer.append("Magrib: "+cr.getString(2)+ "\n");
buffer.append("Isha: "+cr.getString(3)+ "\n");
}
showData("Data",buffer.toString());
}
});
//home button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}}
//function for going back to previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
public void InsertingData()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
cb2.setChecked(true);
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
cb3.setChecked(true);
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
cb4.setChecked(true);
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
cb5.setChecked(true);
}
else
{
vcb5 = 0;
}
boolean result = mydb.InsertData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(result == true)
{
Toast.makeText(NamazCounterActivity.this, "Prayer Saved",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(NamazCounterActivity.this, "Some Error", Toast.LENGTH_LONG).show();
}
}
public void Updateingdata()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean res = mydb.UpdateData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(res == true)
{
Toast.makeText(NamazCounterActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(NamazCounterActivity.this,"Data Not Updated",Toast.LENGTH_SHORT).show();
}
}
//for date ()
public void c_date()
{
date.setTime(System.currentTimeMillis()); //set to current time
B2.setText(date.toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEEEEEE, MMM dd, yyyy");
B2.setText(dateFormat.format(date));
}
public void showData(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
Its XML file
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.shakeelmughal.assanislam.NamazCounterActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView2">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/namaz1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="47dp"
android:layout_marginStart="47dp"
android:layout_marginTop="50dp"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:button="#null"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz1"
android:layout_alignStart="#+id/namaz1"
android:layout_below="#+id/namaz1"
android:layout_marginTop="12dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz3"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz2"
android:layout_alignStart="#+id/namaz2"
android:layout_below="#+id/namaz2"
android:layout_marginTop="19dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz4"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz3"
android:layout_alignStart="#+id/namaz3"
android:layout_below="#+id/namaz3"
android:layout_marginTop="19dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz5"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz4"
android:layout_alignStart="#+id/namaz4"
android:layout_below="#+id/namaz4"
android:layout_marginTop="11dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<TextView
android:id="#+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/namaz1"
android:layout_alignBottom="#+id/namaz1"
android:layout_marginLeft="41dp"
android:layout_marginStart="41dp"
android:layout_toEndOf="#+id/result"
android:layout_toRightOf="#+id/result"
android:text="نمازِ فجر"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView20"
android:layout_alignRight="#+id/textView20"
android:layout_alignTop="#+id/namaz2"
android:layout_marginTop="14dp"
android:text=" نمازِ ظہر / جمعہ"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView21"
android:layout_alignRight="#+id/textView21"
android:layout_alignTop="#+id/namaz3"
android:layout_marginTop="11dp"
android:text="نمازِ عصر"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/namaz4"
android:layout_alignBottom="#+id/namaz4"
android:layout_alignEnd="#+id/textView21"
android:layout_alignRight="#+id/textView21"
android:text="نمازِ مغرب"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView23"
android:layout_alignRight="#+id/textView23"
android:layout_alignTop="#+id/namaz5"
android:layout_marginTop="12dp"
android:text="نمازِ عشاء"
android:textColor="#000"
android:textSize="20sp"/>
<Button
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView24"
android:layout_centerHorizontal="true"
android:text="Save" />
<Button
android:id="#+id/dateee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView20"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/sumr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/result"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:text="View Summery" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
There could be many ways to do that, some of them are :
1. By using a File
2. By using shared preferences
I will recommend that latter one, a great implementation could be found by
Save CheckBox State to SharedPreferences File in Android

What should i do to move to another activity when only special conditions are met

I am making a quiz app. I want the exit page to be displayed when the next button is pressed after last question has been answered. I have a activity_questions.xml and a activity_exit.xml. The xml for activity_questions.xml is :
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.crystal.questions">
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:fontFamily="sans-serif-thin"
android:padding="10dp"
android:text=""
android:textColor="#440027"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/edit2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/text3"
android:layout_margin="30dp"
android:background="#9775AA"
android:hint="Answer"
android:inputType="text"
android:padding="10dp"
android:textSize="20dip" />
<LinearLayout
android:id="#+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edit2"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/answer"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="1"
android:onClick="onAnswerClick"
android:padding="2dp"
android:text="Okay" />
<Button
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="1"
android:onClick="onHintClick"
android:padding="2dp"
android:text="Hint" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="5dp"
android:orientation="vertical"
android:layout_marginTop="26dp"
android:layout_below="#+id/ll"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:id="#+id/tickcross"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/ll"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:src="#drawable/wierdtick" />
<TextView
android:id="#+id/correctornot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tickcross"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Correct!"
android:textColor="#440027"
android:textSize="30dp" />
<Button
android:id="#+id/nextbutton"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Next"
android:onClick="onNextClick"
/>
</LinearLayout>
</RelativeLayout>
And the java is:
package com.example.android.crystal;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class questions extends AppCompatActivity {
Random r = new Random();
private boolean done;
private int QuestionNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
findViewById(R.id.tickcross).setVisibility(View.INVISIBLE);
findViewById(R.id.correctornot).setVisibility(View.INVISIBLE);
findViewById(R.id.nextbutton).setVisibility(View.INVISIBLE);
String[] questions = getResources().getStringArray(R.array.Questions);
TextView t = (TextView) findViewById(R.id.text3);
t.setText(questions[QuestionNo]);
}
public void onFinishClick(View view){
Intent intent = new Intent(this, exit.class);
startActivity(intent);
}
public static void hideKeyboardFrom(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void answersubmitted() {
findViewById(R.id.tickcross).setVisibility(View.VISIBLE);
TranslateAnimation animation = new TranslateAnimation(0, 0, 2000, 0);
animation.setDuration(1000);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
findViewById(R.id.tickcross).startAnimation(animation);
findViewById(R.id.correctornot).setVisibility(View.VISIBLE);
findViewById(R.id.nextbutton).setVisibility(View.VISIBLE);
}
public void onHintClick(View view) {
String[] hints = getResources().getStringArray(R.array.Hints);
Toast toasty = Toast.makeText(getApplicationContext(), hints[QuestionNo], Toast.LENGTH_SHORT);
toasty.show();
}
public void onAnswerClick(View view) {
if (done == false) {
hideKeyboardFrom(this);
String answer = ((EditText) findViewById(R.id.edit2)).getText().toString();
String[] answers = getResources().getStringArray(R.array.Answers);
String correctAnswer = answers[QuestionNo];
correctAnswer = correctAnswer.toUpperCase();
answer = answer.toUpperCase();
if (answer.equals(correctAnswer)) {
TextView t = (TextView) findViewById(R.id.correctornot);
t.setText("CORRECT!");
ImageView i = (ImageView) findViewById(R.id.tickcross);
i.setImageDrawable(getDrawable(R.drawable.wierdtick));
answersubmitted();
} else {
TextView t = (TextView) findViewById(R.id.correctornot);
t.setText("Correct Answer: " + correctAnswer);
ImageView i = (ImageView) findViewById(R.id.tickcross);
i.setImageDrawable(getDrawable(R.drawable.weirdcross));
answersubmitted();
}
done = true;
}
}
public void onNextClick(View view){
if (done){
String[] questions = getResources().getStringArray(R.array.Questions);
if (QuestionNo < (questions.length - 1)) {
QuestionNo += 1;
TextView t = (TextView) findViewById(R.id.text3);
t.setText(questions[QuestionNo]);
findViewById(R.id.tickcross).setVisibility(View.INVISIBLE);
findViewById(R.id.correctornot).setVisibility(View.INVISIBLE);
findViewById(R.id.nextbutton).setVisibility(View.INVISIBLE);
EditText et = (EditText) findViewById(R.id.edit2);
et.setText("");
done = false;
}
else {
onFinishClick();
}
}
}
}
But the onFinishClick() gives an error
Thanks in advance for your help
What should i do to move to another activity when only special conditions are met
Basically, an if-statement and an Intent.
Raw code with no variables added:
if(condition(s)){
Intent i = new Intent(this, TargetActivity.class);
//Put arguments into the intent if you need them...
startActivity(i);
}
You can put it in a thread, in an onClickListener, anywhere and any way you want to execute the code.
As to the error you are receiving, I cannot help you with that until you supply the stacktrace from Logcat
You can do like this:
mNextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mQuestionCount < questionList.size()){
// set next question
} else {
// call finish
}
}
});

Categories

Resources