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
Related
I'm working on an android app and I need to fetch data from internet.
I declare an "private Progress dialog" in Homepage.java.
In onCreate() method, call the function
dialog = ProgressDialog.show(Homepage.this, "Connecting", "Please wait for a while...", true);
And create another thread to fetch the data, and in finally block, call
"dialog.dismiss()"
The whole onResume() code is shown in below.
#Override
protected void onResume(){
super.onResume();
Log.e(TAG, "onResume");
dialog = ProgressDialog.show(Homepage.this, "Connecting", "Please wait for a while..", true);
/******Start fetching data.******/
Thread getDataThread = new Thread() {
#Override
public void run() {
try {
try {
getData();
} catch (JSONException e) {
alert_error();
e.printStackTrace();
} catch (IOException e) {
alert_error();
e.printStackTrace();
} finally {
dialog.dismiss();
}
} catch (SQLException e) {
alert_error();
e.printStackTrace();
} catch (ExecutionException e) {
alert_error();
e.printStackTrace();
} catch (InterruptedException e) {
alert_error();
e.printStackTrace();
}finally{
dialog.dismiss();
}
}
};
getDataThread.start();
}
At first, this worked great.(the spinner showed)
But at some point(I don't remember when), the dialog still works, but the spinner disappear
Show as below(place marked with red line should be the place where spinner display)
Spinner is gone
The dialog still works, but all ProgressDialog called anywhere from this app, the spinner is gone.(not even show up)
If I changed the getting data from internet part to sleeping for 10 secs
Which is shown below
#Override
protected void onResume(){
super.onResume();
Log.e(TAG, "onResume");
dialog = ProgressDialog.show(Homepage.this, "Connecting", "Please wait for a while...", true);
/******Start fetching data.******/
Thread getDataThread = new Thread() {
#Override
public void run() {
try {
sleep(10*1000);
} catch (InterruptedException e) {
e.printStackTrace();
dialog.dismiss;
}
}
};
getDataThread.start();
}
The spinner still doesn't show up.
I think that might be something related to global settings or values in my project, I create a empty activity with only one method other than super.onCreate and setContentView
I called
"ProgressDialog dialog = ProgressDialog.show(Homepage.this, "123", "456", true);"
and the spinner still doesn't show up!
But if I create a new project and added the same code, it works!
Thanks in advance!
I think the problem is in your phone setting, I had the same issue once, what you need to do is:
Go to developer options in your phone setting.
Turn transition on (in my case i had them turned off to make the phone act fast)
Restart the app and hopefully spinner will be there.
UPDATE:
Or you can try a library like Material Dialogs for that purpose, its one of my favorites, all you need to do is
Compile
compile 'com.afollestad.material-dialogs:core:0.8.6.0'
and then where you want to show the dialog
new MaterialDialog.Builder(this)
.title(R.string.progress_dialog)
.content(R.string.please_wait)
.progress(true, 0)
.show();
you can find more info here to customize it further and usage details.
Hope it helps
I know this is a kind of weird title to describe the question. I have a code as below:
new AlertDialog.Builder(getActivity()).setView(myScrollView)
.setPositiveButton("Sent Query", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
try {
JSONStringURL = myURL_here;
image = new AsyncTaskParseJson1(JSONStringURL).execute().get();
if (image.size() == 0) {
Toast.makeText(getActivity(), "no data", Toast.LENGTH_LONG).show();
} else {
overlayImage(image);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}.show();
when i press "Positive Button", the app should cancel the AlertDialog immediately, and then execute the AsyncTask. Unfortunately, the AlertDialog will lag for 3~4 sec and then run the AsyncTask makes the UX feel really bad, but i have no idea why it will lag?
NEVER use AsyncTask.get(). That makes you wait for the task to finish, which totally ruins the idea of it being asynchronous. The fact the function even exists is a design flaw in Android. Instead, anything that needs to be done after the AsyncTask finishes should be done in onPostExecute() of the task (or in a function called from there).
Obviously this is your problem- you aren't closing the dialog and doing the task in parallel, you're waiting for the task to finish (remember the UI will not update until control is returned to the UI thread looper).
You have to use these changes
dialog.dismiss();
In place of
dialog.cancel();
i want to capture a picture periodically for every minute. without user interaction.something like capture the image in service. any help will be appreciated.
thanks in advance.
This is just suggestion.
Use alarm manager, Which is help you access the camera in every minute.
I think that you can have a Service that launchs at startup. That service will be part of an Application that has permission to use the camera.
Inside that service you can have something like this:
private class threadPhoto extends Thread {
#Override
public synchronized void start() {
super.start();
}
public void force() {
this.force = true;
}
#Override
public void run() {
super.run();
while (true) {
if (force) {
try {
//Code for taking the photo
}
catch (Exception e) {
Log.e("", "Error");
}
force = false;
}
try {
sleep(TIME_INTERVAL_IN_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
And in the Service onCreate you should create the threadPhoto object, and periodically call the force() method that it has.
For learn to take photos in Android you should read this article on Android Developers.
public void get(View view){
try {
asPt = new ProgressTask().execute(null,null,null);
Log.d("Watcher","Get finished");
}
catch (Exception e) {
e.printStackTrace();
Log.e("Watcher","Get Exception");
}
}
When I cancel(Boolean) the AsyncTask asPt the Line "Get finished" is never printed.
Why? It also doesn't catch an Exception in this method.
Remember cancel does nothing so you need to implement it yourself, see link: Android - Cancel AsyncTask Forcefully
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