Database contents in different pages like same layout - android

Showing database rows as ListView/Gridview in the same layout via adapter, is there a option to display those in separate pages like same layout. So I can switch to next page by a button.
Currently am just saving values using sharedprefernce and changes the contents from layout (Just TEXT in my case). I am trying to create app for exam tests with a question and 4 options. currently am saving user score and checked radio button id in sharedpreferences when user click NEXT button.
My code:
package com.sap.quizmaster;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private MyDatabase testdb;
private Cursor mycursor;
private TextView ques;
private RadioGroup options;
private RadioButton op1;
private RadioButton op2;
private RadioButton op3;
private RadioButton op4;
private RadioButton radioButton;
private LinearLayout default_lay;
private LinearLayout default_btn_lay;
private TextView final_text;
private Button final_btn;
private Button next_btn;
private Button prev_btn;
private int checkedid = -1;
private int q_no = 1;
private String answer;
private int score = 0;
private SharedPreferences sp;
private SharedPreferences.Editor sp_edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ques = findViewById(R.id.ques);
op1 = findViewById(R.id.op1);
op2 = findViewById(R.id.op2);
op3 = findViewById(R.id.op3);
op4 = findViewById(R.id.op4);
next_btn = findViewById(R.id.next_btn);
prev_btn = findViewById(R.id.prev_btn);
options = findViewById(R.id.options);
final_btn = findViewById(R.id.final_btn);
final_text = findViewById(R.id.final_text);
default_lay = findViewById(R.id.default_text);
default_btn_lay = findViewById(R.id.default_btn);
//Loading sharedpreferences
sp = getSharedPreferences("QuizMaster", MainActivity.MODE_PRIVATE);
//Clearing all values from sharedpreferences when app re-launching
sp_edit = sp.edit();
sp_edit.clear();
sp_edit.commit();
testdb = new MyDatabase(this);
mycursor = testdb.getQuestion(q_no);
setQuestion();
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mycursor.close();
checkedid = options.getCheckedRadioButtonId();
saveInteger(q_no, checkedid);
if (checkedid != -1) {
radioButton = findViewById(checkedid);
if (radioButton.getText().equals(answer)) {
score += 3;
} else {
score -= 1;
}
}
options.clearCheck();
q_no = q_no + 1;
if(q_no>3){
default_btn_lay.setVisibility(View.GONE);
default_lay.setVisibility(View.GONE);
final_btn.setVisibility(View.VISIBLE);
final_text.setVisibility(View.VISIBLE);
final_text.setText("Your Score is "+score);
q_no = 1;
return;
}
checkedid = sp.getInt(q_no + "", -1);
if (checkedid != -1) {
radioButton = findViewById(checkedid);
radioButton.setChecked(true);
}
mycursor = testdb.getQuestion(q_no);
setQuestion();
}
});
prev_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mycursor.close();
if (q_no <= 1) {
Toast.makeText(MainActivity.this, "END", Toast.LENGTH_SHORT).show();
return;
}
q_no = q_no - 1;
mycursor = testdb.getQuestion(q_no);
setQuestion();
checkedid = sp.getInt(q_no + "", -1);
if (checkedid != -1) {
radioButton = findViewById(checkedid);
radioButton.setChecked(true);
if (radioButton.getText().equals(answer)) {
score -= 3;
} else {
score += 1;
}
}
Toast.makeText(MainActivity.this, "Button PREVIOUS pressed", Toast.LENGTH_SHORT).show();
}
});
final_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final_text.setVisibility(View.GONE);
final_btn.setVisibility(View.GONE);
default_lay.setVisibility(View.VISIBLE);
default_btn_lay.setVisibility(View.VISIBLE);
mycursor = testdb.getQuestion(q_no);
setQuestion();
sp_edit = sp.edit();
sp_edit.clear();
sp_edit.commit();
score = 0;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
testdb.close();
mycursor.close();
}
public void setQuestion() {
answer = mycursor.getString(mycursor.getColumnIndex("ANS"));
ques.setText(mycursor.getString(mycursor.getColumnIndex("QUES")));
op1.setText(mycursor.getString(mycursor.getColumnIndex("OP1")));
op2.setText(mycursor.getString(mycursor.getColumnIndex("OP2")));
op3.setText(mycursor.getString(mycursor.getColumnIndex("OP3")));
op4.setText(mycursor.getString(mycursor.getColumnIndex("OP4")));
}
public void saveInteger(int ques, int value) {
sp_edit = sp.edit();
sp_edit.putInt(ques + "", value);
sp_edit.apply();
}
}
Just get me an link or idea to think in any easy way.

Sounds like you want to use an AdapterViewFlipper
https://developer.android.com/reference/android/widget/AdapterViewFlipper
with a custom adapter
This will generate a view from a template using data from the adapter
e.g. Each question could be on a separate page with a button to move to the next question.
Example https://abhiandroid.com/ui/adapterviewflipper
But you probably don't want to use the autoflipping option and instead link a next button to the showNext() method

Related

Android: unable to read from sharedpreferences

So i have a slight problem. I have a feeling its something simple that i must be overlooking. In my second fragment im writing to sharedpreferences a certain number of keys and applying() afterwords. After i have finished writing my data to the sharedpreferences, i replace the current fragment(fragment#2), with the home fragment(fragment#1). Upon loading this fragment i call readPreferences(), which should read the data stored ealier and write the data to the various textviews i have on the home fragment. This does not happen. Im unsure at this time if its due to a write error or a read error. your help is as always, appreciated. Thanks.
Second Fragment
package lucaclock.moticlock;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class secondFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private TimePicker timePicker;
private int hour = 0;
private int min = 0;
private String mParam1;
private String mParam2;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public int snoozeTime;
public secondFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static secondFragment newInstance(String param1, String param2) {
secondFragment fragment = new secondFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
final Button btnOK = (Button) view.findViewById(R.id.btnOK);
final TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
//Stage 1 Components
final EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
edAlarmName.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
edAlarmName.setText("");
}
return false;
}
});
final EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
final EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
edOccurance.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
dialogOccurance(view);
return true;
}
return false;
}
});
final SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
seekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
TextView tv = (TextView) view.findViewById(R.id.txtVolume);
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
tv.setText("How Loud?");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
tv.setText("Volume: " + Integer.toString(progress));
//Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
}
});
final RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
final RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
rad5min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad5min.isChecked() == true)
{
rad10min.setChecked(false);
snoozeTime = 5;
}
}
});
rad10min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad10min.isChecked() == true)
{
rad5min.setChecked(false);
snoozeTime = 10;
}
}
});
final EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
edCustomSnooze.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent motion)
{
edCustomSnooze.setText("");
if(motion.getAction() == MotionEvent.ACTION_DOWN)
{
rad5min.setChecked(false);
rad10min.setChecked(false);
snoozeTime = 0;
}
return false;
}
});
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
final TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
final Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
btnOK.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String minString = null;
tp.setIs24HourView(false);
hour = tp.getCurrentHour();
min = tp.getCurrentMinute();
if(min < 10)
{
minString = new StringBuilder().append(Integer.toString(0)).append(min).toString();
}
else
minString = new StringBuilder().append(Integer.toString(min)).toString();
//tv.setText(formatTime(hour, minString));
//storeSetAlarmTime(formatTime(hour, minString));
setVisibleStage(0, view);
setVisibleStage(1, view);
edAlarmTime.setText(formatTime(hour, minString));
//HomeFragment hFrag = new HomeFragment();
//replaceFragment(hFrag);
}
});
btnCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
});
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
edAlarmName.clearFocus();
edAlarmTime.clearFocus();
edOccurance.clearFocus();
edCustomSnooze.clearFocus();
//INPUT VALIDATION
//ALL INPUT IS OK. NO NULL VALUES ANYWHERE. PROCEED...
if(validateInput(edAlarmTime, edAlarmName, edOccurance, seekVolume, rad5min, rad10min, edCustomSnooze))
{
saveData(view, edAlarmName.getText().toString(), edAlarmTime.getText().toString(), edOccurance.getText().toString(), seekVolume.getProgress(), snoozeTime, sharedPreferences);
//dialogBuilder("Alarm Saved", "Your alarm has been saved");
}
else
dialogBuilder("Validation Error", "Fix your input and try again");
}
});
edAlarmTime.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
}
return false;
}
});
return view;
}
public void dialogBuilder(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void dialogOccurance(final View view)
{
CharSequence colors[] = new CharSequence[] {"Once", "Daily", "Weekly"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("How often will this alarm repeat?");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView tv = (TextView) view.findViewById(R.id.edOccurance);
if(which == 0)
{
tv.setText("ONCE");
}
else if(which == 1)
tv.setText("DAILY");
else if(which == 2)
tv.setText("WEEKLY");
}
});
builder.show();
}
public void saveData(View view, String alarmName, String alarmTime, String occurance, int volume, int snoozeTime, SharedPreferences sharedPreferences)
{
prefEditor = sharedPreferences.edit();
prefEditor.putString(alarmTimeKey, alarmTime);
prefEditor.putString(alarmNameKey, alarmName);
prefEditor.putString(alarmOccuranceKey, occurance);
prefEditor.putInt(alarmVolumeKey, volume);
prefEditor.putInt(alarmSnoozeKey, snoozeTime);
prefEditor.putBoolean(alarmVisibleKey, true);
prefEditor.commit();
if(!sharedPreferences.getBoolean(alarmVisibleKey, true))
{
dialogBuilder("ERROR", "We tried writing the data, however we cant verify it exists");
}
else
{
dialogBuilder("Write Successfull", "true");
}
Toast.makeText(getActivity().getApplicationContext(), "Alarm Added", Toast.LENGTH_LONG).show();
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
public void setVisibleStage(int stage, View view)
{
//Stage 0 Components
TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
Button btnOK = (Button) view.findViewById(R.id.btnOK);
Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
//Stage 1 Components
EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
if(stage == 0)
{
//STAGE 0 = ANALOG CLOCK DISPLAY ONLY
tp.setVisibility(view.INVISIBLE);
btnOK.setVisibility(view.INVISIBLE);
btnCancel.setVisibility(view.INVISIBLE);
}
else if(stage == 1)
{
//STAGE 1 = EVERYTHING ELSE VISIBLE
edAlarmName.setVisibility(view.VISIBLE);
edAlarmTime.setVisibility(view.VISIBLE);
txtOccur.setVisibility(view.VISIBLE);
edOccurance.setVisibility(view.VISIBLE);
txtVolume.setVisibility(view.VISIBLE);
seekVolume.setVisibility(view.VISIBLE);
txtSnooze.setVisibility(view.VISIBLE);
rad5min.setVisibility(view.VISIBLE);
rad10min.setVisibility(view.VISIBLE);
edCustomSnooze.setVisibility(view.VISIBLE);
btnSave.setVisibility(view.VISIBLE);
}
}
public void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment);
//fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
public boolean validateInput(EditText edAlarmTime, EditText edAlarmName, EditText edOccurance, SeekBar seekVolume, RadioButton rad5min, RadioButton rad10min, EditText customSnooze)
{
String alarmTimeOK = edAlarmTime.getText().toString();
String alarmNameOK = edAlarmName.getText().toString();
String OccuranceOK = edOccurance.getText().toString();
int volumeOK = seekVolume.getProgress();
boolean FiveMinChecked = rad5min.isChecked();
boolean TenMinChecked = rad10min.isChecked();
String customSnoozeOK = customSnooze.getText().toString();
if(alarmTimeOK.matches("") || !alarmTimeOK.contains(":"))
return false;
else if(alarmNameOK.matches("") || alarmNameOK.contains("Alarm Name"))
return false;
else if(OccuranceOK.matches("") || OccuranceOK.contains("Choose Occurance"))
return false;
else if(volumeOK == 0)
return false;
else if(FiveMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(TenMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(FiveMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else if(TenMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else
return true;
}
public String formatTime(int hour, String minString)
{
String formattedString = null;
if(hour > 12)
{
formattedString = new StringBuilder().append(Integer.toString(hour - 12)).append(":").append(minString).append("PM").toString();
}
else
formattedString = new StringBuilder().append(Integer.toString(hour)).append(":").append(minString).append("AM").toString();
return formattedString;
}
}
Home Fragment
public class HomeFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private boolean alarm1Active = false;
//private boolean alarm1Visible = false;
//public String alarm1Name;
//public String alarm1Time;
//public String alarm1Occurance;
//public int alarm1Snooze;
//public int alarm1Volume;
//public boolean fragmentSwitch;
SharedPreferences sharedPreferences;
SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public boolean devMode = true;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.fragment_home, container, false);
//CODE HERE
readPreferences(view);
FloatingActionButton fabAddAlarm = (FloatingActionButton) view.findViewById(R.id.fabRefresh);
fabAddAlarm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplicationContext(), "Reading Preferences", Toast.LENGTH_LONG).show();
readPreferences(view);
}
});
return view;
}
public void readPreferences(View view)
{
TextView tvAlarm1Name = (TextView) view.findViewById(R.id.tvAlarm1Name);
TextView tvAlarm1Time = (TextView) view.findViewById(R.id.tvAlarm1Time);
TextView tvAlarm1Occurance = (TextView) view.findViewById(R.id.tvAlarm1Occurance);
Switch swAlarm1Active = (Switch) view.findViewById(R.id.swEnableAlarm1);
Button btnEditAlarm1 = (Button) view.findViewById(R.id.btnEditAlarm1);
TextView status = (TextView) view.findViewById(R.id.tvNoAlarms);
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
String alarm1Name = sharedPreferences.getString(alarmNameKey, null);
String alarm1Time = sharedPreferences.getString(alarmTimeKey, null);
String alarm1Occurance = sharedPreferences.getString(alarmOccuranceKey, null);
int alarm1Snooze = sharedPreferences.getInt(alarmSnoozeKey, 0);
int alarm1Volume = sharedPreferences.getInt(alarmVolumeKey, 0);
boolean alarm1Visible = sharedPreferences.getBoolean(alarmVisibleKey, false);
if(!alarm1Visible)
{
status.setVisibility(View.VISIBLE);
status.setText("You have no alarms set!");
}
else if(alarm1Visible)
{
status.setVisibility(View.INVISIBLE);
tvAlarm1Time.setVisibility(View.VISIBLE);
tvAlarm1Name.setVisibility(View.VISIBLE);
tvAlarm1Occurance.setVisibility(View.VISIBLE);
btnEditAlarm1.setVisibility(View.VISIBLE);
swAlarm1Active.setVisibility(View.VISIBLE);
tvAlarm1Time.setText(alarm1Time);
tvAlarm1Name.setText(alarm1Name);
tvAlarm1Occurance.setText(alarm1Occurance);
}
}
}
While saving string on SharedPreferences make sure that you are not saving null. It will instead clear the preference key.
prefEditor.putString(alarmOccuranceKey, occurance);
Make sure that occurance is not null.
Please use commit() to save the data. Also you can create a simple reusable class for SharedPreferences. Please refer to my customized class for the same: https://codebegetter.wordpress.com/2016/08/04/shared-preferences-reusable-class/
Based on the comments in one of the answers it looks like you have applied a solution. However, based on the code you posted here was the issue:
You are not storing and retrieving values from the same SharedPreferences file. When you store values you are using a custom named SharedPreferences file. When you try to retrieve those values you are referencing the SharedPreferences file that is specific to the Activity which hosts your secondFragment. (Which, in a way, is actually custom named as well...the framework bases it on your Activity name).
When you write values to SharedPreferences in your secondFragment you call:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
//...
prefEditor = sharedPreferences.edit();
When you attempt to read those values in your HomeFragment you call:
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
These two code snippets don't reference the same SharePreferences file. The most direct solution would be to update the code in your HomeFragment so that you obtain the same SharePreferences file where you stored your values like so:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);

How to get the bmi result in 2 decial places?

Here is a code that i want to make a bmi application..
So i want to make the result display like this 20.30..
How to make the result into 2 decimals places only..
Hope anybody cant help me at this part....
package com.example.bmi;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText displayweight;
EditText displayheight;
EditText displayresult;
Button Calculate;
Button Reset;
double bmi=0;
double valueheight=0;
double valueweight=0;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
/*TextView tv = new TextView(this);
tv.setText("BMI Calculator");
setContentView(tv);*/
}
private void initControls() {
displayheight = (EditText)findViewById(R.id.displayheight);
displayweight = (EditText)findViewById(R.id.displayweight);
displayresult = (EditText)findViewById(R.id.displayresult);
Calculate = (Button)findViewById(R.id.calculate);
Reset = (Button)findViewById(R.id.reset);
Calculate.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calculate(); }});
Reset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }
private void reset() {
displayheight.setText("");
displayweight.setText("");
displayresult.setText("");
}});
}
private void calculate() {
valueheight = Double.parseDouble(displayheight.getText().toString());
valueweight = Double.parseDouble(displayweight.getText().toString());
Double valueheightmeters;
valueheightmeters = valueheight / 100;
bmi = (valueweight / (valueheightmeters * valueheightmeters));
//txttipamount.setText(Double.toString(bmi));
if(bmi >= 30)
{
result = "Your BMI of " + Double.toString(bmi) + " is OBESE.";
displayresult.setText(result);
}
else if (bmi >= 25)
{
result = "Your BMI of " + Double.toString(bmi) + " is OVERWEIGHT.";
displayresult.setText(result);
}
else if (bmi >= 18.5)
{
result = "Your BMI of " + Double.toString(bmi) + " is IDEAL.";
displayresult.setText(result);
}
else
{
result = "Your BMI of " + Double.toString(bmi) + " is UNDERWEIGHT.";
displayresult.setText(result);
}
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()){
case R.id.reset:
displayresult.setText("");
break;
default:
break;
}
}
}
this topic is discussed very often. Take a look at Round a double to 2 decimal places and see if it helps you.
Just let me know if you have any further questions.

How to compare data(int) in the first and data(int) in second button in Android?

I have a problem where I want to make the comparison the data in button
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.EditText;
public class CalculateAll extends Activity implements OnClickListener {
protected int totalKalori1;
protected int totalKalori2;
protected int totalKalori3;
EditText EstimateCalorie;
TextView TotalKaloriSehari;
TextView totalsarapan;
TextView totallunch;
TextView totaldinner;
TextView calorieneeds;
TextView resultDiff;
public CalculateAll() {
}
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.calculate_all);
View kiraButton = findViewById(R.id.buttonKiraAll);
kiraButton.setOnClickListener(this);
View bezaButton = findViewById(R.id.caloriediff);
bezaButton.setOnClickListener(this);
TotalKaloriSehari = (TextView) findViewById(R.id.JumlahKalori);
totalsarapan = (TextView) findViewById(R.id.sarapantext);
totallunch = (TextView) findViewById(R.id.lunchtext);
totaldinner = (TextView) findViewById(R.id.dinnertext);
EstimateCalorie = (EditText) findViewById(R.id.BMR);
// calorieneeds = (TextView) findViewById(R.id.BMR);
resultDiff = (TextView) findViewById(R.id.result);
Bundle extras = getIntent().getExtras();
if (extras != null) {
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
totalsarapan.setText(totalKalori1 + "");
totallunch.setText(totalKalori2 + "");
totaldinner.setText(totalKalori3 + "");
}
public void onClick(View v) {
if (v.getId() == R.id.buttonKiraAll) {
int TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2,
totalKalori3);
TotalKaloriSehari.setText(TotalKalori + "");
}
else if (v.getId()== R.id.caloriediff) {
int nilaikalori = Integer.parseInt(EstimateCalorie.getText()
.toString());
int bmr = calculatebmr(nilaikalori);
String deskripsiKalori = describekalori(bmr);
resultDiff.setText("kalori makanan" + TotalKalori + " calori diperlukan " + bmr + "=" + deskripsiKalori);
// --> this TotalKalori also can't be used
Intent n = new Intent(this, MainActivity.class);
startActivity(n);
}
}
public int calculateTotalKalori(int totalKalori1, int totalKalori2,
int totalKalori3) {
return (int) (totalKalori1 + totalKalori2 + totalKalori3);
}
public int calculatebmr(int nilaikalori) {
return (int) (nilaikalori);
}
private String describekalori(int bmr) {
if (bmr < TotalKalori ) { //<-- this TotalKalori can't be read/used
return "bykkan makan";
} else if (bmr == TotalKalori) {
return "kekalkan jumlah kalori ini";
} else if (bmr > TotalKalori) {
return "kurangkan pengambilan kalori";
} else
return "oiii";
}
}
The first button, buttonKiraAll read int totalKalori, then i want to use the totalKalori data to be compare with 2nd data button calorieDiff, how i want to make the totalKalori can be read by the second button? so i can make the comparison
It's a scoping problem, you are declaring int TotalKalori locally in the onClick event.
Declare it like you have done with totalKalori1 and it should work
Or you can use getTag(); setTag(); to store the variables on the buttons...
Use setTag to the data you want
myButton.setTag("fun Stuff");
Then on the listener just get the tag (you will need to do a type cast):
OnClickListener myListner = new OnClickListener() {
public void onClick(View view) {
doSomethingAwesome(view, (String) view.getTag());
}
};
Declare int TotalKalori only once globally (in the section you declared protected int totalKalori1; protected int totalKalori2;... ) and simply use it for both buttons like: in button1 TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2,totalKalori3); this value is global so button2 already can acess it by simply using TotalKalori where you need and also the comparison portion.

Hiding and showing a single Menu Button

I have a project for an Android class, so I'm still learning and this should be a basic question. We were given a tip calculator and already made some modifications, now we have to add a menu.
When it starts up, it will be in multi-person mode. Gives a text box and Text Field for how many people you want the bill split into. When you hit menu, it should show a Single person mode which eliminates a text box and text field. The menu then changes to show a multi-person mode button in the menu.
I've got everything to work except it's showing both buttons, I cannot figure out how to hide a button temporarily. The main error is:
Cannot invoke setVisibility(int) on the primitive type int
on the statement:
multiple_button.setVisibility(View.GONE);
I've tried every combination of hiding the button I can think of, and think that the above line is correct, but unsure of how make it work.
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
I have this in the code, but it's not doing anything either.
Any help would be greatly appreciated.
edit: code. I've read through the link, but considering I don't have a OnPrepareOptions section, I need to re-read it
package com.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class tipcalc extends Activity
{
public static int one_person_button = Menu.FIRST;
private int multiple_button = Menu.FIRST +1;
static final private int reset_button = Menu.FIRST +2;
private static final int MENU_ITEM = 0;
private EditText txtbillamount;
private EditText txtpeople;
private EditText txtpercentage;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople=0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem itemOne = menu.add(0, one_person_button, Menu.NONE,
R.string.one_person);
MenuItem itemMultiple = menu.add(1, multiple_button, Menu.NONE,
R.string.multiple);
MenuItem itemReset = menu.add(2, reset_button, Menu.NONE,
R.string.reset);
itemOne.setIcon(R.drawable.ic_menu_invite);
itemMultiple.setIcon(R.drawable.ic_menu_allfriends);
itemReset.setIcon(R.drawable.ic_menu_refresh);
one_person_button.setGroupVisible(0, true);
multiple_button.setVisibility(View.GONE);
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (one_person_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.INVISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.INVISIBLE) ;
multiple_button = View.VISIBLE;
one_person_button = View.GONE;
numofpeople = 1; }
else if (multiple_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.VISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.VISIBLE) ;
multiple_button = View.GONE;
one_person_button = View.VISIBLE;
}
return false;
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
txtperperson=(TextView)findViewById(R.id.txtperperson);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
RadioButton poorButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton goodButton = (RadioButton) findViewById(R.id.radioButton2);
RadioButton excellentButton = (RadioButton) findViewById(R.id.radioButton3);
if (poorButton.isChecked()){
percentage = Double.parseDouble(poorButton.getText().toString());
} else if (goodButton.isChecked()){
percentage = Double.parseDouble(goodButton.getText().toString());
} else if (excellentButton.isChecked()){
percentage = Double.parseDouble(excellentButton.getText().toString());
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
txtperperson.setText("");
txttipamount.setText("");
txttotal.setText("");
}
}
Post all of your relavent source code. Without it, we cannot give you specific advice about what is going wrong.
I can tell you though you'll be needing to override onPrepareOptionsMenu() and inside there you'll want to check which mode your in and make the proper button be visible. But you need to call setVisibility(View.VISIBLE); on a reference to the button widget, not on an int.
This page holds the answer to your questions.
try calling setVisibility with 8

Android - register button click and take action based on radio selection

I'm trying to teach myself how to write android apps and I'm having trouble registering a button click and taking actions based on which radio button is selected at the time. This is a simple tip calculator:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.RadioGroup;
import android.view.View;
public class TipCalc extends Activity implements RadioGroup.OnCheckedChangeListener,View.OnClickListener
{
TextView result;
RadioGroup radiogroup1;
RadioButton r1,r2,r3;
Button calculate;
EditText bill, resulttotal;
private int radioCheckedId = -1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radiogroup1 = (RadioGroup) findViewById(R.id.radiogroup1);
Button calculate = (Button) findViewById(R.id.calculate);
RadioButton r1 = (RadioButton) findViewById(R.id.poor);
RadioButton r2 = (RadioButton) findViewById(R.id.average);
RadioButton r3 = (RadioButton) findViewById(R.id.excellent);
EditText bill = new EditText(this);
EditText resulttotal = new EditText(this);
radiogroup1.setOnCheckedChangeListener(this);
calculate.setOnClickListener(this);
//bill.setText("0");
//resulttotal.setText("0");
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
radioCheckedId = checkedId;
}
public void onClick(View v)
{
if (v == calculate)
{
String billtotal;
double total = 0;
billtotal = bill.getText().toString();
final int aInt = Integer.parseInt(billtotal);
if (radioCheckedId == 1)
{
total = aInt * 1.1;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == 2)
{
total = aInt * 1.15;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == 3)
{
total = aInt * 1.2;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
}
}
}
Everything loads just fine, but nothing happens when I press the calculate button in the virtual phone.
The problem is where you're comparing the RadioGroup's selected id... you'll want to change your onClick() to:
public void onClick(View v) {
if (v == calculate) {
String billtotal;
double total = 0;
billtotal = bill.getText().toString();
final int aInt = Integer.parseInt(billtotal);
if (radioCheckedId == R.id.poor) {
total = aInt * 1.1;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == R.id.average) {
total = aInt * 1.15;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == R.id.excellent) {
total = aInt * 1.2;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
}
}
onCheckedChanged() gives you will be the R.id for the view and not just a number which tells you which it is in sequence.
A few quick (unrelated) suggestions:
Use a switch statement instead of a bunch of if-statements.
Put something in there to check for -1 (nothing checked) too... just to be sure.
In the onClick() I usually check for which View was clicked by checking the incoming view's id. This just makes it where you don't have to keep everything stored and (IMHO) is a little more clear what you're talking about.
The above suggestions would look something like:
public void onClick(View v) {
if (v.getId() == R.id.calculate) {
String billtotal;
double total = 0;
billtotal = bill.getText().toString();
final int aInt = Integer.parseInt(billtotal);
switch(radioCheckedId) {
case R.id.poor:
total = aInt * 1.1;
final String aString = Double.toString(total);
resulttotal.setText(aString);
break;
case R.id.average:
total = aInt * 1.15;
final String aString = Double.toString(total);
resulttotal.setText(aString);
break;
case R.id.excellent:
total = aInt * 1.2;
final String aString = Double.toString(total);
resulttotal.setText(aString);
break;
default:
// do something for when nothing is selected... maybe throw an error?
break;
}
}
}
Lastly, if all you're doing in onCheckedChanged() is storing the value you could get rid of it all together and just check for it in the onClick(). Something like:
public void onClick(View v) {
int radioCheckedId = radiogroup1.getCheckedRadioButtonId();
if (v == calculate) {
// ...
Unrelated, but another problem I noticed (and someone else mentioned)... if your EditTexts are listed in the XML layout then you'd need to get hooks to them like this (and not create new ones):
EditText bill = (EditText) findViewById(R.id.bill );
EditText resulttotal = (EditText) findViewById(R.id.resulttotal);
Also, you could probably just use a TextView instead of an EditView for the result if yo udon't need it to be editable.
import java.text.NumberFormat;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.RadioGroup;
import android.view.View;
public class TipCalc extends Activity
{
TextView result;
RadioGroup radiogroup1;
RadioButton r1,r2,r3;
Button calculate;
EditText bill, resulttotal;
Locale currentLocale = Locale.getDefault();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radiogroup1 = (RadioGroup) findViewById(R.id.radiogroup1);
final Button calculate = (Button) findViewById(R.id.calculate);
final RadioButton r1 = (RadioButton) findViewById(R.id.poor);
final RadioButton r2 = (RadioButton) findViewById(R.id.average);
final RadioButton r3 = (RadioButton) findViewById(R.id.excellent);
final EditText bill = (EditText) findViewById(R.id.bill);
final EditText tiptotal = (EditText) findViewById(R.id.tiptotal);
final EditText resulttotal = (EditText) findViewById(R.id.resulttotal);
bill.setText("0.00");
tiptotal.setText("0.00");
resulttotal.setText("0.00");
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws NumberFormatException {
if (v == calculate)
{
NumberFormat currencyFormatter;
currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
double atotal = 0;
double btotal = 0;
String billtotal = bill.getText().toString();
Double aDbl = 0.00;
try
{
aDbl = Double.parseDouble(billtotal);
}
catch(NumberFormatException n)
{
aDbl = 0.00;
}
if (r1.isChecked())
{
atotal = aDbl * 1.1;
btotal = aDbl * 0.1;
}
if (r2.isChecked())
{
atotal = aDbl * 1.15;
btotal = aDbl * 0.15;
}
if (r3.isChecked())
{
atotal = aDbl * 1.2;
btotal = aDbl * 0.2;
}
final String bString = currencyFormatter.format(btotal);
tiptotal.setText(bString);
final String aString = currencyFormatter.format(atotal);
resulttotal.setText(aString);
}
}
});
}
}
I have some similar problem. I have a countdown in a radio group activity.
When user clicks the next Button the radio group is checked to see if an option is selected.
I implemented the button pressed at the end of the countdown, now i need to pass a checked radio Id to bypass the default user message of an option not selected.
case R.id.next:
Log.d(" ID BOTAO",((java.lang.String) String).valueOf(rGroup3.getCheckedRadioButtonId()));
if(rGroup3.getCheckedRadioButtonId()==-1){
Context context = getApplicationContext();
CharSequence text = "Please, select an option!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
}
Your problem is that you never add EditText instances to the current layout.
You should add them as children of the main layout.

Categories

Resources