mercredi 28 mars 2018

How to save checkbox State in other activity

In this MainActivity.java I am trying to call a checkbox which is in other layout. Purpose: I want to save the state of the CheckBox even when the activity is closed it should the state of the CheckBox. If someone of you have different method for adding the CheckBox in the ListView please add that code. I am trying to make a todo list app.

package com.vivekraja07.vivekatgt;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Paint;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; 

import com.vivekraja07.vivekatgt.db.Task;
import com.vivekraja07.vivekatgt.db.TaskHelper;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
private TaskHelper mHelper;
private ListView mTaskListView;

private ArrayAdapter<String> mAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mHelper = new TaskHelper(this);

    CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox);
    boolean checked = PreferenceManager.getDefaultSharedPreferences(this)
            .getBoolean("checkBox", false);
    checkBox1.setChecked(checked);
    mTaskListView = (ListView) findViewById(R.id.list_todo);
    mTaskListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    updateUI();
}
public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();
    switch(view.getId()) {
        case R.id.checkBox:
            PreferenceManager.getDefaultSharedPreferences(this).edit()
                    .putBoolean("checkBox", checked).commit();
            break;
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_add_task:
            final EditText taskEditText = new EditText(this);
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("New Task")
                    .setMessage("Add a new task")
                    .setView(taskEditText)
                    .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogue, int which) {
                            String task = String.valueOf(taskEditText.getText());
                            if (task.length() == 0) {
                                return;
                            }
                            SQLiteDatabase db = mHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put(Task.TaskEntry.COL_TASK_TITLE, task);
                            db.insertWithOnConflict(Task.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                            db.close();
                            updateUI();
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create();
            dialog.show();
            return true;
        case R.id.menu_item_delete:
            Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
        case R.id.menu_item_select:
            Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
        default:
            return super.onOptionsItemSelected(item);

    }
}

private void updateUI() {
    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(Task.TaskEntry.TABLE,
            new String[] {Task.TaskEntry.COL_TASK_TITLE}, null, null, null, null, null);

    while (cursor.moveToNext()) {
        int index = cursor.getColumnIndex(Task.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(index));
    }

    if (mAdapter == null) {
        mAdapter = new ArrayAdapter<String>(this, R.layout.item_todo, R.id.task_title, taskList);
        mTaskListView.setAdapter(mAdapter);

    } else {
        mAdapter.clear();
        mAdapter.addAll(taskList);
        mAdapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
}

public void deleteTask(View view) {
    View parent = (View) view.getParent();
    TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
    String task = String.valueOf(taskTextView.getText());
    SQLiteDatabase db = mHelper.getWritableDatabase();
    taskTextView.setPaintFlags(taskTextView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    db.close();
    updateUI();

}
}

here is the code for item_todo.xml from where the Checkbox is called.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_gravity="center_vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/task_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/checkBox"
    android:layout_alignParentEnd="true"
    android:layout_marginEnd="15dp"
    android:text="Hi"
    android:textSize="20sp" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:text="CheckBox"
    android:onClick="deleteTask"/>

</RelativeLayout>




Aucun commentaire:

Enregistrer un commentaire