Passing from Preferences to Activity - android

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?

Related

How I can remove items of ListView?

The apk is a memo pad or something like that. First you can put the title and then the note and if you press the button "Save" the note is saved and it saves in database. And if you press the button "Notes", you can view a list with all notes saved in database and you can select all notes and in the top of screen, you can read how many notes are selected. Ok, it's fine but I need remove notes when the are selected and I press the button with bin icon in the top menu.
The code:
package com.example.u2tarea3;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AnotacionesOpenHelperSingleton extends SQLiteOpenHelper {
private static AnotacionesOpenHelperSingleton instancia = null;
private Context mCtx;
public static AnotacionesOpenHelperSingleton getInstance(Context ctx){
if(instancia == null){
instancia = new AnotacionesOpenHelperSingleton(ctx);
}
return instancia;
}
private AnotacionesOpenHelperSingleton(Context ctx) {
super(ctx,"anotaciones",null,2);
}
#Override
public void onCreate(SQLiteDatabase bd) {
StringBuilder sql = new StringBuilder();
sql.append("create table IF NOT EXISTS anotaciones (");
sql.append("_id integer primary key autoincrement,");
sql.append("texto text not null,");
sql.append("fecha text not null)");
bd.execSQL(sql.toString());
}
#Override
public void onUpgrade(SQLiteDatabase bd, int oldVersion, int newVersion) {
//bd.execSQL("drop table anotaciones");
bd.execSQL("ALTER TABLE anotaciones ADD titulo text");
bd.execSQL("UPDATE anotaciones SET titulo = 'sin titulo' WHERE titulo is NULL");
onCreate(bd);
}
}
package com.example.u2tarea3;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText editText;
EditText editTitulo;
Button btnGuardar;
Button btnAnotaciones;
SQLiteDatabase bd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton.getInstance(this);
bd = openHelperSingleton.getWritableDatabase();
editText = (EditText)findViewById(R.id.editText);
editTitulo = (EditText) findViewById(R.id.editTitulo);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnGuardar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
ContentValues valores = new ContentValues();
valores.put("texto", editText.getText().toString());
valores.put("fecha", sdf.format(c.getTime()));
valores.put("titulo", editTitulo.getText().toString());
bd.insert("anotaciones", null, valores);
editText.setText("");
}
});
btnAnotaciones = (Button) findViewById(R.id.btnAnotaciones);
btnAnotaciones.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ListAnotaciones.class);
startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
}
package com.example.u2tarea3;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ListAnotaciones extends ListActivity {
SQLiteDatabase bd;
Cursor cursor;
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton
.getInstance(this);
int cont = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelperSingleton.getReadableDatabase();
cursor = bd.rawQuery("SELECT * FROM anotaciones", null);
try {
String[] from = { "fecha", "titulo" };
int[] to = { R.id.anotacionesFecha, R.id.anotacionesTitulo };
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.anotacion, cursor, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
MenuInflater inflater = arg0.getMenuInflater();
inflater.inflate(R.menu.anotaciones, arg1);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch(arg1.getItemId()){
case R.id.delete_id:
//arg0.finish();
default:
break;
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
int seleccionados = getListView()
.getCheckedItemCount();
switch (seleccionados) {
case 1:
mode.setTitle("1 nota seleccionada");
break;
default:
mode.setTitle("" + seleccionados
+ " notas seleccionadas");
break;
}
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}
}
You'll need to remove the note from the database and the ListView, and then call ListViewAdapter.notifyDataSetChanged()
To delete from the datasource have a method in the class that deals with the datasource:
/**
* Delete a note given an id.
* #param id Key used to identify a note to delete.
*/
public void deleteNote(long id) {
System.out.println("Note deleted with id: " + id);
database.delete(ListOpenHelper.TABLE_MEMOS,
ListOpenHelper.ID + " = " + id,
null);
}
To refresh the ListView you could simply clear and re-add all the Views via the ListViewAdapter:
// Refresh adapter view with new data
ListAdapter.clear();
ListAdapter.addAll(dataSource.getAllNotes());
ListAdapter.notifyDataSetChanged();
Alternatively remove only a single element from the ListViewAdapter and call notifyDataSetChanged();.

Save preferences in android

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)){

New way of referencing deprecated xml prefrence

I work with preference xml file as options menu and i use it in my java class like bellwo
but the compiler says its deprecated and add a black line on addpreffrencefromresource(R.xml.mypreff). what is the new way of coding for it? thank you for helping.
package com.bestdiet;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
public class prefs extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.mypref);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
// return super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.exit:
finish();
break;
case R.id.help:
break;
case R.id.options:
break;
}
return false;
}
xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:title="پخش صدا"
android:defaultValue="true"
android:key="checkbox1"
/>
<CheckBoxPreference
android:title="پخش موسیقی"
android:defaultValue="true"
android:key="checkbox2"/>
</PreferenceScreen>
There is something notable: I just used the same xml preference layout...
But nobody tells you not to use two different files (say prefs_old.xml and prefs_new.xml), to add some of the new features to the (new) PreferenceFragment version of your PreferenceScreen.
This is my PreferenceActivity. It simply checks the build version to see which version of the preferences must be prepared:
package com.example.android.scheduler2;
/* ---------------------------------- Imports ------------------------------- */
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.ListView;
public final class ACT_Prefs
extends PreferenceActivity
implements OnSharedPreferenceChangeListener
{
/* ------------------------------ Objects ------------------------------- */
private Context ctx = null;
/* ----------------------------- Overrides ------------------------------ */
#Override
public final void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ctx = getApplicationContext();
if (Build.VERSION.SDK_INT < 11)
{
createPreference_Activity();
}
else
{
createPreference_Fragment();
}
}
#Override
protected void onPause()
{
// Unregister OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(ctx).
unregisterOnSharedPreferenceChangeListener(this);
// Call base method
super.onPause();
}
#Override
protected void onResume()
{
// Register OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(ctx).
registerOnSharedPreferenceChangeListener(this);
// Fire base method
super.onResume();
}
#Override
public void onSharedPreferenceChanged
(final SharedPreferences sharedPreferences, final String key)
{
// ... Do whatever you need to do here ...
System.out.println(key + " changed!!");
}
/* ------------------------------ Methods ------------------------------- */
//#SuppressWarnings("deprecation")
private final void createPreference_Activity()
{
addPreferencesFromResource(R.xml.prefs);
}
#SuppressLint("NewApi")
private final void createPreference_Fragment()
{
getFragmentManager().beginTransaction().replace
(android.R.id.content, new FRG_Prefs()).commit();
getFragmentManager().executePendingTransactions();
}
}
This is FRG_Prefs (the PreferenceFragment)
package com.example.android.scheduler2;
/* ---------------------------------- Imports ------------------------------- */
import android.annotation.SuppressLint;
import android.graphics.PixelFormat;
import android.preference.PreferenceFragment;
import android.view.View;
import android.widget.ListView;
#SuppressLint("NewApi")
public final class FRG_Prefs
extends PreferenceFragment
{
/* ----------------------------- Overrides ------------------------------ */
#Override
public final void onResume()
{
super.onResume();
addPreferencesFromResource(R.xml.prefs);
}
}

having multiple choice game that will calculate the score of the user but the system crush out

i have a sample android application that will display flag of coutry and multiple choice using radio button and each time the user check one of the answers the system will check if true and add 25 points to its score using intent to pass from activity to another with transferring the data mean the score until the user play 4 times to get to the end where the system will display his score .
until now i did the MainActivity that pass the data to the second but the problem is that the system force to close and in the log cat this what its display:
can anyone help me to solve this problem ????
logcat
11-27 22:15:53.609: E/AndroidRuntime(4834): Caused by: java.lang.NullPointerException
11-27 22:15:53.609: E/AndroidRuntime(4834): at com.devleb.flagology.SecondActivity.onCreate(SecondActivity.java:56)
MainActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnS;
RadioGroup rdgS;
RadioButton rdS1, rdS2, rdS3, rdS4;
private int score =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdgS = (RadioGroup) findViewById(R.id.rdg1);
rdgS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (rdS1.isChecked() || rdS2.isChecked() || rdS3.isChecked()
|| rdS4.isChecked()) {
btnS.setVisibility(View.VISIBLE);
}
}
});
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
i.putExtra("score", score);
break;
case R.id.rd_s2:
i.putExtra("score", score);
break;
case R.id.rd_s3:
i.putExtra("score", score + 25);
break;
case R.id.rd_s4:
i.putExtra("score", score);
break;
default:
break;
}
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.hint_icon:
ShowAlertDialog();
break;
case R.id.about_icon:
Toast.makeText(this, "developed by Georges Matta",
Toast.LENGTH_SHORT).show();
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void ShowAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hint")
.setMessage("The famouse sport is Bullfighting")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
SecondActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class SecondActivity extends Activity {
Button btnI;
RadioGroup rdgI;
RadioButton rdI1, rdI2, rdI3, rdI4;
// TextView txt_result;
private int score = 0;
int finalScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("score");
finalScore = score + value;
rdgI = (RadioGroup) findViewById(R.id.rdg2);
rdgI.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (rdI1.isChecked() || rdI2.isChecked()
|| rdI3.isChecked() || rdI4.isChecked()) {
btnI.setVisibility(View.VISIBLE);
}
}
});
rdI1 = (RadioButton) findViewById(R.id.rd_I1);
rdI2 = (RadioButton) findViewById(R.id.rd_I2);
rdI3 = (RadioButton) findViewById(R.id.rd_I3);
rdI4 = (RadioButton) findViewById(R.id.rd_I4);
btnI = (Button) findViewById(R.id.btn_s);
btnI.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(SecondActivity.this,
ThirdActivity.class);
switch (rdgI.getCheckedRadioButtonId()) {
case R.id.rd_I1:
i.putExtra("score", finalScore);
break;
case R.id.rd_I2:
i.putExtra("score", finalScore);
break;
case R.id.rd_I3:
i.putExtra("score", finalScore);
break;
case R.id.rd_I4:
i.putExtra("score", finalScore);
break;
default:
break;
}
startActivity(i);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
ThirdActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class ThirdActivity extends Activity {
TextView txt_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
txt_result = (TextView) findViewById(R.id.txtResult);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = String.valueOf(extras.getInt("score"));
txt_result.setText(value);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.third, menu);
return true;
}
}
I would venture to guess that your problem comes from this line:
btnS = (Button) findViewById(R.id.btn_s);
Most likely you made changes to your main activity layout (R.layout.activity_main) and either renamed or removed the <Button> element from it. If my guess is correct, then this line will fail to find the view in the inflated layout, and your btnS object will be null, leading to the actual exception you see.

Sensor Reading keeps increasing even after closing app, Android

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);
}
}

Categories

Resources