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
Related
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.
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
}
}
});
I have ten questions from my succession. I want to do,
1- an answer to a problem (only one button should be clicked)
2- When I go to the next question, see the answer I clicked radiobutton the previous
JAVA Class
public class Sinavsorulari extends Activity {
TextView tv_soruNum, tv_soru;
RadioButton rb_a, rb_b, rb_c, rb_d;
Button btn_sonrakiSoru,btn_oncekiSoru , btn_kaydet;
String url = "http://192.168.56.2/soru_cekme.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sinav_sorulari);
tv_soruNum=(TextView)findViewById(R.id.tv_soruNum);
tv_soru=(TextView)findViewById(R.id.tv_soru);
btn_oncekiSoru=(Button)findViewById(R.id.btn_oncekiSoru);
btn_sonrakiSoru=(Button)findViewById(R.id.btn_sonrakiSoru);
btn_kaydet = (Button) findViewById(R.id.btn_kaydet);
rb_a = (RadioButton) findViewById(R.id.rb_cevapa);
rb_b = (RadioButton) findViewById(R.id.rb_cevapb);
rb_c = (RadioButton) findViewById(R.id.rb_cevapc);
rb_d = (RadioButton) findViewById(R.id.rb_cevapd);
btn_oncekiSoru.setEnabled(false);
btn_kaydet.setEnabled(false);
btn_kaydet.setVisibility(View.INVISIBLE);
new HttpAsyncTask().execute(url);
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(final String result) {
final String[] cevaplar = new String[20];
final JSONArray[] jsonarray = {null};
final String[] soru1 = {null};
final String[] id_soru1 = {null};
final int[] y = {0};
final String[] cvp = new String[24];
try {
final int[] t = { 0 };
jsonarray[0] = new JSONArray(result);
final JSONObject obj1 = jsonarray[0].getJSONObject(t[0]);
id_soru1[0] = obj1.getString("id_soru");
soru1[0] = obj1.getString("baslik_soru");
tv_soruNum.setText(id_soru1[0]);
tv_soru.setText(soru1[0]);
for (int k = 0; k < 4; k++) {
cvp[k] = obj1.getString("icerik_cevap");
if(k == 0){
rb_a.setText(cvp[k]);
}else if(k == 1) {
rb_b.setText(cvp[k]);
}else if(k == 2){
rb_c.setText(cvp[k]);
}else if(k == 3){
rb_d.setText(cvp[k]);
}
}
if ( rb_a.isSelected()){
cvp[y[0]]="A";
}
else if( rb_b.isSelected()){
cvp[y[0]] ="B";
}
else if( rb_c.isSelected()){
cvp[y[0]]="C";
}
else if( rb_d.isSelected()){
cvp[y[0]]="D";
}
else {
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
}
final JSONArray finalJsonarray = jsonarray[0];
btn_sonrakiSoru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
t[0]+=4;
y[0] +=1;
btn_oncekiSoru.setEnabled(true);
JSONObject obj2 = finalJsonarray.getJSONObject(t[0]);
id_soru1[0] = obj2.getString("id_soru");
soru1[0] = obj2.getString("baslik_soru");
tv_soruNum.setText(id_soru1[0]);
tv_soru.setText(soru1[0]);
for (int k = 0; k < 4; k++) {
cvp[k] = obj2.getString("icerik_cevap");
if (k == 0) {
rb_a.setText(cvp[k]);
} else if (k == 1) {
rb_b.setText(cvp[k]);
} else if (k == 2) {
rb_c.setText(cvp[k]);
} else if (k == 3) {
rb_d.setText(cvp[k]);
}
}
if ( rb_a.isSelected()){
cvp[y[0]]="A";
}
else if( rb_b.isSelected()){
cvp[y[0]] ="B";
}
else if( rb_c.isSelected()){
cvp[y[0]]="C";
}
else if( rb_d.isSelected()){
cvp[y[0]]="D";
}
else {
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
}
int j=t[0] + 4;
if(j == finalJsonarray.length()){
btn_sonrakiSoru.setEnabled(false);
btn_sonrakiSoru.setVisibility(View.INVISIBLE);
btn_kaydet.setVisibility(View.VISIBLE);
btn_kaydet.setEnabled(true);
btn_kaydet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_oncekiSoru.setEnabled(false);
}
});
}
}catch (JSONException e) {
e.printStackTrace();
}
}
});
btn_oncekiSoru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t[0]-=4;
JSONObject obj2 = null;
try {
obj2 = finalJsonarray.getJSONObject(t[0]);
id_soru1[0] = obj2.getString("id_soru");
soru1[0] = obj2.getString("baslik_soru");
tv_soruNum.setText(id_soru1[0]);
tv_soru.setText(soru1[0]);
for (int k = 0; k <4; k++) {
cvp[k] = obj2.getString("icerik_cevap");
if (k == 0) {
rb_a.setText(cvp[k]);
} else if (k == 1) {
rb_b.setText(cvp[k]);
} else if (k == 2) {
rb_c.setText(cvp[k]);
} else if (k == 3) {
rb_d.setText(cvp[k]);
}
}
if ( rb_a.isSelected()){
cvp[y[0]]="A";
}
else if( rb_b.isSelected()){
cvp[y[0]] ="B";
}
else if( rb_c.isSelected()){
cvp[y[0]]="C";
}
else if( rb_d.isSelected()){
cvp[y[0]]="D";
}
else {
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
}
if( t[0] == 0 ){
btn_oncekiSoru.setEnabled(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
and my .xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/tv_soruNum"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/tv_soru"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/tv_soruNum"
android:layout_toEndOf="#+id/tv_soruNum"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp" />
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_below="#+id/tv_soru"
android:id="#+id/view"
android:layout_marginBottom="25dp"
android:layout_marginTop="35dp"
android:background="#000000" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapa"
android:layout_below="#+id/view"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapb"
android:layout_below="#+id/rb_cevapa"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapc"
android:layout_below="#+id/rb_cevapb"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="68dp"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapd"
android:layout_below="#+id/rb_cevapc"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="68dp"
android:checked="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Oncekı"
android:id="#+id/btn_oncekiSoru"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_sonrakiSoru"
android:layout_alignTop="#+id/btn_oncekiSoru"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="Sonraki" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kaydet"
android:id="#+id/btn_kaydet"
android:layout_alignTop="#+id/btn_sonrakiSoru"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Thanks for help me..
For the RadioButton problem you need to add a RadioGroup like the example below.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
For displaying the selected RadioButton you could use a Toast.
Use RadioGroup refer here
Example
activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="How do you like the quality of our tutorials?"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Excellent " />
<RadioButton
android:id="#+id/radioButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Satisfactory" />
<RadioButton
android:id="#+id/radioButton3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Below Average" />
</RadioGroup>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clearBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClear"
android:text="Clear " />
<Button
android:id="#+id/submitBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onSubmit"
android:text="Submit" />
</LinearLayout>
</LinearLayout>
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Initialize Radio Group and attach click handler */
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.clearCheck();
/* Attach CheckedChangeListener to radio group */
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb = (RadioButton) group.findViewById(checkedId);
if(null!=rb && checkedId > -1){
Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void onClear(View v) {
/* Clears all selected radio buttons to default */
radioGroup.clearCheck();
}
public void onSubmit(View v) {
RadioButton rb = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
}
This may helps you.
For your problem, you should use a RadioGroup.
A RadioGroup is basically a group of RadioButtons such that only one can be selected at time. Although you can customise it to allow multiple selections, but by default it allows you to select one RadioButton at a time.
So form a RadioGroup that contains 4 RadioButtons for 4 options.
radioGroup = (RadioGroup) findViewById(R.id.myRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
switch(checkedId){
case R.id.rb_option1: //1st option selected
break;
case R.id.rb_option2: //2nd option selected
break;
case R.id.rb_option3: //3rd option selected
break;
case R.id.rb_option4: //4th option selected
break;
}
}
});
Hope this helps :)
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()
I tried everything but unable to disable that save button. i wrote it at the end of my onCreate.
Actually i wanted if user edits some notes and selects category from spinner it will automatically get enabled and i achieved it.
But i want that first when user is on this page button should be disabled. When user dose his work it will enable.
But how should i disable this save button.
Here is my OfflinePBDetails.java class
package passbookManager;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import logs.TraceLog;
import mainApplication.*;
import forbes.mPassbook.R;
import databaseClasses.DBAccountStatement;
import databaseClasses.DBCategoryMaster;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class OfflinePBDetails extends Activity implements OnItemSelectedListener
{
TextView tvDate;
TextView tvAmount;
TextView tvBalance;
TextView tvParticular;
TextView tvTitleAmount;
EditText etNotes;
Spinner spinnerCategory;
Button btnBack;
Button btnSave;
String file_Path;
Properties properties_config;
long sessionTimeout;
String passTransId;
String passDate;
String passParticular;
String passDebitCreditIndicator;
String passAmount;
String passTransString;
String passBalance;
String passFlag;
String transId;
String notes;
int countDBRows;
int countDBColumns;
String dbSubCategory;
String dbNotes;
String selectedCategory;
String[][] tableCategory ;
ArrayList<String> categoryIncome;
ArrayList<String> categoryExpense;
ArrayAdapter<String> adapterSelect;
DBCategoryMaster dbCMaster;
DBAccountStatement dbStatement;
TraceLog tc = new TraceLog();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ActionBar bar=getActionBar();
bar.hide();
setContentView(R.layout.activity_offline_pbdetails);
dbCMaster = new DBCategoryMaster(this);
dbStatement = new DBAccountStatement(this);
file_Path=Environment.getExternalStorageDirectory()+ "/Android/data/forbes.mPassbook/";
readConfigFileDetails();
if( Build.VERSION.SDK_INT >= 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try
{
tvDate = (TextView)findViewById(R.id.tv_getDate);
tvParticular = (TextView)findViewById(R.id.tv_getParticular);
tvAmount = (TextView)findViewById(R.id.tv_getAmount);
tvTitleAmount = (TextView)findViewById(R.id.tv_titleAmount);
tvBalance = (TextView)findViewById(R.id.tv_getBalance);
spinnerCategory = (Spinner)findViewById(R.id.spn_selectCategory);
etNotes = (EditText)findViewById(R.id.et_getNotes);
btnBack = (Button)findViewById(R.id.btnBack);
btnSave = (Button)findViewById(R.id.btnSave);
Intent intent = getIntent();
passTransId = intent.getExtras().getString("TransactionId");
passDate = intent.getExtras().getString("Date");
passParticular = intent.getExtras().getString("Particular");
passAmount = intent.getExtras().getString("Amount");
passTransString = intent.getExtras().getString("TransString");
passDebitCreditIndicator = intent.getExtras().getString("Indicator");
passBalance = intent.getExtras().getString("Balance");
passFlag = intent.getExtras().getString("FilterFlag");
tvDate.setText(passDate);
tvParticular.setText(passParticular);
tvTitleAmount.setText(passTransString);
if(tvTitleAmount.getText().equals("Withdrawal Amount"))
{
tvAmount.setTextColor(Color.RED);
}
else
{
tvAmount.setTextColor(Color.rgb(48,128,20));
}
String trimAmount = passAmount.trim();
String trimBalance = passBalance.trim();
tvAmount.setText(trimAmount);
tvBalance.setText(trimBalance);
etNotes.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0)
{
btnSave.setEnabled(true);
resetDisconnectTimer();
// Toast.makeText(getApplicationContext(), "After Typing", Toast.LENGTH_LONG).show();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
// Toast.makeText(getApplicationContext(), "Before Typing", Toast.LENGTH_LONG).show();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// Toast.makeText(getApplicationContext(), "Typing", Toast.LENGTH_LONG).show();
}
});
btnBack.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(passFlag.equalsIgnoreCase("OfflinePB"))
{
Intent i = new Intent(OfflinePBDetails.this,OfflinePB.class);
i.putExtra("filterFlag","notes");/**********Code to go back to DisplayFilter Page***************************/
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("notes"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","notes");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("transfer"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","transfer");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("cheque"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","cheque");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
});
btnSave.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
btnSave.setEnabled(false);
transId = passTransId;
notes = etNotes.getText().toString();
// if(spinnerCategory.length()==0)
// {
// spinnerCategory.setError("Please Enter mPIN ");
// mPin.requestFocus();
// }
// else
// if(notes.trim().length()==0)
// {
// etNotes.setError("Please Add Your Notes ");
// etNotes.setText(null);
// etNotes.requestFocus();
// }
if(dbStatement.updatePassbook(transId, selectedCategory, notes))
{
Toast.makeText(getApplicationContext(), "Data Updated Successfully", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "notes : " + notes, Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java Save.setOnClickListener():- "+e.toString());
}
}
});
dbGetCategoryList();
btnSave.setEnabled(false);
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java onCreate():- "+e.toString());
}
}
public void dbGetCategoryList()
{
int element;
try
{
Cursor rs = dbCMaster.getData();
countDBRows = rs.getCount();
countDBColumns = rs.getColumnCount();
tableCategory = new String[countDBRows][countDBColumns];
rs.moveToFirst();
for(element = 0; element < countDBRows; element++)
{
tableCategory[element][0] = rs.getString(0); // subCategory
tableCategory[element][1] = rs.getString(1); // Category
tableCategory[element][2] = rs.getString(2); // transType
rs.moveToNext();
// String finalData = tableCategory[element][0]+ " " + tableCategory[element][1]
// + " " + tableCategory[element][2];
// Toast.makeText(getApplicationContext(), "finalData : " + finalData, Toast.LENGTH_SHORT).show();
}
rs.close();
showCategoryList();
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java dbGetCategoryList():- "+e.toString());
}
}
public void showCategoryList()
{
int i = 0;
int j = 0;
int element;
String transType;
categoryIncome = new ArrayList<String>();
categoryExpense = new ArrayList<String>();
// categoryIncome = new String[2];
// categoryExpense = new String[3];
try
{
for(element = 0; element < countDBRows; element++)
{
transType = tableCategory[element][2];
// Toast.makeText(getApplicationContext(), "transType : " + transType, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), "passDebitCreditIndicator : " + passDebitCreditIndicator, Toast.LENGTH_SHORT).show();
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
if(passDebitCreditIndicator.equalsIgnoreCase(transType))
{
if(tableCategory[element][0].equalsIgnoreCase("Others-E"))
{
categoryExpense.add("Others");
}
else
{
categoryExpense.add(tableCategory[element][0]);
}
// Toast.makeText(getApplicationContext(), "categoryExpense : " + categoryExpense, Toast.LENGTH_SHORT).show();
i++;
}
}
else
{
if(passDebitCreditIndicator.equalsIgnoreCase(transType))
{
if(tableCategory[element][0].equalsIgnoreCase("Others-I"))
{
categoryIncome.add("Others");
}
else
{
categoryIncome.add(tableCategory[element][0]);
}
// Toast.makeText(getApplicationContext(), "categoryIncome : " + categoryIncome, Toast.LENGTH_SHORT).show();
j++;
}
}
}
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
adapterSelect = new ArrayAdapter<String>(this, R.layout.spinner_pb_details,categoryExpense);
// adapterSelect = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryExpense);
}
else
{
adapterSelect = new ArrayAdapter<String>(this, R.layout.spinner_pb_details,categoryIncome);
// adapterSelect = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryIncome);
}
adapterSelect.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(adapterSelect);
spinnerCategory.setOnItemSelectedListener(this);
checkDBData();
if(dbSubCategory.equalsIgnoreCase("Others-E") || dbSubCategory.equalsIgnoreCase("Others-I"))
{
dbSubCategory = "Others";
}
ArrayAdapter myAdap = (ArrayAdapter) spinnerCategory.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(dbSubCategory);
//set the default according to value
spinnerCategory.setSelection(spinnerPosition);
etNotes.setText(dbNotes);
// to disable save button after notes is filled with note from db and item is selected from item listner
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java showCategoryList():- "+e.toString());
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// try
// {
spinnerCategory.setSelection(position);
selectedCategory = (String) spinnerCategory.getSelectedItem();
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
if(selectedCategory.equalsIgnoreCase("Others"))
{
selectedCategory = "Others-E";
}
// else
// {
// selectedCategory = selectedCategory;
// }
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_SHORT).show();
}
else
{
if(selectedCategory.equalsIgnoreCase("Others"))
{
selectedCategory = "Others-I";
}
// else
// {
// selectedCategory = (String) spinnerCategory.getSelectedItem();
// }
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_SHORT).show();
}
btnSave.setEnabled(true);
// switch (position) {
// case 0:
// // Whatever you want to happen when the first item gets selected
// break;
// case 1:
// // Whatever you want to happen when the second item gets selected
// break;
// case 2:
// // Whatever you want to happen when the thrid item gets selected
// break;}
// }
// catch(Exception e)
// {
// Toast.makeText(getApplicationContext(), "Exception onItemSelected : " + e, Toast.LENGTH_SHORT).show();
// }
}
public void checkDBData()
{
try
{
int element;
Cursor rs = dbStatement.getCategory(passTransId);
// int countCategoryRow = rs.getCount();
// int countCategoryColumn = rs.getColumnCount();
rs.moveToFirst();
dbSubCategory = rs.getString(13);
dbNotes = rs.getString(14);
rs.moveToNext();
// String reducedNotes = dbNotes.replace("\n", "").replace("\r", "");
//// String str =dbNotes.substring(0, 3);
// Toast.makeText(getApplicationContext(), "reducedNotes : " + reducedNotes, Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java checkDBData():- "+e.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
public void readConfigFileDetails()
{
try
{
properties_config= new Properties();
FileInputStream fis2 = new FileInputStream(file_Path + "config.properties");
properties_config.load(fis2);
sessionTimeout = Long.parseLong(properties_config.getProperty("session_timeout"));
fis2.close();
}
catch(Exception e)
{
e.printStackTrace();
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java readConfigFileDetails():- "+e.toString());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed()
{
return;
}
public void onRestart()
{
finish();
super.onRestart();
startActivity(new Intent(this, Welcome.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
}
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg)
{
}
};
private Runnable disconnectCallback = new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "Session Expired", Toast.LENGTH_LONG).show();
System.out.println("Session Expired");
Intent intent = new Intent(getApplicationContext(),Welcome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
};
public void resetDisconnectTimer()
{
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, sessionTimeout);
}
public void stopDisconnectTimer()
{
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction()
{
resetDisconnectTimer();
}
#Override
public void onResume()
{
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop()
{
super.onStop();
stopDisconnectTimer();
}
}
Here is my .xml file :
<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:background="#drawable/bbk_base_all"
android:focusable="true"
android:focusableInTouchMode="true"
android:paddingRight="3dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/txtwelcome" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="130dp"
android:gravity="center" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleDate"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Transaction Date"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getDate"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="5dp"
android:paddingLeft="30dp"
android:text="Date"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleParticulars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Particulars"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getParticular"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:ems="50"
android:gravity="left"
android:maxLines="4"
android:paddingLeft="30dp"
android:text="Particulars"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleAmount"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Amount"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getAmount"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="30dp"
android:text="Amount"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleBalance"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Balance Amount"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getBalance"
android:layout_width="125dp"
android:layout_height="25dp"
android:gravity="left"
android:paddingLeft="30dp"
android:text="Balance"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleCategory"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="center_vertical"
android:paddingLeft="25dp"
android:text="Select Category"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<Spinner
android:id="#+id/spn_selectCategory"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="30dp"
android:textColor="#FFFFFF" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleNotes"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="center_vertical"
android:paddingLeft="25dp"
android:text="Notes"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/et_getNotes"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tableLayout1"
android:layout_toLeftOf="#+id/imageView1"
android:hint="Add Your Own Notes"
android:maxLines="3"
android:paddingLeft="30dp"
android:textColor="#FFFFFF" >
</EditText>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:gravity="center"
android:text="Transaction Details"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="24dp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/btnSave"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tableLayout1"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:background="#drawable/normalbuttonborder"
android:text="Save"
android:textSize="16sp"
android:textStyle="bold"
android:enabled="false" />
<Button
android:id="#+id/btnBack"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_alignBaseline="#+id/btnSave"
android:layout_alignBottom="#+id/btnSave"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/imageView1"
android:background="#drawable/normalbuttonborder"
android:text="Back"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Please help me.
Initially disable that Button after findViewById like this
btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setEnabled(false);
The problem is you have Spinner where u enabling that Button. By default 1st item of Spinner is selected automatically and it is call in onCreate(...) and your Button gets enabled what you can do
Change logic of enabling that Button in Spinner's OnItemSelected(...) check if previously selected value and currently selected value is equal and EditText's value has not been changed then disable that Button otherwise enable that Button. Use boolean flag for this work.
You didnt disable your button before enabling it.
disble your button after declaring it.
btnSave.setEnabled(false);
Then enable it in your textChanged method
Since you want to disable your button use:
btnSave.setEnabled(false);
or try setting:
btnSave.setClickable(false);
along with setEnabled(false)
Alternatively, use below line in your xml:
android:clickable = "false"
android:enabled = "false"
and whenever user is done with note editing (i.e after selecting spinner item ) enable both(enabled & clickable) on btnSave according to your logic i.e use:
btnSave.setClickable(true);
btnSave.setEnabled(true);