Android checkboxes, how to implement if statement. - android

I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.
But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.
e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".
package com.example.vic.cdmes_;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class results extends AppCompatActivity {
private Button displayResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
viewResults();
}
private void viewResults() {
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");
displayResult = (Button)findViewById(R.id.displayResults);
displayResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(results.this,.toString(),
// Toast.LENGTH_SHORT).show();
if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
{
//if the number of checkboxes exceeds
}
else
if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
{
//display the person might be having a widened bronchus
}
else
if (alb1&&alb2&&alb3&&cs1&&cs2)
{
//display the person might be having a alb disease
}
else
if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
{
//display the person might be having a airborne disease
}
}
});
}
}
thanks for the help in advance.

Set Default Boolean value. Like This
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1",true);

You can get the count of wb, ab and alb below, using that you can write the if statement.
int wbCount = 0, abCount = 0, albCount = 0;
boolean cs = (cs1 && cs2);
for(int i=1; i <= 7; i++) {
if(getIntent().getExtras().getBoolean("wb"+i) && cs) {
wbCount++;
}
}
for(int i=1; i <= 3; i++) {
if(getIntent().getExtras().getBoolean("alb"+i) && cs) {
albCount++;
}
}
for(int i=1; i <= 4; i++) {
if(getIntent().getExtras().getBoolean("ab"+i) && cs) {
abCount++;
}
}

Related

Database contents in different pages like same layout

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

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 can I give a value to a variable in one Onclicklistener and use that value in another Onclicklistener in Android?

I can't figure out how to fix this problem in my code: I am making a small app which randomly asks you for 20 words from Dutch (nederlands) to English (engels). I have saved the words in arrays and the words are randomly picked now. There are 2 buttons: One for picking a random word and one for checking if the answer is correct. The variable iwoord is given a random value when pressing button Newword and i want the same value to be used in the next OnClickListener, so I can compare the arrays and see if the answer is correct. But the variable cannot be resolved in the second OnClickListener. Can anybody help me solving my problem?
public class MainActivity extends Activity {
EditText NederlandsEdit;
EditText EngelsEdit;
Button ControleerButton;
Button NieuwwoordButton;
Random woord = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] nederlands = new String[20];
nederlands[0] = "bij";
nederlands[1] = "paraplu";
nederlands[2] = "hond";
nederlands[3] = "kaas";
nederlands[4] = "eekhoorn";
nederlands[5] = "fiets";
nederlands[6] = "auto";
nederlands[7] = "vis";
nederlands[8] = "maan";
nederlands[9] = "aarde";
nederlands[10] = "vuur";
nederlands[11] = "boom";
nederlands[12] = "blaadje";
nederlands[13] = "soep";
nederlands[14] = "sok";
nederlands[15] = "potlood";
nederlands[16] = "kat";
nederlands[17] = "muis";
nederlands[18] = "zeep";
nederlands[19] = "ring";
final String[] engels = new String[20];
engels[0] = "bee";
engels[1] = "umbrella";
engels[2] = "dog";
engels[3] = "cheese";
engels[4] = "squirrel";
engels[5] = "bicycle";
engels[6] = "car";
engels[7] = "fish";
engels[8] = "moon";
engels[9] = "earth";
engels[10] = "fire";
engels[11] = "tree";
engels[12] = "leaf";
engels[13] = "soup";
engels[14] = "sock";
engels[15] = "pencil";
engels[16] = "cat";
engels[17] = "mouse";
engels[18] = "soap";
engels[19] = "ring";
NederlandsEdit = (EditText) findViewById(R.id.editnederlands);
EngelsEdit = (EditText) findViewById(R.id.editengels);
ControleerButton = (Button) findViewById(R.id.butcontroleer);
NieuwwoordButton = (Button) findViewById(R.id.butnieuwwoord);
NieuwwoordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwwoordButton.setEnabled(false);
ControleerButton.setEnabled(true);
int iwoord = woord.nextInt(20 - 0) + 0;
NederlandsEdit.setText(nederlands[iwoord]);
}
});
ControleerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(EngelsEdit.getText().toString().equals(engels[iwoord])){
Toast.makeText(getBaseContext(), "correct!", Toast.LENGTH_SHORT).show();
}
else
{
i = i + 1;
}
}
});
}
The int "iwoord" should be declared globally just like the edittexts. I have posted the code just in case.
package com.example.stack_test;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText NederlandsEdit;
EditText EngelsEdit;
Button ControleerButton;
Button NieuwwoordButton;
Random woord = new Random();
int i,iwoord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] nederlands = new String[20];
nederlands[0] = "bij";
nederlands[1] = "paraplu";
nederlands[2] = "hond";
nederlands[3] = "kaas";
nederlands[4] = "eekhoorn";
nederlands[5] = "fiets";
nederlands[6] = "auto";
nederlands[7] = "vis";
nederlands[8] = "maan";
nederlands[9] = "aarde";
nederlands[10] = "vuur";
nederlands[11] = "boom";
nederlands[12] = "blaadje";
nederlands[13] = "soep";
nederlands[14] = "sok";
nederlands[15] = "potlood";
nederlands[16] = "kat";
nederlands[17] = "muis";
nederlands[18] = "zeep";
nederlands[19] = "ring";
final String[] engels = new String[20];
engels[0] = "bee";
engels[1] = "umbrella";
engels[2] = "dog";
engels[3] = "cheese";
engels[4] = "squirrel";
engels[5] = "bicycle";
engels[6] = "car";
engels[7] = "fish";
engels[8] = "moon";
engels[9] = "earth";
engels[10] = "fire";
engels[11] = "tree";
engels[12] = "leaf";
engels[13] = "soup";
engels[14] = "sock";
engels[15] = "pencil";
engels[16] = "cat";
engels[17] = "mouse";
engels[18] = "soap";
engels[19] = "ring";
NederlandsEdit = (EditText) findViewById(R.id.editnederlands);
EngelsEdit = (EditText) findViewById(R.id.editengels);
ControleerButton = (Button) findViewById(R.id.butcontroleer);
NieuwwoordButton = (Button) findViewById(R.id.butnieuwwoord);
NieuwwoordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwwoordButton.setEnabled(false);
ControleerButton.setEnabled(true);
iwoord = woord.nextInt(20 - 0) + 0;
NederlandsEdit.setText(nederlands[iwoord]);
}
});
ControleerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(EngelsEdit.getText().toString().equals(engels[iwoord])){
Toast.makeText(getBaseContext(), "correct!", Toast.LENGTH_SHORT).show();
}
else
{
i = i + 1;
}
}
});
}
}
Declare your variable globally and you can able assign value from first onclicklistener and use it frm the second onclicklistener
In case you are facing problems that listeners ask you to make your variable final, use a setter and a getter method for your variable. You cant change the value of an integer variable once you have initialized it for the first time. Don't use it directly in the Listener code, and you wont have to make it final.
Read this article if you need to be familiar with getters and setters.

how to pass value data between classes/activity in Android?

For example i have activity1, activity2, activity3 and lastly valueAllActivity?
how do I pass the data from activity1, activity2, activity3 to --> valueAllActivity?
to pass INT value in each activity to valueAllActivity.
I am very new in developing Android program, so if anyone could guide, it would be an honor :)
Thank you
//Activity1
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
public class Breakfast extends Activity {
public static int TotalKalori;
ArrayAdapter<String> FoodType1Adapter;
ArrayAdapter<String> DrinkType1Adapter;
String FoodTypeArray[] = { "","white bread"}
int[] valueFoodTypeArray = { 0,20};
String[] DrinkTypeArray = { "","tea"};
int[] valueDrinkTypeArray = { 0,201};
Spinner FoodTypeSpinner;
Spinner DrinkTypeSpinner;
TextView SarapanTotalKalori;
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.breakfast);
FoodTypeSpinner = (Spinner) findViewById(R.id.spinner1);
DrinkTypeSpinner = (Spinner) findViewById(R.id.spinner2);
SarapanTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
// load the default values for the spinners
loadFoodValue1Range();
loadDrinkValue1Range();
}
// nk handle button --> refer calculate button
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
// nk bace dkat spinner
int food1 = getSelectedFood();
int drink1 = getSelectedDrink();
// kira kalori sarapan
// view kalori sarapan
int totalKalori1 = calculateSarapan(food1, drink1);
SarapanTotalKalori.setText(totalKalori1 + "");
//setttlBreakfast(totalKalori1);
Intent b= new Intent(Breakfast.this, Lunch.class);
b.putExtra("totalBreakfast",totalKalori1);
Breakfast.this.startActivity(b);
}
}
public int getSelectedFood() {
String selectedFoodValue = (String) FoodTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodTypeArray.length; i++) {
if (selectedFoodValue.equals(FoodTypeArray[i])) {
index = i;
break;
}
}
return valueFoodTypeArray[index];
}
public int getSelectedDrink() {
String selectedDrinkValue = (String) DrinkTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkTypeArray.length; i++) {
if (selectedDrinkValue.equals(DrinkTypeArray[i])) {
index = i;
break;
}
}
return valueDrinkTypeArray[index];
}
public int calculateSarapan(int food1, int drink1) {
return (int) (food1 + drink1);
}
public void loadFoodValue1Range() {
FoodTypeSpinner.setAdapter(FoodType1Adapter);
// set makanan b4 pilih
FoodTypeSpinner.setSelection(FoodType1Adapter.getPosition("400"));
}
public void loadDrinkValue1Range() {
DrinkTypeSpinner.setAdapter(DrinkType1Adapter);
DrinkTypeSpinner.setSelection(DrinkType1Adapter.getPosition("77"));
}
public void initializeSpinnerAdapters() {
FoodType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodTypeArray);
DrinkType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkTypeArray);
}
}
//Acitivity 2
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.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Lunch extends Activity {
public static int TotalKalori;
private int totalKalori1;
/* private int ttlLunch;
public void setttlLunch(int ttlLunch){
this.ttlLunch=ttlLunch;
}
public int getttlLunch(){
return ttlLunch;
} */
ArrayAdapter<String> FoodType2Adapter;
ArrayAdapter<String> DrinkType2Adapter;
ArrayAdapter<String> LaukType2Adapter;
String FoodType2Array[] = { "","Burger"};
int[] valueFoodType2Array = { 0, 150 };
String DrinkType2Array[] = { "","Pepsi" };
int[] valueDrinkType2Array = { 0,100 };
String LaukType2Array[] = { "","Wings" };
int[] valueLaukType2Array = { 0,200 };
Spinner FoodType2Spinner;
Spinner DrinkType2Spinner;
Spinner LaukType2Spinner;
TextView LunchTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.lunch);
FoodType2Spinner = (Spinner) findViewById(R.id.spinner1);
LaukType2Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType2Spinner = (Spinner) findViewById(R.id.spinner3);
LunchTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue2Range();
loadDrinkValue2Range();
loadLaukValue2Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food2 = getSelectedFood2();
int drink2 = getSelectedDrink2();
int lauk2 = getSelectedLauk2();
int totalKalori2 = calculateLunch(food2, drink2, lauk2);
LunchTotalKalori.setText(totalKalori2 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(Lunch.this, Dinner.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
Lunch.this.startActivity(n);
}
}
public int getSelectedFood2() {
String selectedFoodValue2 = (String) FoodType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType2Array.length; i++) {
if (selectedFoodValue2.equals(FoodType2Array[i])) {
index = i;
break;
}
}
return valueFoodType2Array[index];
}
public int getSelectedDrink2() {
String selectedDrinkValue2 = (String) DrinkType2Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType2Array.length; i++) {
if (selectedDrinkValue2.equals(DrinkType2Array[i])) {
index = i;
break;
}
}
return valueDrinkType2Array[index];
}
public int getSelectedLauk2() {
String selectedLaukValue2 = (String) LaukType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < LaukType2Array.length; i++) {
if (selectedLaukValue2.equals(LaukType2Array[i])) {
index = i;
break;
}
}
return valueLaukType2Array[index];
}
public int calculateLunch(double food2, double drink2, double lauk2) {
return (int) (food2 + drink2 + lauk2);
}
public void loadFoodValue2Range(){
FoodType2Spinner.setAdapter(FoodType2Adapter);
FoodType2Spinner.setSelection(FoodType2Adapter.getPosition("200"));
}
public void loadDrinkValue2Range(){
DrinkType2Spinner.setAdapter(DrinkType2Adapter);
DrinkType2Spinner.setSelection(DrinkType2Adapter.getPosition("77"));
}
public void loadLaukValue2Range(){
LaukType2Spinner.setAdapter(LaukType2Adapter);
LaukType2Spinner.setSelection(LaukType2Adapter.getPosition("2"));
}
public void initializeSpinnerAdapters(){
FoodType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodType2Array);
DrinkType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkType2Array);
LaukType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, LaukType2Array);
}
}
//Activity 3
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.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Dinner extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
/*private int ttlDinner;
public void setttlDinner(int ttlDinner){
this.ttlDinner=ttlDinner;
}
public int getttlDinner(){
return ttlDinner;
} */
ArrayAdapter<String> FoodType3Adapter;
ArrayAdapter<String> ProteinType3Adapter;
ArrayAdapter<String> DrinkType3Adapter;
String FoodType3Array[] = { "","chicken chop" };
int[] valueFoodType3Array = { 0, 204};
String ProteinType3Array[] = { "","chicken breast", };
int[] valueProteinType3Array = { 0, 40 };
String DrinkType3Array[] = { "","mineral water" };
int[] valueDrinkType3Array = { 0, 0};
Spinner FoodType3Spinner;
Spinner ProteinType3Spinner;
Spinner DrinkType3Spinner;
TextView DinnerTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.dinner);
FoodType3Spinner = (Spinner) findViewById(R.id.spinner1);
ProteinType3Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType3Spinner = (Spinner) findViewById(R.id.spinner3);
DinnerTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue3Range();
loadProteinValue3Range();
loadDrinkValue3Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food3 = getSelectedFood3();
int protein3 = getSelectedProtein3();
int drink3 = getSelectedDrink3();
int totalKalori3 = calculateDinner(food3, protein3, drink3);
DinnerTotalKalori.setText(totalKalori3 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlDinner(totalKalori3);
Intent d= new Intent(Dinner.this, CalculateAll.class);
d.putExtra("totalBreakfast", totalKalori1);
d.putExtra("totalLunch", totalKalori2);
d.putExtra("totalDinner", totalKalori3);
startActivity(d);
}
}
public int getSelectedFood3() {
String selectedFoodValue3 = (String) FoodType3Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType3Array.length; i++) {
if (selectedFoodValue3.equals(FoodType3Array[i])) {
index = i;
break;
}
}
return valueFoodType3Array[index];
}
public int getSelectedProtein3() {
String selectedProteinValue3 = (String) ProteinType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < ProteinType3Array.length; i++) {
if (selectedProteinValue3.equals(ProteinType3Array[i])) {
index = i;
break;
}
}
return valueProteinType3Array[index];
}
public int getSelectedDrink3() {
String selectedDrinkValue3 = (String) DrinkType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType3Array.length; i++) {
if (selectedDrinkValue3.equals(DrinkType3Array[i])) {
index = i;
break;
}
}
return valueDrinkType3Array[index];
}
public int calculateDinner(int food3, int protein3, int drink3) {
return (int) (food3 + protein3 + drink3);
}
public void loadFoodValue3Range() {
FoodType3Spinner.setAdapter(FoodType3Adapter);
FoodType3Spinner.setSelection(FoodType3Adapter.getPosition("10"));
}
public void loadProteinValue3Range() {
ProteinType3Spinner.setAdapter(ProteinType3Adapter);
ProteinType3Spinner.setSelection(ProteinType3Adapter.getPosition("99"));
}
public void loadDrinkValue3Range(){
DrinkType3Spinner.setAdapter(DrinkType3Adapter);
DrinkType3Spinner.setSelection(DrinkType3Adapter.getPosition("10"));
}
public void initializeSpinnerAdapters(){
FoodType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, FoodType3Array);
ProteinType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ProteinType3Array);
DrinkType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DrinkType3Array);
}
}
// CalulateAllActivity - where I want to add up all the value (int)
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.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class CalculateAll extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
private int totalKalori3;
ArrayAdapter<String> SexTypeAdapter;
String SexTypeArray[] = { "Lelaki", "Perempuan" };
Spinner SexTypeSpinner;
TextView TotalKaloriSehari;
TextView totalsarapan;
public CalculateAll() {
}
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.calculate_all);
SexTypeSpinner = (Spinner) findViewById(R.id.spinnerSex);
TotalKaloriSehari = (TextView) findViewById(R.id.JumlahKalori);
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.buttonKiraAll) {
// public final int TotalKalori;
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(this, CalculateAll.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
n.putExtra("totalDinner", totalKalori3);
startActivity(n);
int TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2, totalKalori3);
TotalKaloriSehari.setText(TotalKalori+ "");
// int ttlCAl =getttlBreakfast()+getttlLunch()+getttlDinner();
//String finalString = Integer.toString(calcAll());
//TextView tv1 = (TextView) findViewById(R.id.JumlahKalori);
//tv1.setText(finalString);
}
}
public int calculateTotalKalori(int totalKalori1, int totalKalori2,
int totalKalori3) {
return (int) (totalKalori1 + totalKalori2 + totalKalori3);
}
}
thank you anyone who try to help me. much appreciated :) as you know, I on my early stage developing the program, so thank you very much everyone :)
You would do it via intents. Assume data1 and data 2 are Strings and data3 is an int.
In your first activity when you set the intent to call the next activity:
Intent myIntent = new Intent(Activity1.this, Activity2.class);
myIntent.putExtra("Data1", data1);
myIntent.putExtra("Data2", data2);
myIntent.putExtra("Data3", data3);
Activity1.this.startActivity(myIntent);
Then in Activity 2:
Private String data1;
Private String data2;
Private int data3;
Bundle extras = getIntent().getExtras();
if (extras != null) {
data1 = extras.getString("Data1");
data2 = extras.getString("Data2");
data3 = extras.getInt("Data3");
}
// other code
Intent myIntent = new Intent(Activity2.this, Activity3.class);
myIntent.putExtra("Data1", data1);
myIntent.putExtra("Data2", data2);
myIntent.putExtra("Data3", data3);
Activity2.this.startActivity(myIntent);
And so on, through as many activities as you want.
You can Use any identifier you want. Above I used Data1, Data2, Data3. They could have as well been called Make, Model and TopSpeed. As long as you use the same id to get the data as you use to put it, it'll be fine.
EDIT
Several things I see...
First, use the getExtra to get the data out of the bundle in your onCreate method for each activity. Put the intents to call the next activity wherever you need to.
Then, one of your issues is here in activity 2:
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
}
You haven't put totalLunch into the bundle yet, so you shouldn't be trying to get it yet. Delete that line.
Same thing in Activity 3:
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
You haven't put totalDinner into the bundle yet, so you shouldn't be trying to get it yet. Delete that line.
Then in Calculate All you set an unnecessary intent and restart the activity... which looks to me like it would result in an infintie loop:
Intent n= new Intent(this, CalculateAll.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
n.putExtra("totalDinner", totalKalori3);
startActivity(n);
Delete this whole section from the 'CalculateAll` activity.
I think moving the getExtra parts and removing the bad data will fix your issue.
You have several options:
Use intents to pass data when you move between activities.
Use a global application state bean, which you create by extending the Application class, which you can then access in your activity by calling the getApplication() method.
Use the SharedPreferences api if the shared data is something that will be provided by the user.
Persist data to the SQLite database and retrieve it in each Activity, if you want the data to be available even when the application is shutdown and restarted.
Read the documentation for all available ways in which you can store and retrieve data in your application.
You have some possibilities.
One that I like more is using the application context...
Create a new class like:
public class DataApp extends Application{
private int myInt;
private MyCustomObject myObj;
public int getMyInt() { return myInt; }
public void setMyInt(int i) { this.myInt = i; }
public MyCustomObject getMyObj() { return myObj; }
public void setMyObj(MyCustomObject ob) { this.myObj = ob;}
}
Add this to you manifest:
<application
android:name=".DataApp"
...>
...
</application>
After, when you need to pass data you can do this in your activity:
DataApp dataInfo = (DataApp)getApplicationContext();
//set some data:
dataInfo.setMyObj(/*put the object*/);
In your other activity, you get you object like this:
DataApp dataInfo = (DataApp)getApplicationContext();
MyCustomObject obj = dataInfo.getMyObj();
With this option, you can pass every object type you want.
The recommended way to pass data from one activity to another is via intents.
Have a look at this tutorial.
I used a method in an activity to call another activity.
It starts a game with two variables (resume and number of players).
private void MethodToCallAnotherActivity(int resume, int players) {
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra(NextActivity.RESUME, resume);
intent.putExtra(NextActivity.PLAYERS, players);
startActivity(intent);
}
in the 'onCreate' of the NextActivity, I used
int resume = getIntent().getIntExtra(Game.RESUME, 1);
to read the variable I wanted.
Good luck!
To pass using the intent just do like that:
private String fUserName;
private String fPassword;
private Boolean fUseProxy;
private String fProxyAddress;
private Integer fProxyPort;
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard_activity);
fProjectsButton = (Button) findViewById(R.id.dashProjectsButton);
fUserName = "something";
fPassword = "xxx";
fUseProxy = false;
fProxyAddress = "";
fProxyPort = 80;
fProjectsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(CodeBaseClientDashBoardActivity.this, CodeBaseClientProjectsActivity.class);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_API_USERNAME, fUserName);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PASSWORD, fPassword);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_USE_PROXY, fUseProxy);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PROXY_ADDRESS, fProxyAddress);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PROXY_PORT, fProxyPort);
startActivity(i);
}
});
}

Show log messages on screen for Android application

Is it possible to display the log messages (which I print using android.util.Log) on screen in an Android application?
Is there any other better method to just output lines on the screen?
Something like System.out.println?
Like others have suggested, you can use log cat. If you are using the emulator or debugging a device, you can use adb logcat to view the messages. In Eclipse debug perspective, there is a window that will do that for you.
Another way, without a debugger attached, is to use the CatLog - Logcat Reader application.
Yes zero4
what you are attempting to do is dropping 'logcat' comand on android shell & getting command output as output stream.This link will help you.
I use "android.widget.Toast.makeText(Context context, CharSequence text, int duration)" to do something like what you are asking. Seems like the easiest way to get some quick messages on the screen and make it go away automatically (based on the last parameter).
:-)
Well, there is a solution to log anything you want on screen using this lib. It didn't worked for me, so I develop my own solution you can find an example of it here. It's really simple, just add a class OnScreenLog to your project
package br.com.ideiageni.onscreenlogSample;
import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by ariel on 07/07/2016.
*/
public class OnScreenLog {
private static int timeoutTime = 1000;
private static TextView tvLog;
private static int logCount = 0;
private static int logCountMax = 30;
private static String[] logs = new String[logCountMax];
private static int cntClicks = 0;
private static boolean visibility = false;
private static Activity activity;
private int maxClicks = 5;
public OnScreenLog(){}
public OnScreenLog(Activity activity, int ViewID){
OnScreenLog.activity = activity;
tvLog = new TextView(activity.getApplicationContext());
maintainLog("Log is working");
tvLog.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
tvLog.setTextColor(Color.BLACK);
tvLog.setBackgroundColor(Color.LTGRAY);
tvLog.setAlpha((float) 0.4);
View v = null;
LinearLayout linearLayout;
RelativeLayout relativeLayout;
try {
linearLayout = (LinearLayout) activity.findViewById(ViewID);
} catch (ClassCastException e) {linearLayout = null;};
try {
relativeLayout = (RelativeLayout) activity.findViewById(ViewID);
} catch (ClassCastException e) {relativeLayout = null;};
if(linearLayout != null) {
linearLayout.addView(tvLog);
v = linearLayout;
} else if(relativeLayout != null) {
relativeLayout.addView(tvLog);
v = relativeLayout;
}
if(v != null) {
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
cntClicks++;
timerHandler.removeCallbacks(rTimeout);
timerHandler.postDelayed(rTimeout, timeoutTime);
if (cntClicks > maxClicks-1) {
setLogVisible(!visibility);
timerHandler.removeCallbacks(rTimeout);
cntClicks = 0;
}
break;
}
return false;
}
});
}
}
public void log (String text){
String logText = text;
maintainLog(logText);
}
public void log (int text){
String logText = String.valueOf(text);
maintainLog(logText);
}
public void log (int[] text){
StringBuilder builder = new StringBuilder();
for (int i : text) {
builder.append(i);
builder.append("-");
}
String logText = builder.toString();
maintainLog(logText);
}
public void log (byte[] text){
StringBuilder builder = new StringBuilder();
for (int i : text) {
builder.append(i);
builder.append("-");
}
String logText = builder.toString();
maintainLog(logText);
}
private void maintainLog(String newText){
String logText = "";
if(logCount<logCountMax) logCount++;
for(int i=logCount-1; i>0; i--){
logs[i] = logs[i-1];
}
logs[0] = newText;
for(int i=0; i<logCount; i++){
if(i<logCount-1) logText+=logs[i]+System.getProperty("line.separator");
else logText+=logs[i];
}
tvLog.setText(logText);
}
public void clearLog(){
tvLog.setText("");
}
public void setLogVisible(boolean visibility){
if(visibility) tvLog.setVisibility(View.VISIBLE);
else tvLog.setVisibility(View.INVISIBLE);
OnScreenLog.visibility = visibility;
}
public static int getLogCountMax() {
return logCountMax;
}
public static void setLogCountMax(int logCountMax) {
OnScreenLog.logCountMax = logCountMax;
logs = new String[logCountMax];
}
public int getMaxClicks() {
return maxClicks;
}
public void setMaxClicks(int maxClicks) {
this.maxClicks = maxClicks;
}
Handler timerHandler = new Handler();
Runnable rTimeout = new Runnable() {
#Override
public void run() {
cntClicks = 0;
}
};
}
then, for instance:
public class Activity1 extends AppCompatActivity {
private OnScreenLog log;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
log = new OnScreenLog(this, R.id.content_1);
log.log("Started log on Activity 1");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(intent);
log.log("Starting Activity 2");
Snackbar.make(view, "Starting Activity 2", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
Where R.id.content_1 is the name of the main LinearLayout or RelativeLayout of your activity.
<?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:id="#+id/content_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="br.com.ideiageni.onscreenlogSample.Activity1"
tools:showIn="#layout/activity_1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 1!" />
</RelativeLayout>
Neither solutions print the current log messages, so you'll need to tell it to log to screen the same informations you log today on your current log.
Work not finished yet but can be used for anyone in need. Missing some directions on how to use. Suggestions are welcome.

Categories

Resources