I'm trying to check uncaught exceptions in any of my activities.
I put this block code after onCreate :
Thread.setDefaultUncaughtExceptionHandler(
new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
Utils.logError(MainActivity.this,session);
}
});
Utils.logError method writes logCat content to a text file and then upload with a custom AsyncTask to a FTP Server.
This is the logError method code
public static void logError(final Context ctx,final SessionManager session){
StringBuilder log=new StringBuilder();
try {
(... code that read logCat and write to a file ...)
//Upload result file to FTP with a AsyncTask
new Thread(new Runnable() {
public void run() {
if(Utils.isInternetConn(ctx)){
FTPHandler ftp = null;
ArrayList<File> archivosAcargar = new ArrayList<File>();
archivosAcargar.add(file);
ftp = new FTPHandler(ctx,archivosAcargar,session.getCodUser());
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if(ftp.ftpConnect("server","user" ,"pass" ,21)){
ftp.execute("upload");
}
}
}
}).start();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The AsyncTask code
EDIT:
#Override
protected String doInBackground(String... peticion) {
String res="";
if(peticion[0].equals("upload")){
if(ftpUpload()) res = "Done upload";
else res = "Error upload";
}
//This print shows "Done upload"
System.out.println(res);
return res;
}
#Override
protected void onPostExecute(String response) {
//This print not executes
System.out.println("Response " + "/" + response + "/");
if(response.equals("Done upload"))
{
System.out.println("done");
if(!isLog){ mDialog.dismiss();
//Toast
}
else{
System.exit(1);
}
}
if(response.equals("Error upload"))
{
if(!isLog)mDialog.dismiss();
}
}
The problem is that the AsyncTask is completed and the file is uploaded the (#Override) onPostExecute never is called.
I've tried to call Utils.logError without a exception and works fine but if I force a exception not works.
Can anyone help me?
Related
I'm using Vk Sdk. I have created AsyncTask to load data from the server in background. However, it turns out that doInBackground() is finished before the tasks inside of it are done. The code is below:
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}
I suspect that request.executeWithListener(...) is creating another thread and doing necessary work there. Therefore, AsyncTask thinks that work in his thread is finished. However, I'm not sure. There is nothing in the documentation for this method.
Another question is on which thread onComplete(...) method is running when it is called? On main or the same separate thread created by request?
Any help is appreciated :)
Base on your code, you have 2 different Threads called.
AsynTask is a background thread which will execute first. Then you called VKRequest executeWithListener which will created another thread in doInBackground().
To archive this in single Thread, you should change your execute method to executeSyncWithListener() in VKRequest
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeSyncWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}
Hope this will help!
Do something like this:
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
// YOUR CUSTOM CALLBACK
new Thread(new myCustomRunnable(jsonData)).start();
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}
where myCustomRunnable is a class that implements 'Runnable' interface.
public class myCustomRunnable implements Runnable{
private String msg ="";
public OToast(String msg) {
this.msg = msg;
}
#Override
public void run() {
//here do anything you want
Log.v("mylog",msg);
//or even execute code in main thread:
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code
}
});
}
}
Or even simpler:
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
// EXECUTE CODE IN MAIN UI THREAD:
final String final_json = jsonData;
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code
textview.setText(final_json);
}
});
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}
I am creating an android app that depends on data that the app gets from the database. To get this data I have the following class (this class gets data from the database in JSON, translates it and returns it):
public class Json {
public String jsonResult;
private Activity activity;
private String url = "http://json.example.org/json.php";
private String db, query;
public Json(Activity activity) {
this.activity = activity;
}
public String accessWebService(String db, String query) {
JsonReadTask task = new JsonReadTask();
this.db = db;
this.query = query;
task.execute(new String[] { url });
try {
task.get();
} catch (InterruptedException e) {
Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread got interrupted",
Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread wasn't able to execute",
Toast.LENGTH_LONG).show();
}
return jsonResult;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(activity);
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
// add post data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("db", db));
nameValuePairs.add(new BasicNameValuePair("query", query));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
if (jsonResult.isEmpty()) {
Toast.makeText(activity.getApplicationContext(),
"Error, connection is up but didn't receive data. That's strange...", Toast.LENGTH_LONG)
.show();
this.cancel(true);
}
} catch (ClientProtocolException e) {
// Toast.makeText(activity.getApplicationContext(),
// "Error, Client Protocol Exception in JSON task",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Client Protocol Exception in JSON task");
this.cancel(true);
} catch (IOException e) {
// Toast.makeText(activity.getApplicationContext(),
// "Error, Please check your internet connection",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Please check your internet connection");
this.cancel(true);
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
Toast.makeText(activity.getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
}// end async task
}
I noticed that my app freezes while accessing the database. After some googling, I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog like so (I also deleted the .get() method):
private final ProgressDialog dialog = new ProgressDialog(activity);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
protected void onPostExecute(String result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
but the dialog didn't show up and I got NullPointerException because the app only works when there is data:
result = json.accessWebService(db, query);
(maybe an important thing to mention: I also use this method in for loops)
So now my question is: How can I change my app so that I get a ProgressDialog while accessing the database and without getting NullPointerException? I fear that I have to rearchitect my whole app and if I have to do this, how do I do this? I hope you guys understand my question and have a fix for this because I really need help. Thanks in advance.
P.S. Sorry if my English is not that good, I'm not a native speaker.
... I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog...
That is right. get() is a blocking call and simply adding a ProgressDialog won't fix it. You need to remove .get() and that will probably fix the issue of your ProgressDialog not showing.
An AsyncTask must be executed on the main Thread so make sure you are doing that.
Another problem you have is Toast.LENGTH_LONG).show(); runs on the UI and you have it in doInBackground() which cannot happen. You need to send the result to onPostExecute() and you can display your Toast there if need. This could also be done in onProgressUpdate().
This null pointer exception happens because of result value was null. put the condition before
if(result != null ) {
// CODE FOR PARSING
} else {
return;
}
You can start showing progress bar before asyncTask is started and finish showing when asyncTask is finished.
Pass handler to asyncTask and sendMessage onPostExecute method. Then handle message on UI thread and hide progress bar
For example there is handler field in UI (mainActivity). There you should handle hiding progress bar:
public Handler refreshChannelsHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case EPGManager.ERROR_MESSAGE:
//do some stuff
break;
case EPGManager.SUCCESS_MESSAGE:
//do some stuff
break;
}
super.handleMessage(msg);
}
};
Then you can call asyncTask with your handler
epgManager.loadChannels(refreshChannelsHandler);
AsyncTask is inside the method so it looks like this:
public void loadChannels(Handler handler) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
try {
//do AsyncTask Job
} catch (Exception e) {
return new LoadingResult((Handler) params[0], false);
}
return new LoadingResult((Handler) params[0], false);
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
LoadingResult loadingResult = ((LoadingResult)o);
sendMessageToHandler(loadingResult.handler, loadingResult.isSuccess);
}
};
task.execute(handler);
}
Here is method:
private void sendMessageToHandler(Handler handler, boolean isSuccess) {
handler.sendEmptyMessage(isSuccess ? SUCCESS_MESSAGE : ERROR_MESSAGE);
}
And finally inner class
private class LoadingResult {
private Handler handler;
private boolean isSuccess;
public LoadingResult(Handler handler, boolean isSuccess) {
this.handler = handler;
this.isSuccess = isSuccess;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
Ow, and don't forget constants
public static final int SUCCESS_MESSAGE = 1;
public static final int ERROR_MESSAGE = -1;
Hope it helps :)
i have a simple application that plays online radio. for showing the title from online php service i use AsyncTask and call it from onCreate method. in android 4 everythin is OK, but in android 2 it's crushed with error
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
then in internet i found, that i must use a code like
new Thread(new Runnable() {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//my code
}
});
}
}).start();
but after i using this tip, a can't see any button and text views in my android 4 and android 2 versions. this is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//thread for update title every second
new Thread(new Runnable() {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
while(true) {
try {
new ShowTitle()
.execute("http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm");
Thread.sleep(1000);
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
}
}
});
}
}).start();
}
//get title string from online source
private String getMusicTitle(String url) {
Document doc = null;
String title = "Music Title";
try {
url = "http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm";
InputStream input = new URL(url).openStream();
doc = Jsoup.parse(input, "CP1251", url);
title = doc.body().text();//doc.select(".products_name").first().text();
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
Toast.makeText(this, "Failed to load title", Toast.LENGTH_SHORT).show();
}
return title;
}
//class for show the audio title
private class ShowTitle extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return getMusicTitle(urls[0]);
}
protected void onPostExecute(final String result) {
lblMusicName.setText(result);
}
}
EDIT: (my working code)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ShowTitle()
.execute("http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm");
}
private String getMusicTitle(String url) {
Document doc = null;
String title = "Music Title";
try {
url = "http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm";
InputStream input = new URL(url).openStream();
doc = Jsoup.parse(input, "CP1251", url);
title = doc.body().text();
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
title = "Failed to load title";
}
return title;
}
private class ShowTitle extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
while (true) {
String str = getMusicTitle(urls[0]);
publishProgress(str);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
}
}
protected void onProgressUpdate(String... result) {
lblMusicName.setText(result[0]);
}
}
In here :
try {
//....your code here
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
Toast.makeText(this, "Failed to load title",
Toast.LENGTH_SHORT).show(); //<<< this line
}
you are trying to show Toast Message from doInBackground (from non-ui Thread). use onPostExecute for showing Toast Message or updating UI according to result returned from doInBackground
and second issue is here:
while(true) {
try {
...
Thread.sleep(1000); //<<< here calling Thread.sleep on Main UI Thread
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
this will always freeze Ui Thread for after AsyncTask execution . so will need to move Thread.sleep(1000) outside runOnUiThread code block
runOnUiThread and AsyncTask are two different things. You are using it in a wrong way.
Try it like this:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ShowTitle().execute("http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm");
}
//get title string from online source
private String getMusicTitle(String url) {
Document doc = null;
String title = "Music Title";
try {
url = "http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm";
InputStream input = new URL(url).openStream();
doc = Jsoup.parse(input, "CP1251", url);
title = doc.body().text();//doc.select(".products_name").first().text();
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
title = "Failed to load title";
}
return title;
}
//class for show the audio title
private class ShowTitle extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
String str = getMusicTitle(urls[0]);
while(true) {
publishProgress(str);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
}
return str;
}
#Override
protected void onProgressUpdate(String... progress) {
if(returnVal.startsWith("Failed")) {
Toast.makeText(this, returnVal, Toast.LENGTH_SHORT).show();
} else {
lblMusicName.setText(result);
}
}
}
You must do all the UI related task in onProgressUpdate
Hi ! I'm trying to display a mesage when the network is off or the server is not responding. My messsage is visible in LOG but does not show on screen (is not toasted). I have a sample code which works fine but my code is not.
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {}
public static AgAppHelperMethods getInstance()
{
if(instance == null)
{
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl ()
{
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl)
{
String _node,_element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list=doc.getElementsByTagName("*");
_node=new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
for (int i=0;i<list.getLength();i++)
{
Node value=list.item(i). getChildNodes().item(0);
_node=list.item(i).getNodeName();
_element=value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
}
}
How can I show my toast message on the screen? Thanks.
You can't do that. You can do something like this
boolean flag=true;//take globally
//working thread
.
.
.
catch (Exception e)
{
flag=false;
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
Once your working thread gets over check the flag value and show the Toast.
//Main Thread
if(!flag)
Toast.makeText(getApplicationContext(), "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
note: If you still want to show in NonUI Thread then you can use Handler or runOnUiThread()
Try this
Toast.makeText(AgAppHelperMethods.this, "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
make sure you pass right context, for example:
Toast.makeText(MyActivity.this , "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
I'm surprised this hasn't been answered yet. It appears to me all you need to do is run the Toast on the UI thread. Thus, in your catch block:
runOnUiThread(new Runnable(){
Toast.makeText(...);
});
Declare globally write it in oncreate and only show in catch block.
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
toast = Toast.makeText(ActivityDeliverables.this, "Server is not working, please contact with admin.", Toast.LENGTH_LONG);
}
try{
} catch (Exception e) {
toast.show();
}
This method is working for me if someone still need help:
getActivity().runOnUiThread(Runnable { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show() })
check this its working fine for me
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_finder);
show();
}
public void show()
{
try
{
throw new ArrayIndexOutOfBoundsException() ;
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "HI", Toast.LENGTH_LONG).show();
}
}
}
I would like to be able to use the facebook android sdk and post a link to facebook. An example of what I want would be is if you were on facebook and you type a link into your status part, like "http://www.google.com". When you do this a box pops up and your post ends up being a block that has an image and a link. I found documentation in the facebook api for this using an attatchment, though when I try to do this with the android facebook api it doesn't seem to work. I've looked for hours on the net, with no luck. Thanks.
Asuming when you read this that you know how to log onto facebook and such via the api...
private void fbImageSubmit(Facebook fb, String imageurl, String caption, String description, String name, String linkurl)
{
if(fb != null)
{
if(fb.isSessionValid())
{
Bundle b = new Bundle();
b.putString("picture", imageurl);
b.putString("caption",caption);
b.putString("description",description );
b.putString("name",name);
b.putString("link",linkurl);
try {
String strRet = "";
strRet = fb.request("/me/feed",b,"POST");
JSONObject json;
try {
json = Util.parseJson(strRet);
if(!json.isNull("id"))
{
Log.i("Facebook", "Image link submitted.");
}
else
{
Log.e("Facebook","Error: " + strRet);
}
} catch (FacebookError e) {
Log.e("Facebook","Error: " + e.getMessage());
}
} catch (Exception e) {
Log.e("Facebook", "Error: " + e.getMessage());
}
}
}
}
This works perfect fine with Progress Dialog box.. I have used it...
You must added the jar of Facebook...
Facebook authenticatedFacebook = new Facebook(APP_ID);
private static final String[] PERMISSIONS = new String[] { "publish_stream", "read_stream", "offline_access" };
Call below function on button Click....
authenticatedFacebook.authorize(YOUR_CLASS_NAME.this, PERMISSIONS, new FaceBookWallPostListener());
Now Add this class...
public class FaceBookWallPostListener implements DialogListener {
public void onComplete(Bundle values) {
new FacebookWallPost().execute();
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class FacebookWallPost extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
path = "Path OF YOUR IMAGE";
Bundle parameters = new Bundle();
parameters.putString("message", "MESSAGE YOU WANT TO POST");
try {
File file = new File(path, "IMAGE_NAME.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
if (data != null) {
parameters.putByteArray("picture", data);
}
parameters.putString("access_token", authenticatedFacebook.getAccessToken());
authenticatedFacebook.request("me");
authenticatedFacebook.request("me/photos", parameters, "POST");
} catch (Exception e) {
return e.getMessage();
}
return "success";
} catch (Exception e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
if (result.equals("success")) {
Toast.makeText(YOUR_CLASS_NAME.this, "WallPost Successfully Done", Toast.LENGTH_SHORT).show();
try {
new File(Environment.getExternalStorageDirectory().toString() + "/Diegodeals", "diegodeals.jpg").delete();
} catch (Exception e) {
}
} else {
Toast.makeText(YOUR_CLASS_NAME.this, "Failed to post \n " + result, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(YOUR_CLASS_NAME.this);
pDialog.setMessage("Posting Picture & Message on Facebook...");
pDialog.show();
}
}
/////GOOOD LUCK.