I am developing a java application. Its purpose is a program that calculates how many minutes you talk on the phone. However, when I start the chronometer when the phone is turned on, I cannot save the chronometer value as a string.
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Chronometer;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textOut;
TelephonyManager telephonyManager;
PhoneStateListener listener;
private Database database;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(MainActivity.this,servis.class));
textOut = (TextView) findViewById(R.id.textOut);
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
final Chronometer kronometre = findViewById(R.id.ch);
int süre = (int)(SystemClock.elapsedRealtime()-kronometre.getBase());
listener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
kronometre.stop();
Database db = new Database(getApplicationContext());
db.GelenArama("17.02.2023",süre,54);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
kronometre.start();
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
kronometre.setBase(SystemClock.elapsedRealtime());
break;
}
textOut.append(String.format("\nonCallStateChanged: %s",
stateString));
}
};
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
I got the stopwatch as an int but the recorded data was not what I wanted.
Related
I have a menu at the beginning of my application which allows the user to choose a specific type of diet, I want to save this as a string to use in another class which finds nearby restaurants,cafes,etc.
For example, if the user chooses the "Vegan" card, then I want to be able to use "Vegan" in other classes, but if it's "Kosher" I want to use the string "kosher" in other classes.
I tried creating a DietChoice class to set/get the diet but that doesn't work because I can't create a HomeMenu object in my MapsActivity class.
How can I make it so that when the user clicks the Vegan card, I can make it so that I can use a string "Vegan" in my MapsActivity class?
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
public class HomeMenu extends AppCompatActivity implements View.OnClickListener {
private CardView veganMenu,halalMenu,vegeterianMenu,kosherMenu;
private DietChoice diet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_menu);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
public void onClick(View v) {
Intent intent = new Intent(this,Home.class)
switch (v.getId()) {
case R.id.vegan_menu:
intent.putExtra("STRING_I_NEED", "vegan");
startActivity(intent);
break;
case R.id.vegetarian_menu:
intent.putExtra("STRING_I_NEED", "vegetarian");
startActivity(intent);
break;
case R.id.halal_menu:
intent.putExtra("STRING_I_NEED", "halal");
startActivity(intent);
break;
case R.id.kosher_menu:
intent.putExtra("STRING_I_NEED", "kosher");
startActivity(intent);
break;
}
Hello just putExtra with intent and extract it later on in your next Activity.No need of any Pojo.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
public class HomeMenu extends AppCompatActivity implements View.OnClickListener {
private CardView veganMenu,halalMenu,vegeterianMenu,kosherMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_menu);
getSupportActionBar().setDisplayShowHomeEnabled(true);
veganMenu = (CardView) findViewById(R.id.vegan_menu);
halalMenu = (CardView) findViewById(R.id.vegetarian_menu);
vegeterianMenu = (CardView) findViewById(R.id.halal_menu);
kosherMenu = (CardView) findViewById(R.id.kosher_menu);
veganMenu.setOnClickListener(this);
halalMenu.setOnClickListener(this);
vegeterianMenu.setOnClickListener(this);
kosherMenu.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = new Intent(this,Home.class)
switch (v.getId()) {
case R.id.vegan_menu:
intent.putExtra("STRING_I_NEED", "vegan");
startActivity(intent);
break;
case R.id.vegetarian_menu:
intent.putExtra("STRING_I_NEED", "vegetarian");
startActivity(intent);
break;
case R.id.halal_menu:
intent.putExtra("STRING_I_NEED", "halal");
startActivity(intent);
break;
case R.id.kosher_menu:
intent.putExtra("STRING_I_NEED", "kosher");
startActivity(intent);
break;
}
}
}
To Retrive the String in Home activity use below Code
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
I am loosely following a guide but I am using an onClickListener to start the search process. I am in the process of implementing a Loader here:
getSupportLoaderManager().restartLoader(0,queryBundle,this);
but when I put in ‘this’ it brings up the following message:
Wrong 3rd argument type. Found: 'android.view.View.OnClickListener', required: 'android.support.v4.app.LoaderManager.
LoaderCallbacks'
I am loathed to change from an onClickListener to a onClick method as the guide suggests, is there a way to implement the Loader in the onClickListener?
The code is below:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GoogleBookActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<String>{
private static final String TAG = GoogleBookActivity.class.getSimpleName();
private EditText mEditText;
private BookAdapter mAdapter;
private Button bookSearch;
private TextView mTitle, mAuthor;
//URL link to the API
private static final String GOOGLE_BOOKS_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_book);
mTitle = (TextView) findViewById(R.id.book_title);
mAuthor = (TextView) findViewById(R.id.book_author);
bookSearch = (Button) findViewById(R.id.searchbutton);
mEditText = (EditText) findViewById(R.id.search_text);
bookSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Initialise String queryText
String queryText = mEditText.getText().toString();
//For Hiding the keyboard when the search button is clicked
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromInputMethod(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
//For Checking the network status and empty search field case
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo !=null && networkInfo.isConnected() && queryText.length()!=0){
//new FetchBook(mTitle, mAuthor).execute(queryText);
}
Log.i(TAG, "Searched " + queryText);
if(queryText.length() != 0){
new FetchBook(mTitle, mAuthor).execute(queryText);
mAuthor.setText("");
mTitle.setText(R.string.loading);
//We replace the call to execute the fetchbook task with a call to restartLoader(), passing in
// the querystring you get from the EditText in the Bundle.
Bundle queryBundle = new Bundle();
queryBundle.putString("queryText", queryText);
getSupportLoaderManager().restartLoader(0,queryBundle,this);
}else {
if(queryText.length() == 0){
mAuthor.setText("");
mTitle.setText("Please enter a search term.");
}else{
mAuthor.setText("");
mTitle.setText("Please check your network connection and try again.");
}
}
}
});
}
#Override
public Loader<String> onCreateLoader(int i, Bundle bundle) {
return null;
}
#Override
public void onLoadFinished(Loader<String> loader, String s) {
}
#Override
public void onLoaderReset(Loader<String> loader) {
}
}
this refers to the encapsulating OnClickListener:
bookSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// You are now inside an anonymous class extending from
// OnClickListener. 'this' now refers to this very instance
// of the OnClickListener
}
});
In order to refer to the encapsulating GoogleBookActivity, just type that class name in front:
getSupportLoaderManager().restartLoader(0, queryBundle, GoogleBookActivity.this);
I'll do my best to explain my issue without a video
I have a login activity where upon successful login, the EditText and Button fields fade out and a "logging in" TextView fades in (using Facebook Shimmer). This works great!! However, upon successfully login we are greeted by a blank activity (still fine). Now, I overwrote the back button so that when the back button is pressed, the user is forced to login again. My problem arises with the user hits the login button at this time. The Edit Text and Button elements fade out nicely but the "logging in" TextView never fades in.
Below are some picture examples. I will also post the source code for LoginActivity.class and if you want to download the project it is available at: git#github.com:fbgrecojr/Android-Application-Login-Activity-Template.git
If you download the project, username: testuser and password: testpass will work.
Images:
Initial Login (working)
Login Attempt after pressing the back button and then logging in again (which I overwrote to restart the intent)
LoginActivity.class
package com.projects.fbgrecojr.logintemplate.UI;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.projects.fbgrecojr.logintemplate.HTTPManager.HttpManager;
import com.projects.fbgrecojr.logintemplate.HTTPManager.RequestPackage;
import com.projects.fbgrecojr.logintemplate.Parser.JSONParser;
import com.projects.fbgrecojr.logintemplate.R;
import com.projects.fbgrecojr.logintemplate.Session.Session;
import com.projects.fbgrecojr.logintemplate.Structures.User;
import com.projects.fbgrecojr.logintemplate.Utility.UTILITY;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private EditText userName, password;
private Button login;
private RelativeLayout image;
private LinearLayout button, belowPic;
private Animation fadeInImage, fadeInButton, bottomUp, fadeOut;
private TextInputLayout inputLayoutName,inputLayoutPassword;
private ViewGroup hiddenPanel;
private ShimmerFrameLayout container, loggingIn;
private static final int SECOND = 1000;
private static final int HALF_SECOND = 500;
private static final int QUARTER_SECOND = 250;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//INITIALIZE ANIMATION ITEMS
fadeInImage = new AlphaAnimation(0, 1);
fadeInButton = new AlphaAnimation(0, 1);
fadeOut = new AlphaAnimation(1.0f,0.0f);
bottomUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bottom_up_animation);
fadeInImage.setInterpolator(new AccelerateInterpolator()); //and this
bottomUp.setInterpolator(new DecelerateInterpolator());
//GET UI ELEMENTS
userName = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
image = (RelativeLayout) findViewById(R.id.image);
button = (LinearLayout) findViewById(R.id.button);
container = (ShimmerFrameLayout) findViewById(R.id.shimmer);
belowPic = (LinearLayout) findViewById(R.id.below_picture);
loggingIn = (com.facebook.shimmer.ShimmerFrameLayout) findViewById(R.id.login_shimmer);
hiddenPanel = (ViewGroup)findViewById(R.id.input);
inputLayoutName = (TextInputLayout) findViewById(R.id.text_input_username);
inputLayoutPassword = (TextInputLayout) findViewById(R.id.text_input_password);
//SET UI PROPERTIES
loggingIn.setVisibility(View.INVISIBLE);
userName.setCursorVisible(false);
password.setCursorVisible(false);
password.setHint("Password");
userName.setHint("Username");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
userName.setCursorVisible(true);
password.setCursorVisible(true);
userName.requestFocus();
}
}, LoginActivity.SECOND * 3);
//ANIMATIONS
fadeInImage.setDuration(SECOND * 3);
fadeOut.setStartOffset(SECOND);
fadeOut.setDuration(SECOND);
image.setAnimation(fadeInImage);
fadeInButton.setStartOffset(SECOND + HALF_SECOND + QUARTER_SECOND);
fadeInButton.setDuration(SECOND * 2);
button.setAnimation(fadeInButton);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
container.setDuration(SECOND * 2 + QUARTER_SECOND);
container.setRepeatDelay(QUARTER_SECOND);
container.setIntensity((float) 0.15);
container.setBaseAlpha((float) 0.75);
container.setFadingEdgeLength(3);
container.setDropoff((float) 0.40);
container.startShimmerAnimation();
//ON CLICK LISTENERS
login.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
if(getUserName().getText().toString().equals("") || getUserName().getText().toString().equals(" ")) {
inputLayoutName.setError("enter username");
}else if(getPassword().getText().toString().equals("") || getPassword().getText().toString().equals(" ")){
inputLayoutPassword.setError("enter password");
}else{
//webservice
if (UTILITY.isOnline(getApplicationContext())) {
RequestPackage p = new RequestPackage();
p.setMethod("GET");
p.setUri(UTILITY.UBUNTU_SERVER_URL);
p.setParam("query", "user");
p.setParam("username", getUserName().getText().toString());
new WebserviceCallOne().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, p);
} else {
Toast.makeText(getApplicationContext(), "you are not connected to the internet", Toast.LENGTH_LONG).show();
}
}
break;
}
}
private void animateExit() {
//fade out annimation
belowPic.startAnimation(fadeOut);
belowPic.setVisibility(View.INVISIBLE);
fadeInImage.setStartOffset(SECOND * 2);
fadeInImage.setDuration(HALF_SECOND);
loggingIn.startAnimation(fadeInImage);
loggingIn.setVisibility(View.VISIBLE);
loggingIn.setDuration(SECOND);
loggingIn.startShimmerAnimation();
}
public EditText getPassword() {
return password;
}
public EditText getUserName() {
return userName;
}
private class WebserviceCallOne extends AsyncTask<RequestPackage, String, User> {
#Override
protected User doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return JSONParser.parseUserFeed(content);
}
#Override
protected void onPostExecute(User s) {
Session.setCurrentUser(s);
//if null, error stacktrace will print to the log. This is expected!!
if(Session.getCurrentUser() == null){ //username was incorrect
inputLayoutName.setError("username does not exist");
}else{ //check password
if(getPassword().getText().toString().equals(s.getPassword())){ //passwords match
animateExit();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
},LoginActivity.SECOND * 4);
}else{
inputLayoutPassword.setError("password incorrect");
}
}
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
#Override
public void onBackPressed() {
startActivity(new Intent(this, LoginActivity.class));
}
}
You have to call animateExit(); code in onResume methord
#Override
public void onResume() {
super.onResume();
animateExit();
}
override onResume() in your Activity.
try starting your animation in onresume.
override onPause() in your Activity
try stopping your animation in onPause.
Hope this Helps :)
I have this problem accessing an extra from an intent.
The value i'm parsing is a long type, and I need this value to be stored in a database.
So this is what I have so far:
MainActivity:
package com.example.calendar;
import java.sql.Date;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CalendarView;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import static com.example.calendar.Constants.DATE;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends Activity implements OnClickListener {
private AppointmentsData appointments;
CalendarView calendar;
Date date = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View createButton = findViewById(R.id.btn_create);
View editButton = findViewById(R.id.btn_viewEdit);
View deleteButton = findViewById(R.id.btn_delete);
View moveButton = findViewById(R.id.btn_move);
View searchButton = findViewById(R.id.btn_search);
View translateButton = findViewById(R.id.btn_translate);
View exitButton = findViewById(R.id.exit);
createButton.setOnClickListener(this);
editButton.setOnClickListener(this);
deleteButton.setOnClickListener(this);
moveButton.setOnClickListener(this);
searchButton.setOnClickListener(this);
translateButton.setOnClickListener(this);
exitButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
date = new Date(year, month, dayOfMonth);
}
});
}
#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 void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.btn_create:
i = new Intent(this, CreateAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_viewEdit:
i = new Intent(this, EditViewAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_move:
i = new Intent(this, MoveAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_delete:
i = new Intent(this, DeleteAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.btn_search:
i = new Intent(this, SearchAppointment.class);
startActivity(i);
break;
case R.id.btn_translate:
i = new Intent(this, TranslateAppointment.class);
i.putExtra(DATE, date.getTime());
startActivity(i);
break;
case R.id.exit:
finish();
break;
}
}
}
And the other Activity to use the value:
package com.example.calendar;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import static com.example.calendar.Constants.DATE;
import static com.example.calendar.Constants.CONTENT_URI;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class CreateAppointment extends Activity implements OnClickListener{
private static String[] FROM = { _ID, DATE, TIME, TITLE, DETAILS};
private static String ORDER_BY = TIME + " ASC";
AppointmentsData appointments;
CalendarView calendar;
String string;
EditText nameTextBox;
EditText timeTextBox;
EditText detailsTextBox;
Button createButton;
SQLiteDatabase db;
Intent fetchDate = getIntent();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
createButton = (Button) findViewById(R.id.apptSave);
nameTextBox = (EditText)findViewById(R.id.apptName);//Assign the global name box
timeTextBox = (EditText)findViewById(R.id.apptTime);//Assign the global time box
detailsTextBox = (EditText)findViewById(R.id.apptDetails);//Assign the global details box
calendar = (CalendarView)findViewById(R.id.calendar);
createButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
string = "row";
long dateFecth = fetchDate.getLongExtra(DATE, defaultValue);
}
private void addAppointment(String string) {
/* Insert a new record into the Events data
source. You would do something similar
for delete and update. */
String getTitle = nameTextBox.getText().toString();
String getTime = timeTextBox.getText().toString();
String getDetails = detailsTextBox.getText().toString();
db = appointments.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DATE, calendar.getDate());
values.put(TIME, getTime);
values.put(TITLE, getTitle);
values.put(DETAILS, getDetails);
getContentResolver().insert(CONTENT_URI, values);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.apptSave:
addAppointment(string);
finish();
break;
}
}
}
The error is on the long dateFecth = fetchDate.getLongExtra(DATE, defaultValue); line and I don't know what to use for the second argument, since everything I think of gives me an error.
Can someone please help me with this?
Move fetchDate = getIntent(); inside onCreate method of Activity as:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
//.your code here..
fetchDate = getIntent(); // get intent here from previous Activity
long dateFecth = fetchDate.getLongExtra(DATE, defaultValue);
}
First check - Value is associated with the given name.
if you don't want to use defaultValue try with bundle as follow
if (getchDate.hasExtra("Date")) {
Bundle bundle = new Bundle();
bundle = getchDate.getExtras();
Object object = bunlde.get(Date);
Now parse this object in your desire type.
}
You should check if result of getIntent() is not empty at first (an of course the call should be inside onCreate, not constructor). If it's not empty, then get long variable from it. defaultValue stands for a value returned from a method if a value for specified key is not found.
I have a SharedPreference in this .java File; towards the bottom you can see I save the values to the SharedPreferences GB_PREFERENCES_BENCH, and GB_PREFERENCES_FLIES. How do I use these values in another activity? See the second code example for how I want to use it.
package com.creativecoders.gymbuddy;
import com.creativecoders.gymbuddy.R;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class Benchmark extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_BENCH = "Bench";
public static final String GB_PREFERENCES_FLIES = "Flies";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_benchmark);
gBValues = getSharedPreferences(GB_PREFERENCES, Context.MODE_PRIVATE);
}
public void onStart() {
super.onStart();
findViewById(R.id.button5).setOnClickListener(new handleButton5());
}
class handleButton5 implements OnClickListener {
public void onClick(View v) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
String sWeight = editText1.getText().toString();
final double dWeight = Double.parseDouble(sWeight);
EditText editText2 = (EditText)findViewById(R.id.editText2);
String sPush = editText2.getText().toString();
final double dPush = Double.parseDouble(sPush);
EditText editText3 = (EditText)findViewById(R.id.editText3);
String sSit = editText3.getText().toString();
final double dSit = Double.parseDouble(sSit);
EditText editText4 = (EditText)findViewById(R.id.editText4);
String sPull = editText4.getText().toString();
final double dPull = Double.parseDouble(sPull);
double dBench = (((Math.floor(dWeight*.0664))*10)-10)+dPush;
double dFlies = (Math.floor(((Math.floor(dBench*.6)/10)*10)));
int iBench = (int)dBench;
int iFlies = (int)dFlies;
Editor editor1 = gBValues.edit();
editor1.putInt(GB_PREFERENCES_BENCH, iBench);
editor1.commit();
Editor editor2 = gBValues.edit();
editor2.putInt(GB_PREFERENCES_FLIES, iFlies);
editor2.commit();
}
}
}
Here is how I want to use it; (specifically in the on create method to set a TextView's text to the value in the SharePreference)
package com.creativecoders.gymbuddy;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Upper100Start extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_CURLS = "Curls";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upper100start);
if (gBValues.contains(GB_PREFERENCES_CURLS)){
TextView TextView2 = (TextView)findViewById(R.id.textView2);
TextView2.setText(gBValues.getString(GB_PREFERENCES_CURLS, ""));
}
}
public void onStart() {
super.onStart();
findViewById(R.id.button2).setOnClickListener(new handleButton2());
findViewById(R.id.button3).setOnClickListener(new handleButton3());
}
class handleButton2 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Upper101.class);
startActivity(intent);
}
}
class handleButton3 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Main.class);
startActivity(intent);
}
}
}
The shared preferences are accessible throughout your application, so you can read them from any activity in the application.
Storing a key/value pair in activity A:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mystring", "wahay");
editor.commit();
Reading this value from another activity:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
String myString = settings.getString("mystring", "defaultvalue");
You can find more information at http://developer.android.com/guide/topics/data/data-storage.html#pref