Facebook authorize not working inside Android Asynctask or Thread - android

Working with facebook in Android. Sometimes my application is cashing in real time device when I tried to authorize Facebook in Android.not in emulator. I used the Android Facebook SDK. So I thought threading might stop that.First tried the asynctask
Activity act=this;
private class fbwork extends AsyncTask<Facebook, Integer, String>
{
#Override
protected String doInBackground(Facebook... para)
{
// TODO Auto-generated method stub
Log.d(tagg, "Entered async");
if(loginflag==0)
{
try
{
para[0].authorize(act, PERMISSIONS, new LoginDialogListener());
}catch(Exception ex)
{
Log.d(tagg,ex.getMessage());
}
Log.d(tagg, tagg.toString());
}
else
{
try {
logout();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "0";
}
calling code:
new fbwork().execute(facebook);
produce error: Can't create handler inside thread that has not called Looper.Prepare()
So tried the normal threading way.
public void loginprocesure() throws MalformedURLException, IOException
{
final Activity ac=this;
if(loginflag==0)
{
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
facebook.authorize(ac, PERMISSIONS, new LoginDialogListener());
}
}).start();
}
else
{
logout();
}
}
Again same result. any way to fix this!!!! How to stop that crashing of application in real device. Please help.

I faced the same issue.You must try to put this method in loop
Looper.prepare();
new fbwork().execute(facebook);
Looper.loop();

Facebook authorize uses methods which access event thread, so you dont need to execute this method into another thread, than event thread.
If you face issue in execution of this method in normal event thread, specifythat issue.

I'm having this problem too. I couldn't get the AsyncTask code working.
So I ended up using runOnUiThread. It works on the emulator, but not on the device, I'm using HTC Desire Android SDK 2.2.2. Unfortunately, I can't even login to Facebook using Hackbook (Facebook's sample project).
Here's code that uses runOnUiThread:
Android App Crashes after Sharing using Facebook Dialogs

Related

Logout functionality for facebook in android app

I am implementing following simple functionality.
I have a simple button, clicking on which I am able to login to Facebook. I am using Facebook SDK for the same. When I click , the src image of the button(imageview) also gets updated.
Up to this point everything works fine. But when i click on the same button for logging out
I get a
android.os.networkonmainthreadexception
exception.
Can anyone please help me solve this issue?
EDIT:
my code is as follows:
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.fb_button:
try{
if(fb.isSessionValid())
{
try {
fb.logout(getBaseContext());
update_fb_buttonimage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button close session
}
else
{
fb.authorize(LoginPage.this, new DialogListener(){
#Override
public void onFacebookError(FacebookError e)
{
Toast.makeText(LoginPage.this, "on Facebook error", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(LoginPage.this, "on error", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values)
{
update_fb_buttonimage();
Toast.makeText(getBaseContext(), "onComplete works",Toast.LENGTH_LONG).show();
}
#Override
public void onCancel()
{
}
});
//login in to facebook
}
}catch(Exception e){
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
thankyou!
The problem here is simply that you need to make your web service calls (or what-have-you) on a separate thread. So, quite simply, you’ll need to look into how to do threading with Android. Unfortunately this can be a bit of a pain because you need to make your service calls on a separate thread, but you need to update the UI on the main thread. Normally this would require passing data between the threads, which involves handlers or other complexities. Luckily the Android platform provides the Async Task to handle this, which alleviates some of this complexity and may help you avoid some clutter in your code.
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask

Calling Drive API for Android on Separate thread returns no data

I am using the Drive API v2 for android, and when I execute the following method my app seems to pause or wait, and no data is returned.
public About getAbout() throws InterruptedException, ExecutionException {
FutureTask<About> future = new FutureTask<About>(new Callable<About>() {
public About call() throws IOException {
About about = null;
try {
about = _driveService.about().get().execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return about;
}
});
About about = future.get();
return about;
}
Does anyone have any idea what I'm doing wrong?
You are creating a FutureTask, but you are never executing it (not on the current thread and not on any other). Then you call future.get() which will block until the operation is completed. Since you never actually perform the operation, it will wait forever.
To execute an operation on a background thread you could for example use http://developer.android.com/reference/android/os/AsyncTask.html

Android thread sometimes does not start

I must use Thread in an Android project. Sometimes, it works corectly, however sometimes does not; it does not start (does not call SendToServer() method)or it starts but return to another function suddenly (return updated; line)before the thread does not finish.
Note: affected value is bigger than 0, it gives condition and it goes to if statement.
Here is the my code sample;
public static Boolean MyUpdateFunction(MyObject myobject){
Boolean updated=false;
//Code for updating local database
int affected= SqliteDb.update(....);
if(affected>0)
{
//Send updated data to server
//For this I must use Thread(I can't use AsyncThread)
updated=true;
SendToServer();
}
return updated;
}
public static void SendToServer()
{
try{
;
Thread th=new Thread(new Runnable() {
public void run() {
try {
//Create data and send it to server
//.......
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
th.start();
th.join();
}
catch(SQLException e)
{
Toast.makeText(myContext,"ERROR: "+e.getMessage(), Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Other people are correct in that an AsyncTask is the way forward, but the direct problem due to what you're experiencing is this (and as such, I would recommend reading up on how Threading works):
When you start the thread, it begins a new process. The UI thread (which is generally where the majority of your code is) continues. So your code will fire the thread with SendToServer(), and then by definition will immediately return updated, as the UI thread immediately goes to the next line.
What you need is a callback from your Thread, which is handled in the onPostExecute() method of an AsyncTask. There's a good tutorial on how to use them and what they do here
Edit:
I've just seen from a comment above that you can't use Asynctasks, fair enough, but you still need a callback/event fired from your Thread to return any results
Instead of using threads and your variables (updated and affected), you can use AsyncTasks: see: http://developer.android.com/reference/android/os/AsyncTask.html
With AsyncTask, you have some methods which are doing exactly what you want:
onPreExecute
doInBackground
onPostExecute
So, what you can do is to check your condition in onPreExecute, then do your SendToServer in the doInBackground and onPostExecute do what you need.

Simple Networking using Datagram in Android

I am trying to make a simple app. Where user sees one edittext .. enters some text in it.. and then press send... then the server on laptop receives that message.
Now the NetworkOnMainThread exception is giving me Headaches......the app works perfectly for 2.3.3 because there was no such thing as NetworkOnMainThread Exception that time.
Having searched a lot .. Two solutions are
Making new thread for networking OR
AsyncTask.
I tried both without any results.
Try 1: With Separate Thread:
Now what I could understand is that I had to start a separate thread. Ok. I did.
Following is my client side code.
EditText e ;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e= (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.textView1);
Thread startNetworking = new Thread(new NetworkThread());
startNetworking.start();
}
public void sendMessage(View v){
if(NetworkThread.sendToClient(e.getText().toString()))
tv.setText("Status : Successful");
else
tv.setText("Status : Unsuccessful");
}
sendMessage is onClick function for my send button. I have another JAVA file NetworkThread.java....
Here is a code for that :
public class NetworkThread implements Runnable{
static DatagramSocket socket;
static InetAddress add;
public void run() {
try {
socket = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
add = InetAddress.getByName("192.168.1.12");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean sendToClient(String message){
DatagramPacket p = new DatagramPacket(message.getBytes(),message.getBytes().length,add,4444);
try {
socket.send(p);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
This is still doesn't work. I first want to exhaust this first try then I will move onto asking here about AsyncTask and what I have tried. So for time being please help me achieve this simple task of sending and receiving a string.
Unfortunately, having sendToClient() defined in the same class as NetworkThread doesn't mean that it will run on your network-specific thread. The sendToClient() method will still run on your main (UI) thread because it's being called from your onClick() method. UI callbacks, such as onClick(), are always processed on the UI thread.
I would recommend using an AsyncTask as it enables you to send arbitrary data (such as your message parameter) to the background/network thread before it executes. Continuing to use Runnable and Thread will require extra machinery to synchronize the execution of your UI and network threads, and these challenges are handled behind the scenes by AsyncTask.

cocos2d-x: threads

I get a small problem: I need using async task in cocos2d-x on Android.
private void parseJSONJava() throws ClientProtocolException, IOException, JSONException
{
STAJSONParser jPars = new STAJSONParser();
jPars.makeHttpRequest(String.format("%s/app/%s/json",STA_URL,STA_APP_UID));
}
But this code crash application with error Can't create handler inside thread that has not called Looper.prepare(). I solve this by adding runOnUiThread:
me.runOnUiThread(new Runnable(){
public void run(){
STAJSONParser jPars = new STAJSONParser();
jPars.makeHttpRequest(String.format("%s/app/%s/json",STA_URL,STA_APP_UID));
}
});
Where "me" is my Activity.
Code from STAJSONParser:
public JSONObject makeHttpRequest(String url) {
AsyncGetJson Task= new AsyncGetJson(url);
try {
return Task.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
AsyncGetJson task its a simple AsyncTask that get JSON from server.
So, my question: is this solution is right/wrong? Or you can give me other solution?
I don't see why you couldn't do that. You could also use libcurl like m.ding mentioned, along with pthreads and a json parser. But the problem there is that you'd need to manage the pthreads yourself. It's "messier" than just doing it the way you're doing it now. Then again, using the JNI isn't exactly pretty either. It's one big giant trade-off, probably leaning in favor of the JNI & Android Java SDK.
On iOS and Android, pthreads are the underlying threading mechanism, which are already managed for you when you use things like iOS's NSOperation and Android's AsyncTask (I'm assuming..)

Categories

Resources