[Q] How to implement sharedpreferences in the app? - Java for Android App Development

Hi!
I am trying to implement an settings menu in my app.
I tried to do by this guide, but it confused me: http://stackoverflow.com/questions/6800244/android-how-to-save-the-state-of-a-checkbox
I want to save a state of only 1 checkbox.
I am trying to make settings menu in the different layout than my main activity one.
Any help is appriciated. Thank You!

First, make sure your CheckBox have an ID.
Second, findViewById to your CheckBox.
Code:
CheckBox check = (CheckBox) findViewById(R.id.check);
Init your SharedPreferences on your onCreate
Code:
SharedPreferences settings = getSharedPreferences("yourappnameorwhatevernameyouwant", 0);
SharedPreferences.Editor editor = settings.edit();
Then save you state of CheckBox
Code:
boolean checkBoxValue = check.isChecked();
editor.putBoolean("CheckBoxValue", checkBoxValue);
editor.commit();
That's it.
And if you want to load the value. <--- this will make the CheckBox checked or unchecked upon opening the app.
Code:
check.setChecked(settings.getBoolean("CheckBoxValue", false));

If you want a more secure (but slower) sharedpreferences, you can implement your own class like this:
(This is an example to put-get a string)
Code:
public class MySharedPreferences implements SharedPreferences {
public MySharedPreferences (Context context, SharedPreferences delegate) {
this.delegate = delegate;
this.context = context;
}
public class Editor implements SharedPreferences.Editor {
protected SharedPreferences.Editor delegate;
public Editor() {
this.delegate = MySharedPreferences.this.delegate.edit();
}
public Editor putString(String key, String value) {
delegate.putString(key, encrypt(value));
return this;
}
public void apply() {
((Editor) delegate).apply();
}
public Editor clear() {
delegate.clear();
return this;
}
public boolean commit() {
return delegate.commit();
}
public Editor remove(String s) {
delegate.remove(s);
return this;
}
}
public String getString(String key, String defValue) {
final String v = delegate.getString(key, null);
return v != null ? decrypt(v) : defValue;
}
public boolean contains(String s) {
return delegate.contains(s);
}
protected String encrypt( String value ) {
//here you use your algorithm to encrypt
return value;
}
protected String decrypt(String value){
//here you use your algorithm to encrypt
return value;
}
}

Use Prefrence apis
frenzyboi said:
First, make sure your CheckBox have an ID.
Second, findViewById to your CheckBox.
Code:
CheckBox check = (CheckBox) findViewById(R.id.check);
Init your SharedPreferences on your onCreate
Code:
SharedPreferences settings = getSharedPreferences("yourappnameorwhatevernameyouwant", 0);
SharedPreferences.Editor editor = settings.edit();
Then save you state of CheckBox
Code:
boolean checkBoxValue = check.isChecked();
editor.putBoolean("CheckBoxValue", checkBoxValue);
editor.commit();
That's it.
And if you want to load the value. <--- this will make the CheckBox checked or unchecked upon opening the app.
Code:
check.setChecked(settings.getBoolean("CheckBoxValue", false));
Click to expand...
Click to collapse
SharedPrefrences are best impilmented by the prefrence apis.
check out Prefrences
Most Effective and simplest way to do it in my opinion

sak-venom1997 said:
SharedPrefrences are best impilmented by the prefrence apis.
check out Prefrences
Most Effective and simplest way to do it in my opinion
Click to expand...
Click to collapse
IMO, you could confuss a reader with that statement.
If you want to create a settings activity where the user can configure the behaviour of the app, then you should go for Preference API. It helps you building the interface and it internally uses SharedPreference to save the state of the parameters.
However, if you just want to save the value of any parameter at any point of your application flow that is outside the Settings activity, you should make use of SharedPreference to store those values as frenzyboi explained.
As shown, Preference and SharedPreference are two different things.

patedit said:
IMO, you could confuss a reader with that statement.
If you want to create a settings activity where the user can configure the behaviour of the app, then you should go for Preference API. It helps you building the interface and it internally uses SharedPreference to save the state of the parameters.
However, if you just want to save the value of any parameter at any point of your application flow that is outside the Settings activity, you should make use of SharedPreference to store those values as frenzyboi explained.
As shown, Preference and SharedPreference are two different things.
Click to expand...
Click to collapse
I had no intention to confuse the op the op wanted a checkbox right?
I wanted to say is that if a prefrence is used it would be easy to manage shared prefrence if theres only the checkbox

sak-venom1997 said:
I had no intention to confuse the op the op wanted a checkbox right?
I wanted to say is that if a prefrence is used it would be easy to manage shared prefrence if theres only the checkbox
Click to expand...
Click to collapse
:good:
U are right man. its pretty good way is to learn those basic aspect.
Preference activiities also doing the same. But it provide all those things in handy manner..
U can use read those data using shared preference and also change those setting by chnaging the data from elsewere
So sharedPreference and PreferenceActivity are Same

CoolMonster said:
So sharedPreference and PreferenceActivity are Same
Click to expand...
Click to collapse
PreferenceActivity is a class that extends ListActivity.
SharedPrefence is an interface to handle preferences.
They have nothing to do.
Neither Preference and SharedPreference are the same, thou both of them can be used for what the user asked.

Related

Help writing something with setOnItemClickListener

In my Android app, I have a sound that I want to play when a certain selection has been made from a spinner, but I want it to play the when the user actually makes the proper selection (or just after). My problem is that although the sound does play when they make the correct selection, as long as that selection stays chosen, it also plays every time the app starts up, when it should ONLY play at the time it's chosen. I think I need to change my setOnItemSelectedListener to setOnItemClickListener, but I'm not sure how (still pretty new to java). Can any generous soul out there show me how to change this up (assuming that's how to best solve this problem)?
Here is the code I have now:
Code:
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(
this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.bowchica);
mp.start();
} if(position == 4) {
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.debbie2);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I haven't try the below code but you can try it on your own and tell us.
In onCreate() declare MediaPlayer mp;
In every if statement that you use for check insert this code:
Code:
if(mp!=null){mp.release();}
int resid = R.raw.yoursound;
mp = MediaPlayer.create(this, resid);
After that override the methods onPause() and onResume() and insert this:
if(mp!=null){mp.release();}
If it is still playing a sound when you start your app, then you should check your code again if you have set as default option any of your selection options.
I would LOVE to try this out...Unfortunately, I'm way too dumb at this point point ot figure out exactly where those code snippets would go inside of what I already have.
Does anyone have a couple of minutes to show me where it would go?
Below is a sample code. Since i don't know your code I give you a snippet that you should adjust it to your code.
Code:
public class SampleSound extends Activity{
private Spinner fitnessSpinner;
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//here goes your layout
setViews();//here you will set all your views(spinners buttons textviews etc..)
setAdapters();//set your adapters here
setListeners();//
}
private void setListeners() {
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
if(mp!=null){mp.release();}
int resid = R.raw.bowchica;
mp = MediaPlayer.create(this, resid);
mp.start();
} if(position == 4) {
if(mp!=null){mp.release();}
int resid = R.raw.debbie2;
mp = MediaPlayer.create(this, resid);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void setAdapters() {
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
}
private void setViews() {
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
}
public void onResume(){
super.onResume();
if(mp!=null){mp.release();}
}
public void onPause(){
super.onPause();
if(mp!=null){mp.release();}
}
}
I really appreciate the help. I put the code in my routine, but it still plays the sound every time the activity is loaded (as long as the selection in the spinner is correct). It should only play the sound when the correct selection is made.
Any other ideas?
I am sure that your Spinner is set to some value (since you have values to display). Because your Spinner points to a selection (doesn't matter if you have selected or it is selected by default) your sound plays (even when you start the app).
A way to stop the sound playing at start is to declare and an other Item like you did with the previous 4 and set it as default selection of your Spinner.
To sum up:
1.You have to append in R.array.fitness_array an Item (like you did with the previous Items) and give it a name.
2.At the end of method setAdapters() insert this:
Code:
fitnessSpiner.setSelection(5);// or whatever is your selection number
Now it should work but you should know that this is not a good practice and you should try make a ListView or something else.
I'd be happy to change this out to a listview, or whatever would work. I just have to give my user a choice of 4 or 5 items, from which they can choose only one. Something like a drop down box, but in Android, I thought my only option was a spinner. But whatever I use, I have to be able to play a sound when certain items are chosen, but ONLY when those items are chosen, NOT whenever the activity is called up.
Any specific ideas of what I might change to?
What if I had another control like a textview or an edittext (with it's visibility property set to false) that I programatically populated with the users selection (when it's the selection that I want) and then have an OnItemClcickListener set to play the sound?
Could that work?
I will answer from the last to the top of your questions.
1.You can do whatever you want with android. You want TextViews and EditTexts with complex and nested Layouts you can do it. Write services that will communicate with your contacts through a content provider? You can do it.
Write, read and test code. Only this way you will actually learn.
2.Read developer.android.com. Read the android tutorials from there and specifically the Notepad example. You will learn a lot.
A good resource with small examples for ListViews is this.
3.Have you tried the changes I told you from the last post? Did it worked?
Since you just started with android and programming you must first be happy if you have the expected result and then read more to make your code better
Your suggested changes (fitnessSpiner.setSelection(5);// or whatever is your selection number) would stop the sound from playing, but defeat the apps purpose. Every time this activity is loaded, the spinners hit preferences to load the previously stored data. So if I force the spinner to a different selection to NOT play sound when the activity loads, then I would be displaying the wrong data for the user.
Yes you are right. So it is better to make a ListActivity. Read developer.android.com and the link i gave you before. You will be ok with this!
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Lakers16 said:
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Click to expand...
Click to collapse
onClickListener doesn't work for the spinner...I wish it did.
I REALLY need the drop down functionality of teh spinner, so I guess I'm going to try and figure out a way to have an invisible edittext that I set to the spinner selection and then use onClickListener or onChange...

Settings.System strings location

Hi, I'm building CM 9 from source. I'm adding some features. I need to add a string to the class settings because I want to store a preference. It's just a simple checkbox.
I've seen at https://github.com/CyanogenMod/andr...android/settings/cyanogenmod/PowerWidget.java that I have to assign the value 0 or 1.
This is the method I'm interested in:
Code:
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mPowerWidgetHapticFeedback) {
int intValue = Integer.parseInt((String) newValue);
Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(),
Settings.System.EXPANDED_HAPTIC_FEEDBACK, intValue);
return true;
}
return false;
}
It's exactly what I want to do, but I need to add a string to Setting.System, for example Settings.System.X_Y_Z, Where do I have to write X_Y_Z? I know there is a class called Settings that has written all these strings, but it's in the "out" folder and the settings app doesn't compile beacuse the variable X_Y_Z can not be found. Anybody knows where should I add the string X_Y_Z?
EDIT: Solved.

Preference changes only happen when restarting the app

Hey there! I was coding an app I added a preferences menu, and it works, but changes happen only when I restart the application,anyone knows how to make changes happen whithout exitting the app??? Thanks in advance
My code ( from main activity):
preferencias = preferenceManager.getDefaultSharedPreferences(TimeToSpeechActivity.this);
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
//nothing here, do I have to put anything?
}
};
preferencias.registerOnSharedPreferenceChangeListener(listener);
getPrefs();
changefont(fuente, letra);
if (boole == true) {fontcolors();}
private void getPrefs(){
fuente = Typeface.createFromAsset(getAssets() , preferencias.getString("elegirfuente", "fonts/Default.ttf"));
letra = Integer.parseInt(preferencias.getString("fontstyle", "0"));
bol = preferencias.getBoolean("randomcolors", true);
}
Click to expand...
Click to collapse
I have nothing put in preference activity, do i have to put anything?
Also, do I have to edit this?: (SharedPreferences prefs, String key) I ask this because i havent created prefs and key varibles
Thanks in advance!!!
It should update for you if you put getPrefs() inside the sharedpreferences listener
Sent from my Xoom using xda premium
thanks, but if I do that I get a nullpointer exception, I think its caused because the params I use to set "changefont(fuente, letra);" and "if (boole == true) {fontcolors();}" have null value....another idea ,please? I am breaking my head with this...
My updated code:
preferencias = preferenceManager.getDefaultSharedPreferences(Time ToSpeechActivity.this);
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener () {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
getPrefs();
}
};
preferencias.registerOnSharedPreferenceChangeListener(listener);
changefont(fuente, letra);
if (boole == true) {fontcolors();}
private void getPrefs(){
fuente = Typeface.createFromAsset(getAssets() , preferencias.getString("elegirfuente", "fonts/Default.ttf"));
letra = Integer.parseInt(preferencias.getString("fontstyle ", "0"));
bol = preferencias.getBoolean("randomcolors", true);
}
Click to expand...
Click to collapse
i tried to put changefont and fontcolors functions inside the sharedpreference listener... but if i do, that options are not set... so I think there is a problem with the listener...why???
I will add the code of my preference class:
public class PantallaOpciones extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.opciones);
}
}
Click to expand...
Click to collapse
One way ive always done preference updates was to use a dedicated method for updating (like you have with openPrefs()) then calling it after operations:
runOperation(){
updatePrefsMethod();
getPrefsMethod();
}
If i was near my pc i could give you a more solid example, but alas, im stuck at work lol
Also, use the stacktraces to check which line gives it null (itll say something like "at com.yourapp.identifier(offending Class - line number)
maybe if you a null check on the boolean for color that sets it false, you may not get the nullPointerException
Sent from my Xoom using xda premium
z3nful said:
One way ive always done preference updates was to use a dedicated method for updating (like you have with openPrefs()) then calling it after operations:
runOperation(){
updatePrefsMethod();
getPrefsMethod();
}
If i was near my pc i could give you a more solid example, but alas, im stuck at work lol
Also, maybe if you a null check on the boolean for color that sets it false, you may not get the nullPointerException
Sent from my Xoom using xda premium
Click to expand...
Click to collapse
OK, could you give me an example as soon as you can,please?

[Q] Parsing XML from web into ListView

Hey guys,
I've been making an app for my ROM (SkyDragon) and I want to include a news section, which will retrieve info from the web using a XML file.
But, I've tried many things and they won't work. So could anyone post a quick working parsing code here that will put the items in a listview, so I can experiment a bit with it? It'd be widely appreciated
I might reccommend using a library like Jackson 2.0+. I have not had the experience to use it with XML, but rather JSON, but it does appear to be just as easy to do so (at least since 2.0).
You would set up a POJO (Plain Old Java Object) class to represent the structure of the xml data, for instance:
Code:
public class Simple
{
private int x, y;
public int getX(){ return x; }
public int getY(){ return y; }
public void setX(int x){ this.x = x; }
public void setY(int y){ this.y = y; }
}
would represent xml like:
Code:
<Simple>
<x>1</x>
<y>2</y>
</Simple>
and to build the object you would use the library as such:
Code:
ObjectMapper xmlMapper = new XmlMapper();
Simple value = xmlMapper.readValue("<Simple><x>1</x><y>2</y></Simple>", Simple.class);
Thanks, will try it. But it can't be that simple, right? I mean, every tutorial is pretty big, and uses multiple activities.
Sent from my awesome fridge
Well like I said, I haven't actually used it for XML but rather JSON, but it really was that simple for me. What I listed is of course a very simple example, but scaling it up really just requires mapping your xml source to a POJO. The hardest part about your use will be that you don't control the XML.
Here is an example right out of a project of mine that worked great. "request.result" was basically a String object that contained the JSON response from a restful web service that I did not control but knew the structure of (by examination). Truly it is just these 2 lines of code to parse the response and after that you have an object that is easy to use.
Code:
ObjectMapper mapper = new ObjectMapper();
inventory = mapper.readValue(request.result, PlayerInventory.class);
Unfortunately this service no longer exists so I cannot get you an example response, but below is the POJO that I used to map it.
Code:
package com.mcdermotsoft;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PlayerInventory
{
private int ok;
private Map<String,Slot> contents;
public PlayerInventory(){}
public int getOk() {
return ok;
}
public Map<String,Slot> getContents() {
return contents;
}
public void setOk(int ok) {
this.ok = ok;
}
public void setContents(Map<String,Slot> contents) {
this.contents = contents;
}
}
"@JsonIgnoreProperties(ignoreUnknown = true)" is important because I really didn't care to map everything from the response so this annotation tells the Jackson parser to ignore anything it can't map instead of throwing an exception (don't remember what the exception is but you might run into it yourself).

Android/Java Newbie

Hi all, im having a go at developing a simple app. i have little experience with Java and Android development. i have a little test app at the moment and have created a new class, im trying to create a new instance of this class on a button click. it fails to do so, i cant for the life of me see why so.. can someone shed any light on this?
Thanks
Debuging this shows it hitting the "LocationFactory locationf = new LocationFactory();" line and throwing an exception-
"java.lang.NullPointerException"
Main
Code:
package com.example.testapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private static final Context Context = null;
protected static final String TAG = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
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;
}
public void mainButton(View view) throws IOException {
try {
LocationFactory locationf = new LocationFactory();
Toast.makeText(this, locationf.getAddress(),Toast.LENGTH_LONG).show();
} catch (Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Class
Code:
package com.example.testapp;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import java.io.IOException;
import java.util.Locale;
import java.util.List;
public class LocationFactory
{
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory()
{
}
public String getAddress() throws IOException
{
String ReturnAddress = "";
String Address = "", City = "", Country = "";
List<Address> addresses = null;
if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
// Use GPS Radio Location
Location GPSlocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Latitude = GPSlocation.getLatitude();
Longitude = GPSlocation.getLongitude();
}
else
{
// Use Cell Tower Location
Location NETlocation = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Latitude = NETlocation.getLatitude();
Longitude = NETlocation.getLongitude();
}
if(Latitude > 0 && Longitude > 0)
{
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
if(!addresses.isEmpty())
{
Address = addresses.get(0).getAddressLine(0);
City = addresses.get(0).getAddressLine(1);
Country = addresses.get(0).getAddressLine(2);
}
}
ReturnAddress = Address + " " + City + " " + Country;
return ReturnAddress;
}
}
I don't see anywhere in your code where you are calling the mainButton(View view) method. In the Android lifecycle, the onCreate method is the equivalent of a normal Java program's main() method, which means that code execution begins with the first line of onCreate(). Not knowing what you're trying to do, a good start would be to call your mainButton() method AFTER setContentView() in onCreate().
Side note: your mainButton() method has a View parameter that is never used. Is there a reason for that?
Android activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
e.g
Code:
Button button = (Button) findViewById(R.id.[B]button[/B]) // replace latter button with actual id defined in main xml.
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("[B]com.example.packagename.CLASSNAME[/B]")); // this should be your own package name.
}
});
Also define this in android manifest under the <application> and </application>
Code:
<activity
android:name=".[B]CLASSNAME[/B]"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="[B]com.example.packagename.CLASSNAME[/B]" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Change the values of BOLD text according to your own values.
I tried to help you as far as I understood your question. Please let me know if you face any problem I would be more than happy to help you. Rest I am also in the learning phase so you can always PM me if you face any problem.
Hit thanks if I have helped you in any way.
coolbud012 said:
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
Click to expand...
Click to collapse
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
jpepin said:
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
Click to expand...
Click to collapse
Oops yeah right read that now...I thought he want to start an activity... Anyways tried to delete my reply but not getting an option to delete.
There are many flaws in his code. And the other thing is if its his first app and if he has low level of programming experience then according to me it would be a next to impossible app for him, as per his code and what he is trying to implement.
I think he should rather start up with small apps, understand things and then move on to complex apps.
P.S - its just my opinion
Click to expand...
Click to collapse
Agreed that he should start small...which is exactly why your suggestion for creating and handling Intents makes no sense. Before that, he should first understand the activity lifecycle. Until then, he can just stick to trivial single-activity apps to gain experience.
OP: This code should be placed in the onCreate method:
Code:
Button button = (Button) findViewById(R.id.your_button_ID_here)
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
mainButton(); // get rid of the View parameter in this method...it's not needed
}
});
This will cause a new instance of your LocationFactory to be created, and will also cause your Toast message to be displayed.
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
osmorgan said:
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
Click to expand...
Click to collapse
I also believe in the same, I also keep on doing experiments and testing things out.
What I would suggest is that start with a small app and understand the insights on how android works and all...
Thanks
Potential Solution
Alright, I think I've found your problem. Have a look at where you define your variables in your LocationManager class:
Code:
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
This is your problem:
Code:
Context Context = null;
If your context is null, and you use it to create a geocoder and call Context.getSystemService, you'll hit a null pointer. You're trying to access an object (the Context) that doesn't even exist
I'd recommend you pass the context in the LocationManager constructor and then instantiate your objects there. That's standard java procedure.
Code:
private Context mContext = null;
Geocoder geocoder = null;
LocationManager manager = null;
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory(Context context)
{
this.mContext = context;
this.geocoder = new Geocoder(context, Locale.getDefault());
this.manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
}
I also renamed Context to mContext - it's generally a good idea to keep the instance's name separate from the class name.
Try that - it should work. Please feel free to ask any more questions - this is how I learned, and I think it's the best way!

Categories

Resources