I want to get file in rest service from android. In my code i send filestream from android via url. If i use like this My entire app is not working by saying...
Logcat
Operation Fileacces in contract 'IREST' has a query variable named
stream of type System.IO.FileStream, but type
System.IO.FileStream is not convertible by QueryStringConverter.
Variables for UriTemplate query values must have types that can
be converted by QueryStringConverter
Here I have post my coding FYR
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri content_describer = data.getData();
String src = null;
try {
src = getFilePath(UploadActivity.this, content_describer);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("src is: ", src);
source = new File(src);
fname = source.getName();
Button text = (Button) findViewById(R.id.txt);
text.setText(fname);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileOpen.openFile(UploadActivity.this, source);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Onclick event in action bar icon:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.mybutton) {
new Save().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
SAVE function asynctask
private class Save extends AsyncTask<String,Void,String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
fis=new FileInputStream(source);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ServiceHandler jsonParser = new ServiceHandler();
String fileaccess = ip+"Mobile/rest.svc/Fileacces?stream="+fis+"&filename="+fname;
Log.d("Fileaccess","fileaccess"+fileaccess);
String result = jsonParser.makeServiceCall(fileaccess, ServiceHandler.GET);
Log.i("fileaccess", "result: > " + result);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
System.out.println(s);
}
}
My rest function in vb.net
Public Function fileacces(ByVal stream As FileStream, ByVal filename As String) As String Implements IREST.fileacces
Dim result = ""
Try
Dim path = "D:\XXX\YYY\ECM Source\Archive\EZECM\Settings\Monitor\" + filename
Dim fileStream = New FileStream(path, FileMode.Create, FileAccess.Write)
stream.CopyTo(fileStream)
fileStream.Dispose()
result = "file uploaded"
Catch ex As Exception
End Try
Return result
End Function
kindly use base 64
like this
public void uploadFile(final String selectedFilePath) {
try {
FileInputStream inputStream = new FileInputStream(selectedFilePath);
byte[] byteArray = IOUtils.toByteArray(inputStream);
final String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// tvFileName.setText(encoded);
Log.e("File Base 64",encoded);
filebas64=encoded;
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("Error",e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Error",e.toString());
}
}
Related
Im trying to parse a json string that is exist in a online server and store in an empty string like this String data = ""; but when i try to parse it and i see the log i see that the response from the server show all the json code (brackets and quotes and jsonobject) when i only need it to parse one specific string to be stored in the empty string. here are the json:
{
"main1": {"bnl":"code"}
}
the httphanlder
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
and this is the mainactivity
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
private NativeExpressAdView mNativeExpressAdView;
// URL of object to be parsed
// This string will hold the results
private String TAG = MainActivity.class.getSimpleName();
String data = "";
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://yourdomain.com/test.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
new GetAd().execute();
LinearLayout layout = (LinearLayout)findViewById(R.id.layoutId);
// Create a native express ad. The ad size and ad unit ID must be set before calling
// loadAd.
mNativeExpressAdView = new NativeExpressAdView(MainActivity.this);
mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, 90));
mNativeExpressAdView.setAdUnitId(data);
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
// Start loading the ad.
mNativeExpressAdView.loadAd(adRequestBuilder.build());
// Add the NativeExpressAdView to the view hierarchy.
layout.addView(mNativeExpressAdView);
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "alltext");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFav");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "today");
startActivity(today);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
void startTheThingWithData(){
//Here data has value
Log.e(data, data);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetAd extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject dataa = jsonObj.getJSONObject("main1");
String ad = dataa.getString("bnl");
data = ad;
Log.e(TAG, "Response from url: " + ad);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
startTheThingWithData();
}}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
this is what it shows in the log
E/MainActivity: Response from url: {
"main1": {
"bnl":"code"
}
}
You are printing the jsonStr while the content you want is the data.
AyncTasks runs async, meaning that code runs paralalel: check this simple sample for better undestanding.
String b = "s";
void onCreate(Bundle b) {
afterAsyncHere();
new Task().execute();
afterAsyncHere();
}
void afterAsyncHere() {
Log.e("onCreate", b);
}
class Task extends AsyncTask {
Object doInBackground(Object ... args) {
b ="value b";
try { Thread.sleep(1000); }catch(Exception e) {}
}
void onPostExecute(Object r) {
afterAsyncHere();
}
}
}
The above code will call afterAsyncHere() three times, two in onCreate and one in onPostExecute. The printed result will be:
"s" from onCreate
"s" from onCreate
"value b" from onPostExecute
Note that in onPostExecute your Task was concluded and the value of 'b' was updated.
While in the second call (right after starting the task) the value is still "s".
String ad = dataa.getString("bnl");
data = ad;
Log.e(TAG, "Response.data from url: " + data);
The actual code that would works is:
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// This string will hold the results
String data = "";
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://yourdomain.com/test.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
new GetAd().execute();
}
void startTheThingWithData(){
mNativeExpressAdView.setAdUnitId(data);
//Here data has value
Log.e(data, data);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetAd extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject dataa = jsonObj.getJSONObject("main1");
String ad = dataa.getString("bnl");
data = ad;
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
startTheThingWithData();
}}
Note I added a callback method on the Activity and called it from the onPostExecute
I need to send image to service, pre-execute method working where as do in background not working. Code is below for same:
private class SendImageAsync extends AsyncTask<String, String, String> {
private Context context;
private String serverUrl;
private String path;
public SendImageAsync(Context context, String serverUrl,
String path) {
this.context = context;
this.serverUrl = serverUrl;
this.path = path;
}
#Override
protected void onPreExecute() {
LogWrite.i(TAG, "onPreExecute method enters!!");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
LogWrite.i(TAG, "doInBackground method enters!!");
byte[] imageBytes = getFileBytes(path);
ImageToSend sendImage = new ImageToSend();
boolean responseStatus = sendImage.send(context, serverUrl,
imageBytes );
String responseString = responseStatus ? "Success!" : "Fail!";
LogWrite.e(TAG, "Response " + responseString);
return "";
}
#Override
protected void onPostExecute(String result) {
LogWrite.i(TAG, "onPostExecute method enters!!");
super.onPostExecute(result);
}
}
Help me on same, why it is not working?
Update code:
I had created an interface, that will notify on image click and provide me path of file:
#Override
public void onImageCapture(File file) {
if (file != null) {
LogWrite.d(TAG, "File Path ::: " + file.getAbsolutePath());
if (isFromCommand) {
LogWrite.d(TAG, "Is from command : "+ isFromCommand);
try {
SendImageAsync async = new SendImageAsync (activity,
serverUrl, file.getAbsolutePath());
async.execute("");
} catch (Exception e) {
LogWrite.e(TAG, "SendImageAsync Exception : " + e.toString());
}
}
Bitmap myBitmap = showBitmapFromFile(file.getAbsolutePath());
myBitmap = RotateBitmap(myBitmap, 90);
Drawable ob = new BitmapDrawable(getResources(), myBitmap);
saveImageView.setBackgroundDrawable(ob);
}
// saveImageView.setImageBitmap(myBitmap);
}
I'm not sure but you probably want to send a request and not a response...
I found the solution, I was using this AsyncTask on another AsyncTask, So its not working, even it was not giving any exception.
Here are the basic sample code you can refer, hope this help
/**
* Async task to post file to remote web api
*/
public class PostFileToWebAPI extends AsyncTask<String, Integer, Object> {
...
#Override
protected Object doInBackground(String... params) {
String filePath = params[1];
try {
return postFile(mAPI_URL, filePath);
} catch (Exception e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
private String postFile(String apiUrl, String filePath) throws Exception {
// init httpClient, httpPost...
...
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filePath);
FileBody fileBody = new FileBody(file);
final long totalSize = fileBody.getContentLength();
builder.addPart("file", fileBody);
httpEntity = builder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
return httpResponse.getStatusLine().toString();
} else {
return getStringContent(httpResponse);
}
}
I am implement photo post on wall for facebook.when run in Emulator it works fine but not work in device?
Its show on device ERROR: Invalid android_key parameter.The key 3x3UBQp16... does not match any allowed key.Configure your app Key hashes at http://developers.facebook.com/apps/47775390...
I am try to another device but it not work.
Here is my code...
// Facebook
'
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 32665:
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
public void onComplete(Bundle values) {
}
public void onFacebookError(FacebookError e) {
}
public void onError(DialogError e) {
}
public void onCancel() {
}
public class StartFBupdateStatus extends AsyncTask<Void, Void, String> {
private String mFacebookToken;
public StartFBupdateStatus(String mFacebookToken) {
this.mFacebookToken = mFacebookToken;
}
#Override
protected void onPreExecute() {
// super.onPreExecute();
pDialog = ProgressDialog.show(getParent(), "Please wait...",
"Photo Uploading on Wall", true, true,
new OnCancelListener() {
public void onCancel(DialogInterface pd) {
try {
pDialog.dismiss();
pDialog = null;
taskFBupdateStatus.cancel(true);
} catch (Exception e) {
Log.e("Exception Cought in onCancel:- ",
e.toString());
}
}
});
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
String response = null;
try {
Bundle bundle = new Bundle();
bundle.putString(Facebook.TOKEN, this.mFacebookToken);
// String url = "https://graph.facebook.com/me/photos";
// String url = "https://graph.facebook.com/me/";
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inSampleSize = 1;
// ByteArrayOutputStream baos = new ByteArrayOutputStream(
// 32 * 1024);
if (pDetails.image_path != null) {
// byte[] data = null;
// Bitmap bmImg;
// URL myFileUrl = null;
try {
// myFileUrl = new URL(product.image);
// HttpURLConnection conn = (HttpURLConnection)
// myFileUrl
// .openConnection();
// conn.setDoInput(true);
// conn.connect();
// InputStream is = conn.getInputStream();
//
// bmImg = BitmapFactory.decodeStream(is);
//
// bmImg.compress(Bitmap.CompressFormat.PNG, 100, baos);
// data = baos.toByteArray();
// Log.v("SATERRA-FACEBOOK",
// "IMAGE Byte ARRAY SIZE::"+data.length);
bundle.putString("name", product.title);
bundle.putString("picture", pDetails.image_path);
// bundle.putString("message", "icon please");
// bundle.putString("link", "http://www.saterra.com");
// bundle.putString("description",
// product.short_description);
response = facebook.request("me/feed", bundle, "POST");
Log.d("UPDATE RESPONSE", "" + response);
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
// ********* Over Changes *********
// try {
// baos.close();
// } catch (IOException e1) {
// Log.d("baos error", e1.toString());
// }
if (connMgr.getActiveNetworkInfo() != null
&& connMgr.getActiveNetworkInfo().isAvailable()
&& connMgr.getActiveNetworkInfo().isConnected()) {
try {
// response = Util.openUrl(url, "POST", bundle);
JSONObject json = Util.parseJson(response);
Log.e("Response Photo String", " " + response);
handler.post(new Runnable() {
public void run() {
Toast.makeText(getParent(),
"Photo Uploaded...", Toast.LENGTH_LONG)
.show();
}
});
} catch (Exception e) {
Log.d("Some problem Please try again", e.toString());
}
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(getParent(),
"InternetConnectionNotAvailable",
Toast.LENGTH_LONG).show();
}
});
}
} catch (Exception e) {
// Log.e("ProductsDetailActivity",e.getMessage());
Log.e("ProductsDetailActivity", e.toString());
response = null;
}
// String s = facebook.getAccessToken()+"\n";
// s += String.valueOf(facebook.getAccessExpires())+"\n";
// s += "Now:"+String.valueOf(System.currentTimeMillis())+"\n";
return response;
}
#Override
protected void onPostExecute(String result) {
if (result == null) {
Toast toast = Toast.makeText(getParent(), "Facebook Error...",
Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else if (result.indexOf("Duplicate status message") > -1) {
Toast toast = Toast.makeText(getParent(),
"You already said that..", Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else if (result.indexOf("OAuthException") > -1) {
Toast toast = Toast.makeText(getParent(), "Facebook Error...",
Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
} else {
Toast toast = Toast.makeText(getParent(),
"Facebook update sent", Toast.LENGTH_LONG);
// toast.setGravity(Gravity.CENTER, 5, 5);
toast.show();
}
pDialog.dismiss();
}
}
private void fbAuthAndPost() {
facebook.authorize(getParent(), new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
Log.d(this.getClass().getName(),
"Facebook.authorize Complete: ");
saveFBToken(facebook.getAccessToken(),
facebook.getAccessExpires());
mFacebookToken = facebook.getAccessToken();
// updateStatus(values.getString(Facebook.TOKEN),
// message);
StartFBupdateStatus taskFBupdateStatus = new StartFBupdateStatus(
mFacebookToken);
taskFBupdateStatus.execute();
}
#Override
public void onFacebookError(FacebookError error) {
Log.d(this.getClass().getName(),
"Facebook.authorize Error: " + error.toString());
}
#Override
public void onError(DialogError e) {
Log.d(this.getClass().getName(),
"Facebook.authorize DialogError: "
+ e.toString());
}
#Override
public void onCancel() {
Log.d(this.getClass().getName(),
"Facebook authorization canceled");
}
});
}
private void saveFBToken(String token, long tokenExpires) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
prefs.edit().putString("FacebookToken", token).commit();
}
In my activity i have an AsyncTask, in which i had overridden doInBackGround.
In the same activity i have a camera intent to open the camera and allow user to take a pic
The problem is when i call the camera intent it is triggering the doInBackGround method i overrode. Which eventually gives me a SingleClientConnManager exception which asks me to release the client before allocating it again.
Here is my activity code:
public class UserProfileActivity extends Activity {
//many instance fiels here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
new LongOperation().execute("");
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
changeImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsLabel = (TextView) findViewById(R.id.userFriends_profile);
changeImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
//Point 1
}
});
//Point 2
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
private ProgressDialog dialog = new ProgressDialog(context);
#Override
protected String doInBackground(String... params) {
//Point 3
try {
HttpResponse response;
HttpPost httppost = new HttpPost(
"http://www.xxxxx.com/yyyy/zzzz");
//httpclient is global to maintain sessions
response = SignUpActivity.httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("error in reading input stream", e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
email = jObj.getString("email");
clickedUserId = jObj.getInt("user_id");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
friendsIds = new int[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
friendsIds[i] = friendsJsonArray.getJSONObject(i)
.getInt("user_id");
}
adapter = new ArrayAdapter<String>(context,
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
Log.d("error in creating json object", e.toString());
}
} catch (Exception e) {
//Point 5
Log.e("error main try", "Error in http connection" + e.toString());
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
changeImage.setText("Change image");
editInfo.setText("Edit");
friendsLabel.setText("Friends");
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
userImage.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
e1.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
} catch (IOException e2) {
e2.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Point 4
if (resultCode == RESULT_OK) {
if (data != null) {
photo = (Bitmap) data.getExtras().get("data");
userImage.setImageBitmap(photo);
}else{
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
}
}
here in the code Point 1, 2, 3, 4, 5 gives the sequence of code flow once i click the changeImage TextView.
Please help me in solving this scenario.
Thank You.
If I am correct the problem is because of your device orientation get changed when you open camera.That calls your activity's onCreate() method again
please insert this line to your activity in menifest that is causing problem
<activity
android:name="your activity" android:configChanges="keyboardHidden|orientation"
/>
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.