Async PostExecute - java

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

Related

Enable WiFi in AlertDialog crashes

If wifi or mobile data is not enabled, it should ask the user, if he clicks yes in the AlertDialog, it will go to the settings.
This is inside main, on create, when the update button clicked:
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG,"ButtonUpdate clicked");
connectIfNecessary();
currentDate = Calendar.getInstance();
formatter= new SimpleDateFormat("yyyy-MM-dd");
new UpdateDB(MainActivity.this);
txtLastUpdateShow.setText(formatter.format(currentDate.getTime()));
});
This is connectifnecessary:
public void connectIfNecessary(){
Log.v(TAG, "main connectIfNecessary");
if(!isConnected()){
final Context ctx = this;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage("need internet");
builder.setTitle("do you want to enable it now?");
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
}
this is isConnected:
public boolean isConnected(){
Log.v(TAG, "mainisconnected");
ConnectivityManager conectivtyManager = (ConnectivityManager)
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (conectivtyManager.getActiveNetworkInfo() != null
&& conectivtyManager.getActiveNetworkInfo().isAvailable()
&& conectivtyManager.getActiveNetworkInfo().isConnected()) {
Log.v(TAG, "mainisconnected true");
return true;
} else {
Log.v(TAG, "mainisconnected false");
return false;
}
}
in updatedb constructor, it will call asynctask to connect websites.
When i run this, and click update button, it crashes because it goes into updatedb withpout asking me in builder. The errors:
FATAL EXCEPTION: AsyncTask #1
Process: com.cursedchico.IstanbulEventPool, PID: 13068
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:303)
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:109)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841) 
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e17480 V.E..... R.....I. 0,0-488,216} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:902)
at com.cursedchico.IstanbulEventPool.MainActivity.connectIfNecessary(MainActivity.java:106)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:276)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e36258 V.E..... R......D 0,0-488,165} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.app.ProgressDialog.show(ProgressDialog.java:117)
at android.app.ProgressDialog.show(ProgressDialog.java:100)
at com.cursedchico.IstanbulEventPool.EventRetriever.onPreExecute(UpdateDB.java:269)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.cursedchico.IstanbulEventPool.UpdateDB.<init>(UpdateDB.java:56)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:280)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java:106) is builder.show()
MainActivity.java:276) connectIfNecessary();
I am getting errors for hours, at first about appcompat, then manifest then layout now this.
I use real tablet device.
When device is not connected , following would be execution flow
Get inside connectIfNecessary()
Create Alert to ask user to enable internet. Please note that only Alter object is created at this moment, it will be displayed on screen only after stack of main thread unwinds.
Return from connectIfNecessary() create instance of updateDB(). Inside this application is crashing
Few simple changes would fix your code.
add isConnected() if check before creating instance of updateDB(). This will cover the CONNECTED case
if the device is NOT CONNECTED, user will shown the alter and take to settings screen. If user enables WIFI from settings and comes back, onResume() of your activity will be called. Check connectivity and add updateDB() here.

IllegalThreadExeption for running thread in surfaceView, specific to Lunar Lander example

So I have an app that uses a surface view that runs a separate thread for the UI. It was taken almost directly from the Lunar Landing sample app. The app also uses Bluetooth service on another thread but I am sure that this is not related to the problem because I can disable bluetooth all together and it still happens.
The problem in my app is that the app when closed and then reopened does not start running the UI thread afterthread.start() except it throws an error. In the Lunar example they have thread.start() in the onSurfaceCreated method. The problem is when I restart my app (it calls onPause then onSurfaceDestroy) the thread is already running and I get an error when I try to start it. My code for onSurfaceCreated, onPause, onResume and onSurfaceDestroyed is all the same as the example. I know I can use if (this.getState() == Thread.State.NEW) { but that seems like it will mask some of my other issues. I want to master the activity life cycle.
My question is how does the Lunar Lander stop the thread? And why is mine not stopping with the same code and running at the onSurfaceCreated method. Obviously I am missing something. As far as I know in the Lunar example the only thing that is called on the thread on a destroy is thread.join().
Edit 3: Here is the Lunar Lander Example Code if needed.
So these are the three override methods in my surfaceview...
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Log.d(TAG, "surfaceCreated");
// start the bluetooth service
thread.startBluetoothService();
// start the game
//if (this.getState() == Thread.State.NEW) {
Log.d(TAG, "thread start");
// start running the thread
this.start();
//}
Log.d(TAG, "running to true");
// release the thread lock
setRunning(true);
}
// surfaceChanged is called at least once after surfaceCreated
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.d(TAG, "surfaceChanged");
// reset the surface size
thread.setSurfaceSize(width, height);
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.d(TAG, "surfaceDestroyed");
// make sure to shut down the thread cleanly
boolean retry = true;
// stop the running thread
thread.setRunning(false);
// continuously try to shut down the thread
while (retry){
try{
// blocks calling thread until termination
thread.join();
// stop the bluetooth service
//thread.stopBluetoothService();
retry = false;
}catch(InterruptedException e){
//try to shut it down again
}
}
}
I am really pretty lost with all of this. Any help would be very appreciated, thanks!
Edit:
So I did a little more testing. When the user hits home(which exits the app completely) onPause, then onSurfaceDestroy like I said before. Then when it restarts I get onResume followed by onSurfaceCreated. I think my issue is that it is not calling onCreate when you reenter the app.
Some more questions...
What distinguishes the difference between a onPause and a onDestroy? I think my problem is that since onCreate is not being called I don't have a newly created UI thread which seems like it is still running.
Should the thread be stopped even on a onPause? Because then I am not garenteed to run onCreate which re instantiates the thread. Here is the onCreate code...
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wobble);
// get view and thread
wobbleView = (WobbleView) findViewById(R.id.wobble);
wobbleThread = wobbleView.getThread();
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
// alert the user of bluetooth failure
Toast.makeText(this, "Bluetooth is not available, using internal devices sensors", Toast.LENGTH_LONG).show();
// set the data source to internal sensors - so we'll just use the devices accel
wobbleThread.setDataSource(WobbleThread.INTERNAL_SENSORS);
// bluetooth is supported so make sure its enabled and
}else{
// make sure bluetooth is enabled on the device
if (!mBluetoothAdapter.isEnabled()) {
Log.d(TAG, "starting request to enable bluetooth");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
// all is well with bluetooth - use bluetooth
Log.d(TAG, "setting bluetooth to bluetooth");
wobbleThread.setDataSource(WobbleThread.BLUETOOTH);
}
// give the LunarView a handle to the TextView used for messages
wobbleView.setTextView(
(TextView) findViewById(R.id.text_accel),
(TextView) findViewById(R.id.game_msg),
(TextView) findViewById(R.id.text_score),
(TextView) findViewById(R.id.bluetooth_status)
);
if (savedInstanceState == null) {
// we were just launched: set up a new game
//wobbleThread.setState(wobbleThread.STATE_READY);
} else {
//wobbleThread.setRunning(true);
// we are being restored: resume a previous game
//wobbleThread.restoreState(savedInstanceState);
}
}
Edit 2:
Some logcat output
So this is what I get when the thread.start() is called after reopening the app.
11-18 22:50:44.104 4868-4868/com.bme.shawn.wobble E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalThreadStateException: Thread already started
at java.lang.Thread.checkNotStarted(Thread.java:871)
at java.lang.Thread.start(Thread.java:1025)
at com.bme.shawn.wobble.WobbleThread.startGame(WobbleThread.java:213)
at com.bme.shawn.wobble.WobbleView.surfaceCreated(WobbleView.java:94)
at android.view.SurfaceView.updateWindow(SurfaceView.java:580)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:240)
at android.view.View.dispatchWindowVisibilityChanged(View.java:7903)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1289)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1050)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5750)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:561)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5406)
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)
And if I use the thread.getState check and bypass the error I get this when I close then reopen the app. (logs in basically everything) In this case when the app reopens the thread is not drawing at all. Which is very weird since without the check I get an error saying that the thread is already running.
11-18 22:59:13.444 5345-5345/com.bme.shawn.wobble D/WobbleActivity﹕ onPause
11-18 22:59:13.584 5345-5345/com.bme.shawn.wobble D/WobbleView﹕ surfaceDestroyed
11-18 22:59:17.794 5345-5345/com.bme.shawn.wobble D/WobbleActivity﹕ onResume
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleView﹕ surfaceCreated
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleThread﹕ running to true
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleView﹕ surfaceChanged
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleThread﹕ setting surface sizes
11-18 22:59:17.824 5345-5345/com.bme.shawn.wobble D/dalvikvm﹕ GC_FOR_ALLOC freed 3343K, 2% free 6585K/6668K, paused 13ms, total 13ms
11-18 22:59:17.844 5345-5345/com.bme.shawn.wobble E/IMGSRV﹕ :0: PVRDRMOpen: TP3, ret = 44
11-18 22:59:17.854 5345-5345/com.bme.shawn.wobble E/IMGSRV﹕ :0: PVRDRMOpen: TP3, ret = 50
Create a new instance of the thread in surfaceCreated() and start it. And call thread.join() in surfaceDestroyed()to destroy it.

android.os.NetworkOnMainThreadException [duplicate]

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.

Simple SharedPreferences in Android

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.

Receiving text from other apps via Share menu

I'm writing a language dictionary app for myself (as a kind of Android-programming learning exercise).
I want my app to be listed as an option in the intent chooser of other apps, so I add these code lines to my manifest:
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
My app successfully appears in the action menu of other apps (e.g. Browser), which is good. My app is also successfully called via Share when I choose it from Browser action menu.
Now I want my app to receive and process text (a word) sent from other apps, and then automatically look the text up for its definition. I add the following code lines to the main activity of my app:
//(under onCreate)
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
EditText edittext = (EditText) findViewById(R.id.edWord);
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
edittext.setText(sharedText);
}
}
}
However at this stage, Browser gets crashed every time my app is chosen from the action menu via Share.
So it comes to my questions:
What have I done wrong?
How/What could I do to "force" my app to accept text
from other apps, and automatically display its definition?
Sorry for these are noobie questions (my headache, though).
Thank you very much for your help.
UPDATE 1
Thanks, CommonWare. Nothing is produced when Browser is crashed but when I choose "Share" from the web view of my app, I get this log cat:
08-09 18:17:23.726: W/dalvikvm(1111): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-09 18:17:23.776: E/AndroidRuntime(1111): FATAL EXCEPTION: main
08-09 18:17:23.776: E/AndroidRuntime(1111): java.lang.RuntimeException: Unable to start activity ComponentInfo{peter.kadict/peter.kadict.Kadict}: java.lang.NullPointerException
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.ActivityThread.access$600(ActivityThread.java:122)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.os.Handler.dispatchMessage(Handler.java:99)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.os.Looper.loop(Looper.java:137)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-09 18:17:23.776: E/AndroidRuntime(1111): at java.lang.reflect.Method.invokeNative(Native Method)
08-09 18:17:23.776: E/AndroidRuntime(1111): at java.lang.reflect.Method.invoke(Method.java:511)
08-09 18:17:23.776: E/AndroidRuntime(1111): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-09 18:17:23.776: E/AndroidRuntime(1111): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-09 18:17:23.776: E/AndroidRuntime(1111): at dalvik.system.NativeStart.main(Native Method)
08-09 18:17:23.776: E/AndroidRuntime(1111): Caused by: java.lang.NullPointerException
08-09 18:17:23.776: E/AndroidRuntime(1111): at peter.kadict.Kadict.onCreate(Kadict.java:449)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.Activity.performCreate(Activity.java:4465)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
08-09 18:17:23.776: E/AndroidRuntime(1111): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
08-09 18:17:23.776: E/AndroidRuntime(1111): ... 11 more
UPDATE 2
This code has solved the problem thanks to CommonsWare.
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
setContentView(R.layout.main);
EditText edittext = (EditText) findViewById(R.id.edWord);
edittext.setText(sharedText);
}
}
}
But it does not do its task: the app is loaded but does not seem to receive and process the text (word) sent from other apps.
Can you you guys help? Many thanks.
Either:
You have not called setContentView(), or
You do not have an EditText widget with an android:id of #+id/edWord, or
Clean your project (e.g., Project > Clean from the Eclipse main menu) and try it again
So i got the same problem and i dont know what is wrong with the activities so i solved the problem by getting the shared text and put it in a bundle to a new intent to do what ever i want with it
here is my code
public class GetFromShared extends Activity {
TextView tex;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.d("Shared text is", sharedText);
Intent rooy = new Intent(getApplicationContext(),
BayenELText.class);
rooy.putExtra("GotText", sharedText);
startActivity(rooy);
}
}
}
}
and receiving class is
public class BayenELText extends Activity {
TextView blabla;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.getsharedtext);
blabla = (TextView) findViewById(R.id.etSharedText);
Bundle extras = getIntent().getExtras();
String hloho = extras.getString("GotText");
blabla.setText(hloho);
}
}
the log shows the shared text when it called from share via but the thing i thought of that the Intent filter when it called by
<action android:name="android.intent.action.SEND" />
doesn't have the permmision to make any changes to the view so that how i solve it and it works fine ;)
When I see this logcat output, I immediately think about the fact that the activity cannot be found. If that is the case, a NPE will be thrown.
So:
1. Do you have the activity in your AndroidManifest.xml ?
2. Is it possible to start the activity yourself using adb shell am start -n peter.kadict/peter.kadict.Kadict ?

Categories

Resources