This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I make simply rss reader in android. I have the errors (I searched and tried some solutions but nothing):
Couldn't open http://pogoda.wp.pl/rss.xml
java.io.IOException: Couldn't open http://pogoda.wp.pl/rss.xml
at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
at com.newsreader.RssReader.getItems(RssReader.java:23)
at com.newsreader.MainActivity$1$1.run(MainActivity.java:48)
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:4340)
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: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
at java.net.InetAddress.getAllByName(InetAddress.java:220)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
and activity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(){
public void run(){
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
try{
RssReader reader = new RssReader("http://pogoda.wp.pl/rss.xml");
ListView items = (ListView) findViewById(R.id.listView1);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(MainActivity.this, android.R.layout.simple_list_item_1, reader.getItems());
items.setAdapter(adapter);
Log.i("", ""+reader);
items.setOnItemClickListener(new ListListener(reader.getItems(), MainActivity.this));
}catch(Exception e){
Log.e("blad", e.getMessage(), e);
}
}
});
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I don't know what am I doing wrong. Maybe someone has got the same problem so please help.
Thanks
It is because you are performing network operation on main thread of activity. Using Async task will be a better option.
Caused by: android.os.NetworkOnMainThreadException
This speaks for itself.
Don't do networking on the main Thread!
AsyncTask to the rescue. Try it out it will work.
Always use AsyncTask to solve this issue.
BUT, if you're within the movie Swordfish, someone points a gun at you and say "fix it in 30 seconds", then change your targetSdkVersion to 9 in the Android Manifest and the exception will stop. Don't worry, it will run on devices with version higher than 9 too. Even so, correct your code later using AsyncTask.
Related
I'm creating my own application. I tested it on Android Lollipop and Marshmallow - everything works great. But whenever I try Android Kitkat, an error occurs. Here's error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newproject/com.example.newproject.Progi}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at com.example.newproject.Progi.onCreate(Progi.java:62)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
It looks like problem is on line 62 in "progi" class, but - as for me - everything is OK especially that on newer Android versions it works great.
public class Progi extends AppCompatActivity {
Intent intent;
Bundle liczby;
Bundle doble;
BigDecimal tablica [][];
BigDecimal punkty = new BigDecimal(-1);
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
android.content.SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
boolean warunek = shared.getBoolean("serial", false);
android.view.MenuItem menuitem = menu.getItem(0);
if(warunek)
{
menuitem.setTitle("Oceny pojedynczo");
}
else menuitem.setTitle("Oceny seryjnie");
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.firstmenu, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutprogi);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("Progi punktowe");
intent = getIntent();
liczby = intent.getBundleExtra("liczby");
doble = intent.getBundleExtra("doble");
tablica = (BigDecimal[][]) doble.getSerializable("doble"); //here is line 62
if(intent.hasExtra("max")) {
Bundle a = intent.getBundleExtra("max");
punkty = (BigDecimal) a.getSerializable("max");
}
przejscie(true);
if(punkty.compareTo(new BigDecimal(-3))==0)
{
procenty(findViewById(android.R.id.content));
}
else if(punkty.compareTo(new BigDecimal(-1))!=0)
{
liczymy(findViewById(android.R.id.content));
}}
And in case someone asking "what 'tablica' gets from intent?":
BigDecimal[][] tablica = new BigDecimal[16][3];
//here i get data from file and put in inside "tablica"
Bundle doble = new Bundle();
doble.putSerializable("doble", tablica);
Intent intent = new Intent(Starter.this, MyActivity.class);
intent.putExtra("doble", doble);
startActivity(intent);
Any idea what's wrong?
Try switching your array implementation (BigDecimal[] []) to ArrayList.
If you want to pass an Array through an intent on Android versions
prior to Android 5.0.1 (maybe some older versions work aswell, but up
to Android 4.3 it is NOT working) You'll have to work around it. You
could do this by converting your Array to an ArrayList.
Then you would be casting it something like this:
(ArrayList<ArrayList<BigDecimal>>) doble.getSerializable("doble");
Related SO answer
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();
}
});
}
}
I want to know why my application is throwing a runtime exception when I run it? I used to the code in the following link for my application,
dynamically add and remove view to viewpager.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ab=getActionBar();
pagerAdapter = new MainPagerAdapter();
pager = (ViewPager) findViewById (R.id.pager);
pager.setAdapter (pagerAdapter);
inflater = (LayoutInflater)getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
v0 = (FrameLayout) inflater.inflate (R.layout.listlayout, null);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(this);
pagerAdapter.addView (v0, 0);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button1)
{
pagerAdapter.addView (v0);
pagerAdapter.notifyDataSetChanged();
}
}
LogCat:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.todolistworkable/com.example.todolistworkable.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
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:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)Caused by: java.lang.NullPointerException
at com.example.todolistworkable.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
the object on line 43 of your code within your onCreate method is null. Most likely the target of one of your findViewById calls is not returning what you expect it to.
See this for more info.
How to interpret Logcat
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.)
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.