I have make this app which calculates Linear Acceleration of device of all dimension, combines it, and calculates net acceleration. Top five acceleration values are stored in Shared Preference key-value pairs.
The problem is when I close the app and reopen it, I find the values increased to a much higher level. I don't seem to catch the point in the code from where it is happening.
Please Help me out.
ShakoMeter.java (this is my main activity where all sensor data is collected and stored)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ShakeOMeter extends Activity implements SensorEventListener{
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SensorManager smngr;
Sensor sen;
TextView t,t3;
double max=-1;
double ax = 0,ay = 0,az = 0;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
ArrayList<Float> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shake_ometer);
t = (TextView)findViewById(R.id.TextView1);
// Showing initial message
TextView textview = new TextView(getApplicationContext());
textview.setText("Get ready to Shake It!!");
textview.setBackgroundColor(Color.BLACK);
textview.setTextColor(Color.WHITE);
textview.setTextSize(30);
textview.setPadding(10,10,10,10);
textview.setGravity(Gravity.CENTER_VERTICAL);
Toast toast = new Toast(getApplicationContext());
toast.setView(textview);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.FILL, 0, 0);
toast.show();
//Getting Sensor Control
smngr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sen = (Sensor) smngr.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
//Obtaining SharedPreferance for storing key-value pairs of high scores.
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPref.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shake_ometer, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
list = new ArrayList<Float>();
ax = event.values[0];
ay = event.values[1];
az = event.values[2];
double temp=Math.sqrt(ro(ax)*ro(ax)+ro(ay)*ro(ay)+ro(az)*ro(az));
if(temp>=max){
max=temp;
t.setText(ro(max)+"");
list.add(sharedPref.getFloat("1", 0));
list.add(sharedPref.getFloat("2", 0));
list.add(sharedPref.getFloat("3", 0));
list.add(sharedPref.getFloat("4", 0));
list.add(sharedPref.getFloat("5", 0));
if(max>list.get(0)){
list.remove(0);
list.add((float) max);
Collections.sort(list);
editor.putFloat("1", list.get(0));
editor.putFloat("2", list.get(1));
editor.putFloat("3", list.get(2));
editor.putFloat("4", list.get(3));
editor.putFloat("5", list.get(4));
editor.commit();
System.out.println(sharedPref.getFloat("5", 0)+" "
+sharedPref.getFloat("4", 0)+" "
+sharedPref.getFloat("3", 0)+" "
+sharedPref.getFloat("2", 0)+" "
+sharedPref.getFloat("1", 0));
}
}
}
public void onClickReset(View view){
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void onClickTopFive(View view){
Intent intent = new Intent(getApplicationContext(),TopFive.class);
startActivity(intent);
}
#Override
protected void onResume(){
super.onResume();
final ShakeOMeter sh = this;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
smngr.registerListener(sh, sen, SensorManager.SENSOR_DELAY_NORMAL);
}
},3000);
}
#Override
protected void onPause() {
super.onPause();
smngr.unregisterListener(this);
}
protected void onStop(){
super.onStop();
smngr.unregisterListener(this);
}
public void onDestroy(){
super.onDestroy();
smngr.unregisterListener(this);
finish();
}
}
TopFive.java (This is a sub Activity where top five activities are displayed)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class TopFive extends Activity {
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SharedPreferences sharedPref;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_five);
// Show the Up button in the action bar.
setupActionBar();
TextView t1 = (TextView) findViewById(R.id.T1);
TextView t2 = (TextView) findViewById(R.id.T2);
TextView t3 = (TextView) findViewById(R.id.T3);
TextView t4 = (TextView) findViewById(R.id.T4);
TextView t5 = (TextView) findViewById(R.id.T5);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
edit = sharedPref.edit();
t1.setText(ro(sharedPref.getFloat("1", 0))+"");
t2.setText(ro(sharedPref.getFloat("2", 0))+"");
t3.setText(ro(sharedPref.getFloat("3", 0))+"");
t4.setText(ro(sharedPref.getFloat("4", 0))+"");
t5.setText(ro(sharedPref.getFloat("5", 0))+"");
}
public void onClickReset(View view){
edit.putFloat("1", 0);edit.commit();
edit.putFloat("2", 0);edit.commit();
edit.putFloat("3", 0);edit.commit();
edit.putFloat("4", 0);edit.commit();
edit.putFloat("5", 0);edit.commit();
Intent intent = getIntent();
finish();
startActivity(intent);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.top_five, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Related
Pageviewer.java code:
//hide status bar/action bar on single tap
package com.app.imageswiper;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Pageviwer extends AppCompatActivity {
private Integer[] mImageIds = {R.drawable.page001, R.drawable.page002,
R.drawable.page003};
private static final String DEBUG_TAG = "pageviwer ";
ImageView imageView;
float startXValue = 1;
public int num;
public int click;
protected static final String TAG = "Pageviwer";
private GestureDetector mGestureDetector;
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
setContentView(R.layout.pageviwer);
imageView = (ImageView) findViewById(R.id.image_place_holder);
imageView.setImageResource(mImageIds[0]);
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
setupGestureDetector();
hideActionBar(); // hide action bar after 1 second
}
private void setupGestureDetector() {
mGestureDetector = new GestureDetector(this,
new GestureDetector.SimpleOnGestureListener() {
//Detecting Swipe/Fling Direction
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
Log.i(TAG, "onFling");
if (e1.getX() < e2.getX()) {
Log.d(TAG, "Left to Right swipe performed");
if (num == 2) {
num = num;
} else {
imageView.setImageResource(mImageIds[num + 1]);
num = num + 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
if (e1.getX() > e2.getX()) {
Log.d(TAG, "Right to Left swipe performed");
if (num == 0) {
num = num;
} else {
imageView.setImageResource(mImageIds[num - 1]);
num = num - 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
return true;
}
//detecting single tap
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.i(TAG, "onSingleTapUp");
Toast.makeText(getApplicationContext(), "Single Tap ", Toast.LENGTH_LONG).show();
//Remove notification bar and action bar
if (click == 0) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
//Return notification bar and action bar
else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().show();
click = 0;
}
return true;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
public void hideActionBar() {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// DO DELAYED STUFF
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
}, 1000); // 1000 milliseconds (1 second)
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == com.app.imageswiper.R.id.action_settings) {
Bookmark=1;
prefs.edit().putInt("Bookmark", Bookmark).commit();
prefs.edit().putInt("Pageno", num).commit();
Toast.makeText(getApplicationContext(), "Bookmark value is "+Bookmark, Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter code:
package com.app.imageswiper;
/**
* Created by Jaffer on 14-Apr-16.
*/
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class Bookmarks extends Fragment {
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
Button sendButton = null;
View inflatedView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
this.inflatedView = inflater.inflate(R.layout.bookmarks, container, false);
sendButton = (Button) inflatedView.findViewById(R.id.bookmark);
if(Bookmark==1){sendButton.setText("Page "+Pageno);}
else {sendButton.setText("No Bookmark ");}
if(sendButton == null)
{
Log.d("debugCheck", "HeadFrag: sendButton is null");
return inflatedView;
}
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Pageviwer.class);
startActivity(intent);
}
});
return inflatedView;
}
}
bookmarks.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/bookmarks">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/bookmark"
android:layout_alignParentBottom="true" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
</LinearLayout>
I don't know how to update the button text from Pageviewer.java for the button with R.id.bookmark that shows up on the Bookmarks fragment on the click of menu item R.id.action_settings. I want to do this so that the button text corresponds to the page that is being bookmarked. I tried alot of things but to no avail. Can someone please help me with anything?
Thanks in advance
Create a method in your fragment to update the text of your button.
public void updateText(String newText){
//assuming button is globally declared in your fragment.
button.setText(newText);
}
Instead of Gesture Detector you could use a ViewPager which supports swiping to the left and right.You can find a sample implementation here.
Then in your Activty,implement PageChanegListener on ViewPager.
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.You have to implement viewpager's adapter with getItem(index) which returns a fragment at that index.
BookMarkFragment fragment (BookMarkFragment)mAdapter.getItem(position);
fragment.updateText(newText);
};
});
You should save the state of a button somewhere. Your field int Bookmark == 0, so expression sendButton.setText("Page "+Pageno); never execute. Save the state in SharedPreferences and get this state. Like this:
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int isBookmark = prefs.getInt("Bookmark", 0);
int mPageno = prefs.getInt("Pageno", 0);
...
if(isBookmark == 1){
sendButton.setText("Page " + mPageno);
} else {
sendButton.setText("No Bookmark");
}
I'm working on a Android App and the layout and all the "android" specific stuff made a friend of my. I only was responsible for the "app" itself.
Nevertheless,
I would like to change some settings, e.g. change the server the stats produced by the app, should be transfered.
Here is the Settings.java:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
public class Settings extends Activity {
private Context mContext;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefEditor;
private EditText textName, textIP;
private RadioButton rdOnline, rdOffline;
private RadioGroup rdGroup;
private Button butSpeichern;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_settings);
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mPrefEditor = mPrefs.edit();
textName = (EditText) findViewById(R.id.txtBenutzer);
textIP = (EditText) findViewById(R.id.txtIP);
rdOffline = (RadioButton) findViewById(R.id.rdOffline);
rdOnline = (RadioButton) findViewById(R.id.rdOnline);
rdGroup = (RadioGroup) findViewById(R.id.radioDB);
butSpeichern = (Button) findViewById(R.id.btnSpeichern);
butSpeichern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveSettings();
}
});
//Online default an
rdOnline.setChecked(true);
rdOffline.setChecked(false);
loadSettings();
//ggf. Lan
System.out.println("online");
if(automatischLAN()){
setLan();
}
}
private void saveSettings()
{
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.putString("benutzer", textName.getText().toString());
mPrefEditor.putString("ip", textIP.getText().toString());
mPrefEditor.apply();
finish();
}
private void loadSettings() {
textName.setText(mPrefs.getString("benutzer", ""));
textIP.setText(mPrefs.getString("ip", "192.168.0.50"));
rdOnline.setChecked(mPrefs.getBoolean("onlineDB", true));
rdOffline.setChecked(!mPrefs.getBoolean("onlineDB", true));
}
public boolean automatischLAN(){
Calendar cal = new GregorianCalendar();
Date currenttimen = new Date();
cal.setTime(currenttimen);
int freitag = cal.get(Calendar.DAY_OF_WEEK);
int STUNDE = 0;
STUNDE = cal.get(Calendar.HOUR_OF_DAY);
System.out.println(STUNDE);
if(freitag == Calendar.FRIDAY && STUNDE>11 && STUNDE< 14 ) {
System.out.println("lan");
return false;
}
else {
System.out.println("online");
return true;
}
}
public void onBackPressed()
{
saveSettings();
super.onBackPressed();
}
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
}
}
I'm afraid my setLan() method isn't working as the values are not stored in the prefs...
What is the easieast way to check prefs and chance them on each start of the app?
Thanks for your help
You have to commit the changes in the SharedPreference.Editor variable. Replace your function above with the given one
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.apply();
}
I have one activity - Salary to which I want to pass values (numbers placed in EditTextPreference) from Preferences.
It looks like this:
ustawienia.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:title="Przepracowane godziny"
android:key="godziny"
android:summary="Wpisz przepracowane godziny"
/>
<EditTextPreference
android:title="Stawka Godzinowa"
android:key="stawka"
android:summary="Wpisz stawkę godzinową"
/>
<EditTextPreference
android:title="ZUS"
android:key="zus"
android:summary="Wpisz wielkość składki ZUS"
/>
</PreferenceScreen>
Then Preferences class - Ustawienia.java:
package com.example.salary;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Ustawienia extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.ustawienia);
}
}
Having that I want to take values from preferences to Salary.java class to use data.
package com.example.salary;
import java.text.DecimalFormat;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Salary extends Activity {
Button przelicz;
TextView brutto, na_czysto;
EditText netto;
SharedPreferences wez_ustawienia = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int godziny = wez_ustawienia.getInt("godziny", 21);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_salary);
przelicz = (Button)findViewById(R.id.b_przelicz);
na_czysto = (TextView) findViewById(R.id.tv_salary);
brutto = (TextView) findViewById(R.id.tv_brutto);
netto = (EditText) findViewById(R.id.et_netto);
przelicz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double netto_int = Double.valueOf(netto.getText().toString());
double kasa_brutto = netto_int * 0.25 + netto_int;
DecimalFormat formatowanie = new DecimalFormat("#0.00");
kasa_brutto = Double.valueOf(formatowanie.format(kasa_brutto));
brutto.setText("Kwota brutto: \t" + kasa_brutto);
double kasa_na_czysto = (netto_int - 1000);
//DecimalFormat formatowanie = new DecimalFormat("#0.00");
kasa_na_czysto = Double.valueOf(formatowanie.format(kasa_na_czysto));
na_czysto.setText("Kwota na czysto:\t" + kasa_na_czysto);
}
});
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater nadmuchanie = getMenuInflater();
nadmuchanie.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.oAutorze:
Intent a = new Intent("com.example.salary.OAUTORZE");
startActivity(a);
break;
case R.id.ustawienia:
Intent u = new Intent("com.example.salary.USTAWIENIA");
startActivity(u);
break;
case R.id.wyjscie:
finish();
break;
}
return false;
}
}
However the application crushes just after I added this piece of code:
SharedPreferences wez_ustawienia = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int godziny = wez_ustawienia.getInt("godziny", 21);
What's going on with that?
Can I be caused because addPreferencesFromResource(R.xml.ustawienia); is deprecated?
I'm trying to write code so that when the hints option is checked in settings it should display hints, but when I do s it says there is no getContext() method defined. What will this method do and where will i have to define this ?
Here is my code for the logic of my maths app:
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5 = ", "9"},
{"20 * 3 - 1 = ","59"},
{"99 - 9 = ","90"},
{"50 / 2 + 18 = ","43"},
{"9 * 8 = ","72"},
{"4 + 20 - 20 = ","4"},
{"75 / 5 = ","15"},
{"99 - 1 * 3 = ","96"},
{"75 + 25 = ","100"}};
TextView displayExpression;
TextView displayAnswer;
TextView setAnswer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
displayExpression = (TextView) findViewById(R.id.expression);
displayAnswer = (TextView) findViewById(R.id.answer_status);
setAnswer = (TextView) findViewById(R.id.answer);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(multiArray.length) ;
// Fetch your random question
String Rquestion = multiArray[random][0];
displayExpression.setText(Rquestion);
displayAnswer.setText("");
setAnswer.setText("?");
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
}
}
//xml attribute to views called android:onclick, that can be used to handle
//clicks directly in the view's activity without need to implement any interface.
public void hash_Clicked(View v){
// Get the Answer from your EditText
String answer = display.getText().toString();
setAnswer.setText(answer);
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayAnswer.setTextColor(getResources().getColor(R.color.green));
displayAnswer.setText("CORRECT");
break;
}else{
// Tell them how bad they are since they can't solve simple equations!
displayAnswer.setTextColor(getResources().getColor(R.color.red));
displayAnswer.setText("INCORRECT");
//this is where i am getting the error
if(Prefs.getHints(getContext())){
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.brain_game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.settings:
startActivity(new Intent(this,Prefs.class));
return true;
// more items go here if any
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And the Prefs class:
package com.gamesup.braingame;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.content.Context;
public class Prefs extends PreferenceActivity {
//option names and default values
private static final String OPT_HINTS = "hints";
private static final boolean OPT_HINTS_DEF = true;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
/**Get the current value of the hints option*/
public static boolean getHints (Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(OPT_HINTS, OPT_HINTS_DEF);
}
}
Just use this, you already are in an Activity, which is a Context:
if(Prefs.getHints(this)){
Don't need to use other context because if you are calling that function in your Activity then you just need to pass this or yourActivityName.this which are also Context.
So change
if(Prefs.getHints(this)){
or
if(Prefs.getHints(YourActivityName.this)){
Sorry about this guys. This must be like the third question I've had to ask about this project alone. =(
What i want to be able to do is toggle the visibility of a radio button using a check box in a preferences activity.
There are no errors in my code and both activities run fine, but there is no change in visibility when the check box is checked or unchecked.
Here is my Activity with the radiobuttons
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import com.medialets.android.analytics.MMAnalyticsManager;
public class Temperature extends Activity {
MMAnalyticsManager mManager;
private EditText text;
public void onStart(Bundle savedInstanceState){
super.onStart();
getPrefs();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.temperature);
text = (EditText)findViewById(R.id.EditText01);
mManager = MMAnalyticsManager.sharedInstance(this);
mManager.start("codeHere", "1.0",
false);
}
#Override
public void onPause() {
super.onPause();
mManager.pause();
}
#Override
public void onResume() {
super.onResume();
mManager.resume();
}
#Override
public void onDestroy() {
super.onDestroy();
mManager.stop();
}
public void myClickHandler(View view){
switch (view.getId()) {
case R.id.Button01:
RadioButton celsiustokelvinButton = (RadioButton) findViewById (R.id.RadioButton05);
RadioButton celsiustofarenheitButton = (RadioButton) findViewById(R.id.RadioButton01);
RadioButton farenheittocelsiusButton = (RadioButton) findViewById(R.id.RadioButton02);
RadioButton farenheittokelvinButton = (RadioButton) findViewById(R.id.RadioButton06);
RadioButton kelvintocelsiusButton = (RadioButton) findViewById (R.id.RadioButton03);
RadioButton kelvintofarenheitButton=(RadioButton) findViewById (R.id.RadioButton04);
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiustofarenheitButton.isChecked()) {
text.setText(String
.valueOf(convertCelsiusToFarenheit(inputValue)));
} if (farenheittocelsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFarenheitToCelsius(inputValue)));
} if (celsiustokelvinButton.isChecked()) {
text.setText(String
.valueOf(convertCelsiusToKelvin(inputValue)));
} if (farenheittokelvinButton.isChecked()) {
text.setText(String
.valueOf(convertFarenheitToKelvin(inputValue)));
} if (kelvintocelsiusButton.isChecked()) {
text.setText(String
.valueOf(convertKelvinToCelsius(inputValue)));
} if (kelvintofarenheitButton.isChecked()) {
text.setText(String
.valueOf(convertKelvinToFarenheit(inputValue)));
}
break;
}}
private float convertFarenheitToCelsius(float fahrenheit){
return ((fahrenheit - 32) * 5 / 9);
}
private float convertCelsiusToFarenheit(float celsius){
return ((celsius * 9) / 5) + 32;
}
private double convertCelsiusToKelvin(float celsius){
return celsius + 273.15;
}
private double convertFarenheitToKelvin(float farenheit){
return ((farenheit-32)/(1.8));
}
private double convertKelvinToCelsius(float kelvin){
return kelvin-273.1;
}
private double convertKelvinToFarenheit(float kelvin){
return kelvin*1.8-459.67;
}
boolean CheckboxPreference;
private void getPrefs() {
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
}
}
And here is my Preferences Activity
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class Preferences extends PreferenceActivity {
private RadioButton btn01;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
btn01 = (RadioButton)findViewById(R.id.RadioButton01);
Preference customPref = (Preference) findPreference("customPref");
customPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),"The Custom Preference Has Been Clicked",Toast.LENGTH_LONG).show();
SharedPreferences customSharedPreference = getSharedPreferences("myCutomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("myCustomPref","The preference has been clicked");
editor.commit();
CheckBox();
return true;
}
private void CheckBox() {
final CheckBox ThisCheckBox = (CheckBox) findViewById (R.id.checkboxPref);
ThisCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoundButton,boolean test) {
if (ThisCheckBox.isChecked()){
btn01.setVisibility(View.VISIBLE);
} else {
btn01.setVisibility(View.GONE);
}
}
});
};
});
}}
Sorry there is other stuff in there as well such as an analytics plug in
Anyone have any idea as to why this just isn't working
(Just a side note. When looking at the logcat, clicking the checkbox returned no results)
EDIT: OK i've just ammended my code as suggested but i'm afraid that the preferences still do not affect anything. Anybody have any ideas?? =(
It's not working because for visiblity the values you should use are (reference):
0 = VISIBLE
4 = INVISIBLE
8 = GONE