I have done login in facebook integration and after login i want to post some message on the wall but i 'm not getting success as I am getting this error
**{Response: responseCode: 200, graphObject: null, error: {HttpStatus: 200, errorCode: 3, errorType: null, errorMessage: Unknown method}, isFromCache:false}**
my code is as follows
postbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
final Bundle params = new Bundle();
params.putString("message", "Test");
//params.putString("name", "American Virgin");
//params.putString("link", "http://bit.ly/12345");
//params.putString("description", "A Freshman College Girl on a scholarship from an ...");
//http://graph.facebook.com/100000431012652/picture?type=square
final Request postToWall = Request.newRestRequest(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
postToWall.setCallback( new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
Log.i("onCompleted", response.toString());
}
});
Request.executeBatchAsync(postToWall);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("onCompletedException", e.toString());
}
}
});
}
Please suggest me.
for login i am using the below code
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// Log.i("session.isOpened", "session.isOpened");
//session.requestNewReadPermissions(newPermissionsRequest);
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
//session.requestNewReadPermissions(newPermissionsRequest);
//System.out.println("Response : "+response.toString());
Log.i("Response", response.toString());
//URL image_value = new URL("http://graph.facebook.com/"+id+"/picture?style=small" );
if (user != null) {
Log.i("USERName", ""+user.getName());
Log.i("Birthday", ""+user.getBirthday());
Log.i("LastName", ""+user.getLastName());
Log.i("FirstName", ""+user.getFirstName());
Log.i("getId", ""+user.getId());
Log.i("email", " "+user.getLink()+" email : ) "+user.asMap().get("email"));
Log.i("location", ""+user.asMap().get("location"));
Log.i("gender", ""+user.asMap().get("gender"));
saveusrname = ""+user.getName().trim();
imagstring = "http://graph.facebook.com/"+""+""+user.getId()+"/picture?type=square";
// imagstring = "http://graph.facebook.com/"+""+""+user.getId()+"/picture?type=large";
//type=square
Log.i("imagstring", imagstring);
finish();
/* String username = ""+user.getName();
String Birthday = ""+user.getBirthday();
String email = ""+user.asMap().get("email");
String location = ""+user.asMap().get("location");
String gender = ""+user.asMap().get("gender");*/
new SendfacebookValue().execute(response.toString(),saveusrname.toString(),imagstring);
/*Intent i =new Intent(FacebookLogin.this, ScreenNameActivity.class);
startActivity(i);*/
/* Intent i =new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);*/
//finish();
}
}
});
}
}
});
I use this methods to post record on facebook wall. I think it will help you, check your GraphObject
private void postStatusUpdate() {
Log.d("myLogs", "Test");
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
Log.d("myLogs", "Test 1");
final String message = "massage to post";
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
}
}
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = "Success";
alertMessage = "All is good";
} else {
title = "Error";
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
Related
I am creating Application in which I have give functionality like Facebook timeline where people can update their story and any user can like or comment on the story. Everything is working fine but what I am facing issue is that when any user update story then data of updated story get saved on server but not added in recycle view at same time. When User go back and again comes on timeline screen then list will get update. How can I solve this problem ?
Custom Adapter
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
holder.txtComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
Intent intent = new Intent(context, StoryDetailActivity.class);
intent.putExtra("storyId",ide);
context.startActivity(intent);
}
});
holder.txtCommentLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
Intent intent = new Intent(context, StoryDetailActivity.class);
intent.putExtra("storyId",ide);
context.startActivity(intent);
}
});
holder.imageLike.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
TimelineActivity t = new TimelineActivity();
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
likeStory(ide,t.token);
return false;
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
private void likeStory(final String story_id, final String token) {
// Tag used to cancel the request
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.likeStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_id", story_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
TimeLineActivity
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
adapter.notifyDataSetChanged();
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
You need to implement some sort of polling mechanism on server end to do this. There's a workaround for it but it's not considered good practice. You can use a Timer to call your getTimeline function periodically to update the recycler view. Something like this in your onCreate:
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, page);
}
});
}
}, 0, your_time_in_milliseconds);
You can even do this asynchronously by using AsyncTask in Android.
I can buy only one item ("productitem1"). If I had purchase this item, I can't purchase it again. But I need it to buy it several times. In my Google Play Console, I can only choose between "Managed In-app Products" and "subs". I have setting it up to "Managed In-app Products".
#Override
protected void onActivityResult(int request, int response, Intent data) {
if (request == 42) {
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATE_SIGNATURE");
if (response == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
String productId = jo.getString("productId");
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.e(getClass().getSimpleName(), "JSONException", e);
}
}
}
}
btnBuy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = "productitem1";
try {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), name, "inapp", "");
if(buyIntentBundle.getInt("RESPONSE_CODE")==0) {
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(
pendingIntent.getIntentSender(), 42, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
}
} catch (Exception e) {
Log.e(Start.this.getClass().getSimpleName(),"Exception:",e);
}
}
});
Before you can buy another item with the same SKU, you need to consume it using one of the methods available from the In-App Billing API like IabHelper.consumeAsync()
mHelper.consumeAsync(inventory.getPurchase(SKU_ITEM), mConsumeFinishedListener);
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
// provision the in-app purchase to the user
// (for example, credit 50 gold coins to player's character)
} else {
// handle error
}
}
};
More info here: https://developer.android.com/training/in-app-billing/purchase-iab-products.html#Consume
IabHelper.OnConsumeFinishedListener onConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
#Override
public void onConsumeFinished(Purchase purchase, IabResult result) {
try {
Log.d("Tag", "this is onConsumeFinished - "+result.toString()+" and purchased"+purchase.toString());
mHelper.consumeAsync(purchase,onConsumeFinishedListener);
} catch (IabHelper.IabAsyncInProgressException e) {
Log.d("Tag", "this is onConsumeFinished Error - "+e.toString());
e.printStackTrace();
}
}
};
I am trying to make a volley PUT request to upload an image, Since httpEntity is deprecated now, I had to do some other research, I came across these solutions and tried to implement them into my code :
1. https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
2. How to send multipart request using Volley without HttpEntity?
3. Working POST Multipart Request with Volley and without HttpEntity
but still I cannot upload my image. The image I want to upload is either captured from the camera or selected in the gallery, and it is executed onClick.
ProfileSetting.java
public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_setting);
CustomerIcon = (ImageView) findViewById(R.id.CustomerIcon);
confirm_button = (Button) findViewById(R.id.confirm_button);
CustomerIcon.setOnClickListener(new ImageView.OnClickListener(){
public void onClick(View v){
showPickImageDialog();
}
});
confirm_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view) {
//PUT VOLLEY
saveProfileAccount();
}
});
}
private void showPickImageDialog() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
builderSingle.setTitle("Choose Profile Icon");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
ProfileSetting.this,
android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Gallery");
arrayAdapter.add("Camera");
builderSingle.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
case 1:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
}
}
});
builderSingle.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
}
}
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "https://url to put image to";
SharedPreferences sp1=this.getSharedPreferences("FINALTOKEN", Context.MODE_PRIVATE);
final String finalToken = sp1.getString("FINALTOKEN","");
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.PUT, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject result = new JSONObject(resultResponse);
String status = result.getString("status");
String message = result.getString("message");
if (status.equals(Constant.REQUEST_SUCCESS)) {
// tell everybody you have succeed upload image and post strings
Log.i("Messsage", message);
} else {
Log.i("Unexpected", message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers= new HashMap<>();
headers.put("Authorization",finalToken);
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", ImageConverter.getFileDataFromDrawable(getBaseContext(), CustomerIcon.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
}
VolleyMultipartRequest.java and VolleySingleton.java I am using the same class as what my first link has.
My errors are first of all I cannot resolve symbol 'Constant' in the if statement:
if (status.equals(Constant.REQUEST_SUCCESS))
so I tried commenting the statement, after running the code I got the following error:
BasicNetwork.performRequest: Unexpected response code 500 for https://my url
W/System.err: org.json.JSONException: No value for status
I am not sure what is causing my problem,please help, thank you!
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* #param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
//Your response here
}
}
mChoosenFile is your image file
First of all convert your image bitmap to base64 string using the following code:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Then make a PUT Request like the following one and pass the base64 string as a parameter of the request
url = "http://example.com";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("imageString", base64String);
return params;
}
};
queue.add(putRequest);
Refer Android Volley Tutorial if you face any difficulty in implementing volley request.
I'm facing an issue with AsyncTask doInBackground method, I don't know how to stop this method from running.
I'm working on an application that has a login screen which retrieves information about the logged user. The problem is when I enter a wrong password or username and then when I re-enter the correct data, my application crashes and I get
"java.lang.IllegalStateException: Cannot execute task: the task has
already been executed"
How can I stop this thread from running? Here is the code:
LoginActivity.java
public class LoginActivity extends Activity implements LoginParser.GetLoginListener{
public LoginParser parser1;
public EditText ETUsername;
public EditText ETPassword;
//private LoginParser lb;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
parser1 = new LoginParser();
ETUsername = (EditText)findViewById(R.id.ET1);
ETPassword = (EditText)findViewById(R.id.ET2);
final Button button = (Button) findViewById(R.id.loginBut);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String UserName = ETUsername.getText().toString();
String Password = ETPassword.getText().toString();
Log.e("LoginAct .. userName: ", UserName);
Log.e("LoginAct .. Password: ", Password);
if (UserName.isEmpty() || Password.isEmpty()) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Please Enter your Username and Password")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
else{
parser1.getLoginInfo(UserName, Password);
parser1.setListener(LoginActivity.this);
}
} // end of button on click
} );
}
#Override
public void didReceivedUserInfo(String displayName) {
if(displayName != null) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Welcome").setMessage("Welcome " + displayName)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent (LoginActivity.this, MainActivity.class);
startActivity(in);
}
}).show();
}
else {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Error in login ID or Password, Please try again later")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
LoginParser.java
public class LoginParser extends AsyncTask <Void,Void,String> {
private String requestURL;
public String UserName ;
public String Password ;
public interface GetLoginListener
{
public void didReceivedUserInfo (String displayName);
}
private GetLoginListener listener;
public GetLoginListener getListener() {
return listener;
}
public void setListener(GetLoginListener listener) {
this.listener = listener;
}
public void getLoginInfo(String userName , String password)
{
requestURL = "some link";
this.UserName = userName ;
this.Password = password ;
execute(); // it will call doInBackground in secondary thread
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(requestURL);
HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();
String jsonString = "LID="+ UserName +"&PWD="+Password+"&Passcode=****";
Log.e("LoginParser","JSONString: " + jsonString);
urlConnection1.setDoOutput(true);
urlConnection1.setRequestMethod("POST");
urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection1.setRequestProperty("charset","utf-8");
PrintWriter out = new PrintWriter(urlConnection1.getOutputStream());
// out.print(this.requestMessage);
out.print(jsonString);
out.close();
int statusCode = urlConnection1.getResponseCode();
Log.d("statusCode", String.valueOf(statusCode));
StringBuilder response = new StringBuilder();
byte[] data = null;
if (statusCode == HttpURLConnection.HTTP_OK)
{
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection1.getInputStream()));
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
data = response.toString().getBytes();
}
else {
data = null;// failed to fetch data
}
String responseString = new String(data);
Log.e("doInBackground", "responseString" + responseString);
JSONObject jsonObject2 = new JSONObject(responseString);
String Status = jsonObject2.getString("Status");
Log.e("Status", Status);
if (Status.equals("s")) {
Log.i("Status:", "Successful");
String displayName = jsonObject2.getString("DisplayName");
return displayName;
}
else {
return null;
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String displayName) {
super.onPostExecute(displayName);
Log.e("onPost: ","onPost");
listener.didReceivedUserInfo(displayName);
}
}
Thank you for your help.
The "can't re-execute task" error can be solved by creating a new instance of the AsyncTask. You can't call execute twice on the same instance, but you can make as many instances as you want.
Stopping the execution won't help that error. The problem isn't that its currently running, the problem is that you need to create a new instance and run that instead.
You can cancel Async task using continuous check of isCancel in your doInBackground method.
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
Hope this will help you.
I am posting on my wall in facebook sdk android but I am getting
I'll post my code below
{Response: responseCode: 403, graphObject: null, error: {HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200) The user hasn't authorized the application to perform this action}, isFromCache:false}
private void postStatusUpdate(final String fbpost) {
Log.d("postStatusUpdate",fbpost);
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#Override
public void call(final Session session, SessionState state, Exception exception) {
if(session.isClosed()){
Log.i("postStatusUpdate session.isClosed", "message not posted session is closed");
}
if (session.isOpened()) {
Log.i("session.isOpened", "session.isOpened");
if (!session.isOpened()) {
Log.w("myConsultant11111111111","Session closed");
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest(TabActivity.this);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("publish_stream","publish_actions"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
session.openForPublish(openRequest);
}
}
Log.i("session.getPermissions() tab", ""+session.getPermissions());
//fbpostcheck = "if";
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
//session.requestNewReadPermissions(newPermissionsRequest2);
if (user != null) {
try {
Session session = Session.getActiveSession();
//session.requestNewReadPermissions(newPermissionsRequest);
if (!session.isOpened() && !session.isClosed()) {
// session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
// Session.openActiveSession(this, true, statusCallback);
Log.d("myLogs", "Test 1");
final String message = fbpost;
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
#Override
public void onCompleted(Response response) {
//showPublishResult(message, response.getGraphObject(), response.getError());
Log.i("onCompleted", response.toString());
Log.i("getGraphObject", ""+response.getGraphObject());
showPublishResult(message, response.getGraphObject(), response.getError());
}
private void showPublishResult(String message,GraphObject graphObject,FacebookRequestError error) {
// TODO Auto-generated method stub
String title = null;
String alertMessage = null;
if (error == null) {
title = "Success";
alertMessage = "All is good";
//Toast.makeText(getApplicationContext(),"Posted successfully", Toast.LENGTH_SHORT).show();
AppMsg.makeText(TabActivity.this, "Posted to facebook", AppMsg.STYLE_INFO).show();
} else {
title = "Error";
alertMessage = error.getErrorMessage();
Log.i("alertMessage", alertMessage.toString());
AppMsg.makeText(TabActivity.this, "Error in Posting Message on facebook\n"/*+alertMessage*/, AppMsg.STYLE_INFO).show();
//Toast.makeText(getApplicationContext(),alertMessage, Toast.LENGTH_LONG).show();
}
}
});
request.executeAsync();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Exception user data", e.toString());
}
}
}
});
}
}
});
}
just open the permission dialogue with the publish_action permission then update your access token and then post your message
facebook Post on your behalf is not working in android facebook sdk 3.0.2