Simple SharedPreferences in Android - java

I'm having a problem, and I already tried everything I found on this site, it's not helping, so I'm asking this question myself.
my code is:
public class MyActivity extends Activity{
protected PositionSense positionSense;
protected Preferences preferences;
String IP;
String ID;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
positionSense = new PositionSense(this, null);
SharedPreferences settings = getSharedPreferences("preferences", 0);
IP = settings.getString("ip", "http://192.168.1.3:8080/servlet");
ID = settings.getString("id", "USER");
}
Later on, I use these variables in a background running thread that contacts the servlet and sends some info (including position and ID of the user which is saved in preferences)
I'm not posting all of that because I don't want to clog up the thread more than necessary (but if it is needed, I will post it all)
In any case, it doesn't work and it gives me the following error log:
09-14 16:47:20.854: WARN/dalvikvm(552): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
09-14 16:47:20.884: ERROR/AndroidRuntime(552): FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3044)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3039)
... 11 more
Caused by: java.lang.NullPointerException
at com.moodswings.MoodSwingsActivity.clickHappy(MoodSwingsActivity.java:94)
... 14 more
I don't know what to do about it.
Can someone give me the SIMPLEST possible way to save 2 strings in preferences in one activity that are used in some other activity within the same application? It's supposed to be really simple, but I simply cannot make it work, and I'm nearing my deadline.
Thanks!

To save to shared preferences you can try:
String ip = "192.168.1.1";
SharedPreferences prefs = getSharedPreferences("IP", Context.MODE_PRIVATE);
prefs.edit().putString("Sample IP", ip).commit();
To get the information from the shared preferences you can try:
String newIP = prefs.getString("Sample IP");//You can also place a default value if needed; to bypass the null character.
Now to pass them into activities you can try doing an intent call like below
**Activity One
Intent intent = new Intent(getApplicationContext(),SecondActivity.class);
intent.putExtra("IP",newIp);
startActivity(intent);
**Activity Two
Bundle extras = intent.getExtras();
String tmp = extras.getString("IP");
Also you can use this link to reference.

Related

Null Pointer Exception when loading SharedPreference value into fragment string

I'm receiving a null pointer exception when trying to load the string value from sharedpreferences into the string value on my fragment.
I have the sharedpreference working correctly, so I know the string is being saved, but I can't replace the string value in my fragment with the sharedpreference value.
MainActivity
SharedPreferences saveLocation = getSharedPreferences(SAVE, MODE_PRIVATE);
SharedPreferences.Editor editor = saveLocation.edit();
editor.putString("name", marker.getTitle());
editor.commit(); //applies the name to XML
FlickrFragment
public class FlickrFragment extends Fragment{
GridView mGridView;
ArrayList<GalleryItem> mItems;
ThumbnailDownloader mThumbnailThread;
String textToSearch = "Keating Hall";
Basically "Keating Hall" is the text that's being used to generate a gridview of photos. That works correctly, however, I'm trying to replace "Keating Hall" with the sharedpreference value, but have been unsuccessful in all methods that I've tried.
Please let me know if my description needs to be updated to better reflect what I need help with.
Thank you.
Updated: Included LogCat
12-14 15:12:25.161 14902-14902/com.example.ramap E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ramap, PID: 14902
java.lang.NullPointerException
at com.example.ramap.FlickrFragment.<init>(FlickrFragment.java:41)
at com.example.ramap.adapter.TabsPagerAdapter.getItem(TabsPagerAdapter.java:25)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:97)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
at android.support.v4.view.ViewPager.populate(ViewPager.java:987)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:16660)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16660)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
at android.view.View.measure(View.java:16660)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
at android.view.View.measure(View.java:16660)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2058)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1189)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1374)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1076)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5905)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:807)
at android.view.Choreographer.doCallbacks(Choreographer.java:601)
at android.view.Choreographer.doFrame(Choreographer.java:562)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:791)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5633)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:896)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
at dalvik.system.NativeStart.main(Native Method)

Async PostExecute

I have been able to set up a connection between my socket server (running on ruby) and my client, which is an Android(java) application. I will explain what my goal is.
I have to send a string to my server through the socket. Depending on the contents of the string, the server would execute a process in the database (store, delete, view data, etc).
The first option is to validate the user name/password. Im able to send the correct string, and the server receives it and replies back to me with the correct response (after validating whether or not my username is capable of logging into the application). Now, depending on this response i need to change the current activity (loginActivity) with the next activity (MenuActivity) so that the user can proceed to use the application menu.
Since the socket has to run on a different thread other than the UIThread, im running it using the AsyncTask way. However im having problems triggering the activity change thing after the AsyncTask process is over.
What im doing is, after the whole Async task is done (onPostExecute method) im trying to call up the activity, but its not working. This is what i've tried (based on similar cases i've found during research):
(AsyncTask class)
Context context;
private void AppContext(Context context) {
this.context = context.getApplicationContext();
}
OnPostExecute
Intent NewActivity = new Intent();
NewActivity.setClass(context.getApplicationContext(),MainActivity.class);
context.startActivity(NewActivity);
However this is not working and its causing my app to crash with a "thread exciting with uncaught exception"
I've tried showing only a Toast message that says "Granted" or "Denied" just to test it with a simpler task, but i keep getting the same error so im assuming its got to do with handling the change between the thread on which the Async task is running and the UI thread. Any ideas?
P.S: I've checked the other questions that are similar to mine and tried the suggested code, but nothing's worked.
ERROR LOG
09-29 09:59:11.387: E/AndroidRuntime(2856): FATAL EXCEPTION: main
09-29 09:59:11.387: E/AndroidRuntime(2856): java.lang.NullPointerException
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.example.prescoterm.SocketClass.onPostExecute(SocketClass.java:111)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.example.prescoterm.SocketClass.onPostExecute(SocketClass.java:1)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask.finish(AsyncTask.java:602)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask.access$600(AsyncTask.java:156)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.Looper.loop(Looper.java:137)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-29 09:59:11.387: E/AndroidRuntime(2856): at java.lang.reflect.Method.invokeNative(Native Method)
09-29 09:59:11.387: E/AndroidRuntime(2856): at java.lang.reflect.Method.invoke(Method.java:511)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-29 09:59:11.387: E/AndroidRuntime(2856): at dalvik.system.NativeStart.main(Native Method)
Ok so i found a workaround this, now i would like to hear from you guys if you think this'd be a suitable solution.
Since the problem was that the context was coming up null at my AsyncTask class, i decided to load the value on a variable from the moment the application start.
context = this.getApplicationContext();
new SocketReception().setContext(context);
On my SocketReception Class i had a setContext(context) method.
public void setContext(Context context)
{
SocketReception.appContext= context;
};
Now, on my AsyncTask post.execute i call the new activity like this:
SocketReception.appContext.startActivity(NewActivity);
Its now working, but i want to know if this is a convenient approach or if i should keep looking for a different solution.
P.S: I had to add the unpopular "FLAG_ACTIVITY_NEW_TASK", will research on how to avoid this later on.
I have used this asynctask directly in activity and work fine, may be help. When i try call Intent i = new Intent(getApplicationContext(), VyberIcoActivitySD.class); in class without context ( class extended not Activity, Fragment... ) i have not result...
class SynchroAllIcosSD extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SynchroIcoActivitySD.this);
pDialog.setMessage(getString(R.string.progdata));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//do something
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Intent i = new Intent(getApplicationContext(), VyberIcoActivitySD.class);
Bundle extras = new Bundle();
extras.putString("odkade", "100");
extras.putString("page", "1");
i.putExtras(extras);
startActivity(i);
finish();
}
});
}
}

Button to set different activity colour

I am trying to set the background colour of a different activity from the activity main but I am getting a null pointer.
This is the main:
View activity;
activity = findViewById(R.layout.activity_connect_four);
The button:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
// null pointer on below line
activity.findViewById(android.R.id.content)
.setBackgroundColor(Color.BLACK);
}
});
The logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.con4.MainActivity$4.onClick(MainActivity.java:80)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Where the logCat is pointing to, I don't know what to change. Any help I would be grateful
You're receiving a NPE because that activity and view is not inflated, therefore it returns as null. The way you're setting the background color is flawed by nature. By setting it as you are, even without the NPE, you're storing a setting in the memory of the device. The moment that the device kills your activity, you'll lose that information. As an alternative, you need to store this setting on the device for later retrieval. For what you're attempting to do, I would recommend using SharedPreferences.
In your settings Activity:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
prefs.edit().putInt(BACKGROUND_COLOR, Color.BLACK).commit();
}
});
BACKGROUND_COLOR is a key variable that could be set to "background_color". Then when you start you other activity:
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
int color = prefs.getInt(BACKGROUND_COLOR, Color.WHITE);
And use that color to set the background. Using this method, the background color will be saved to the device until it gets overridden (settings change) or the app is uninstalled.
If you want this to be the background of all of your activity, I suggest having all activities extending a base activity and implementing that code there.
You can check out other storage methods here: http://developer.android.com/guide/topics/data/data-storage.html

java.lang.ClassNotFoundException....once more

I have updated my app today and after that I got 12 crash reports. As i can see all are tide to my main activity class. Here's couple of them:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{rs.androidaplikacije.zastaveigradovi/rs.androidaplikacije.zastaveigradovi.MainActivity}: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565)
... 11 more
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{rs.androidaplikacije.zastaveigradovi/rs.androidaplikacije.zastaveigradovi.MainActivity}: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1766)
at android.app.ActivityThread.access$1500(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:994)
at android.os.Handler.dispatchMessage(Handler.java:130)
at android.os.Looper.loop(SourceFile:351)
at android.app.ActivityThread.main(ActivityThread.java:3833)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:538)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: rs.androidaplikacije.zastaveigradovi.MainActivity in loader dalvik.system.PathClassLoader[/data/app/rs.androidaplikacije.zastaveigradovi-1.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:271)
at java.lang.ClassLoader.loadClass(ClassLoader.java:582)
at java.lang.ClassLoader.loadClass(ClassLoader.java:542)
at android.app.Instrumentation.newActivity(Instrumentation.java:1056)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1656)
... 11 more
And here's my main activity. I did not change anything in it at all.
public class MainActivity extends SwarmActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
preload(this, 5259, "0d2ab20831857f730c1c362705970d1f");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread splashTimer = new Thread(){
public void run(){
try {
sleep(2000);
Intent menuIntent = new Intent("rs.androidaplikacije.zastaveigradovi.MENU");
startActivity(menuIntent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
finish();
}
}
};
splashTimer.start();
}
private void preload(MainActivity mainActivity, int i, String string) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Everything works fine on my phone, but i got a lot of crash reports today. Can someone tell me what's the problem?
I think that the problem is in the way your application is "packaged". The exception is saying that the class loader cannot find the rs.androidaplikacije.zastaveigradovi.MainActivity class when it tries to load it. The fact that you didn't change your code is probably not relevant.
Why it works on your phone and not on other peoples' is less clear. But it could be that:
The version you are running on your phone is not identical to the one that other people are getting from the app store (or wherever).
Your phone has other stuff on it, and that other stuff is what makes the difference.
(It is also possible that the root cause is earlier than the exception in the reports. On a real Java platform, it is possible for class loading and initialization to fail, leaving some classes in an unintializable state. This can then cause later things to fail to load. In this case, the later exceptions don't tell you the real cause of the problems. You have to look to the earlier exception stacktraces for the real cause. HOWEVER, I don't think that is what is happening here.)

java.lang.NullPointerException:com.google.android.gms.maps.GoogleMap.moveCamera

I am currently working on the new Google Maps Android API v2.
My MapActivity class is working with my Samsung galaxy s3 ans s2 with the code below:
However, there are some particular devices are not working such as: GT-S5830i
class MapActivity extends FragmentActivity implements OnMapClickListener, OnMapLongClickListener, OnMarkerClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
ArrayList<Cooridnates> cooridnatesList = MainActivity.getList();
for(int i=0;i<cooridnatesList.size();i++)
{
//Toast.makeText(MapActivity.this, "SIZE : " + " " + cooridnatesList.size(), Toast.LENGTH_LONG).show();
LatLng point = new LatLng(cooridnatesList.get(i).getLat(),cooridnatesList.get(i).getLon());
tvLocInfo.setText("markers added");
myMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
center=CameraUpdateFactory.newLatLng(point);
}
CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
myMap.moveCamera(center);
myMap.animateCamera(zoom);
myMap.setOnMapClickListener(this);
myMap.setOnMarkerClickListener(this);
markerClicked = false;
}
For some reason, I am getting this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coldice.plotfinder/com.coldice.plotfinder.MapActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.google.android.gms.maps.GoogleMap.moveCamera(Unknown Source)
at com.coldice.plotfinder.MapActivity.onCreate(MapActivity.java:70)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
... 11 more
You function MainActivity.getList() probably returned an empty list, so for loop doesn't execute center=CameraUpdateFactory.newLatLng(point);.
it seems center is null in this >> myMap.moveCamera(center);, make an appropriate check on this variable before passing it in moveCamera method.
It seems problem is here. center might have null value, So to get proper explanation debug your application.
center is initialzed here.
center=CameraUpdateFactory.newLatLng(point);
It might assign null in center.
myMap.moveCamera(center); <<<PROBLEM is here
if(center != null )
myMap.moveCamera(center);

Categories

Resources