Creating a simple post in facebook via Android app - java

I'm trying to submit a simple post request using the facebook SDK.
Here's the code:
public void ShareLinkOnFacebook()
{
Facebook mFacebook = ((GlobalVars)getApplicationContext()).facebook;
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
params.putString("message", place.name );
params.putString("link", "http://www.facebook.com");
mAsyncFbRunner.request("me/feed", params, "POST", new RequestListener());
}
but I have compilation error saying that RequestListener cannot be Resolved to a type. what do I have to do in order to make it work?

Please check this listener.
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = mFacebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}

Try this Its my working code:-
on wallpost Button click:-
mPostButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mFacebook.dialog(Class.this, "feed",
new SampleDialogListener());
}
&
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
mDeleteButton.setVisibility(View.VISIBLE);
} else {
Log.d("Facebook-Example", "No wall post made");
}
}
}
& BaseDialogListner:---
public abstract class BaseDialogListener implements DialogListener {
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onCancel() {
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("message");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
final String text = "Your Wall Post: " + message;
VideoUpload.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText(text);
}
});
}
}
& BaseRequestListner:--
public abstract class BaseRequestListener implements RequestListener {
public void onFacebookError(FacebookError e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}

Related

How do I get return value onResponse

I know this is the answer, but I couldn't add it to my code.
How can I return value from function onResponse of Volley?
<------
like here I created interface.
I did it all.
I just don't know how to convert this my code to it, and how to use the return value in other activities.
public void priceDate(Context contex, final String coin) {
String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;
//String a =
//json_Parser = new JSONParser(_usd);
RequestQueue requestQueue = Volley.newRequestQueue(contex);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("Main",response.toString());}
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(100000);
try {
JSONObject Data = response.getJSONObject("Data");
JSONObject AggregatedData = Data.getJSONObject("AggregatedData");
try {
String Price = AggregatedData.getString("PRICE");
String formatPrice = formatter.format(Math.round(Float.valueOf(Price)));
_price.setText("Price :" + formatPrice);
} catch (Error e) {
_price.setText("Data Not Avvaliable");
}
try {
String Open = AggregatedData.getString("OPENDAY");
String formatOpen = formatter.format(Math.round(Float.valueOf(Open)));
_open.setText("Open :" + formatOpen);
} catch (Error e) {
_open.setText("Data Not Avvaliable");
}
try {
String Low = AggregatedData.getString("LOWDAY");
String formatLow = formatter.format(Math.round(Float.valueOf(Low)));
_low.setText("Low :" + formatLow);
} catch (Error e) {
_low.setText("Data Not Avvaliable");
}
try {
String High = AggregatedData.getString("HIGHDAY");
String formatHigh = formatter.format(Math.round(Float.valueOf(High)));
_high.setText("High :" + formatHigh);
} catch (Error e) {
_high.setText("Data Not Avvaliable");
}
try {
String Volume = AggregatedData.getString("VOLUMEDAY");
String formatVol = formatter.format(Math.round(Float.valueOf(Volume)));
_volume.setText("Volume :" + formatVol);
} catch (Error e) {
_volume.setText("Data Not Avvaliable");
}
try {
String LastUpdate = AggregatedData.getString("LASTUPDATE");
String convert = unix_time(Long.parseLong(LastUpdate));
_lastUpdate.setText("Last Update :" + LastUpdate);
} catch (Error e) {
_lastUpdate.setText("Data Not Avvaliable");
}
try {
String TradeId = AggregatedData.getString("LASTTRADEID");
_tradeId.setText("Trade Id :" + String.valueOf(Math.round(Float.parseFloat(TradeId))));
} catch (Error e) {
_tradeId.setText("Data Not Avvaliable");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
You can achieve this by using interface. Follow the below steps,
First create Interface in your application like,
public interface AsyncTaskListener {
void onRequestCompleted(JSONObject result, Integer statusCode);
}
And implement this interface in your activity where you want make request, Assume object of your volley class is objVolley, then your request will like below
public class YourActivity extends AppCompatActivity implements AsyncTaskListener {
public void priceDate(YourActivity.this, coin, YourActivity.this);
}
Then Your volley class and method like this,
public class PostDataHelper {
public void priceDate(Context contex, final String coin, final AsyncTaskListener asyncTaskListener) {
#Override
public void onResponse(JSONObject response) {
asyncTaskListener.onRequestCompleted(response, 200);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
asyncTaskListener.onRequestCompleted(response, 200);
}
});
}
}
Hope this will help you, Happy coding.
Your volley code is embedded into your activity code so there isn't much advantage to creating a interface.
You need to create a separate class for handling volley requests.
public class VolleyRequest {
VolleyCallback mResultCallback;
RequestQueue mRequestQueue;
public VolleyRequest(VolleyCallback resultCallback, Context context){
mResultCallback = resultCallback;
mRequestQueue = Volley.newRequestQueue(context);
}
public void cancelRequests(String TAG){
if(mRequestQueue != null){
mRequestQueue.cancelAll(TAG);
}
}
public void volleyGetRequest(String url, final String TAG) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (mResultCallback != null) {
mResultCallback.onSuccess(response, TAG);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mResultCallback != null) {
mResultCallback.onError(error, TAG);
}
}
});
jsonObjectRequest.setTag(TAG);
mRequestQueue.add(jsonObjectRequest);
}
}
Then create a interface class to handle the callbacks
public interface VolleyCallback {
void onSuccess(JSONObject response, String tag);
void onError(VolleyError error, String tag);
}
Then in your activity class
private void initvolley(){
VolleyCallback volleyCallback = new VolleyCallback() {
#Override
public void onSuccess(JSONObject response, String tag) {
switch (tag){
//add response handling code here
}
}
#Override
public void onError(VolleyError error, String tag) {
//handle error response here
}
};
VolleyRequest volleyRequest = new VolleyRequest(volleyCallback, this);
String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;
volleyRequest.volleyGetRequest(URL, request_tag/*Request tag incase you have multiple requests in same activity*/);
}

Update Data in Real Time when getting from server into RecylerView

I am getting json from Websockets and showing in recyler view. How do i update the list in real time when getting data from websockets?
My WebSocket Class
public final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
private static final String TAG = "DashBoardScreen.this";
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
initially when connection is established i send some text to server
webSocket.send(builder.toString());
}
#Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
in return server sends me data
output(text);
}
#Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
#Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
Log.d(TAG, "onClosing: ");
}
#Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
Log.d(TAG, "onClosed: ");
}
#Override
public void onFailure(WebSocket webSocket, Throwable t,Response response) {
super.onFailure(webSocket, t, response);
Log.d(TAG, "onFailure: ");
}
}
Output Method
private void output(final String text) {
runOnUiThread(new Runnable() {
#Override
public void run() {
*parsing json inside recyler view*
try {
JSONObject object = new JSONObject(text);
StringBuilder builder = new StringBuilder();
if (object.getBoolean("status")) {
JSONArray jsonArray = object.getJSONArray("events");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject values = jsonArray.getJSONObject(i);
final EventsDataModel dataModel = new EventsDataModel(
values.getString("service_Room_Number"),
values.getString("service_Name"),
values.getString("service_AssignedTo"),
values.getString("service_ID")
);
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
how exactly notifyDataSetChanged() works?
}
} else Toast.makeText(context, "No Events", Toast.LENGTH_SHORT).show();
System.out.println(builder.append(object.getString("status")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
Whenever your dataModel has the new data
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
If you perform the above operations and performing adapter.notifyDataSetChanged();
Will notify the adapter the new data has arrived and have to update the RecyclerView with new dataModel.

android, oauth 1.0a, scribe = exception

I am getting these error when retrieving ucoz.api.ru (oauth 1.0a) token using scribe library oauth (4.2.0) on android :
Caused by: com.github.scribejava.core.exceptions.OAuthException:
Response body is incorrect. Can't extract token and secret from this:
'{"oauth_token":"NAzoveaGm5XIlBvLcLRxUvamEK8P2.BAlQZ.M.aV","oauth_token_secret":"SJsqC0IfFAKS3BkdauQ3bY4ha01PDHTlFIy7GSro","oauth_callback_confirmed":"true"}'
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:42)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:32)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:19)
at
com.github.scribejava.core.oauth.OAuth10aService.getRequestToken(OAuth10aService.java:49)
at
com.vasyaevstropov.oauth10test.MainActivity.request(MainActivity.java:96)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:61)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:53)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841)
My source code:
final OAuth10aService service = new ServiceBuilder(CONSUMER_KEY)
.apiSecret(CONSUMER_SECRET)
.debug()
.build(UcozApi.instance());
final Scanner in = new Scanner(System.in);
// Obtain the Request Token
final OAuth1RequestToken requestToken = service.getRequestToken(); // <<--- Error is in this place
System.out.println(service.getAuthorizationUrl(requestToken));
final String oauthVerifier = in.nextLine();
// Trade the Request Token and Verfier for the Access Token
OAuth1AccessToken accessToken = null;
try {
accessToken = service.getAccessToken(requestToken, oauthVerifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Ucozapi module:
public class UcozApi extends com.github.scribejava.core.builder.api.DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken=%s";
private static final String REQUEST_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetrequesttoken";
private static final String ACCESS_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetaccesstoken";
protected UcozApi() {
}
private static final UcozApi INSTANCE = new UcozApi();
public static UcozApi instance() {
return INSTANCE;
}
#Override
public String getAccessTokenEndpoint() {
return ACCESS_TOKEN_RESOURCE;
}
#Override
public String getRequestTokenEndpoint() {
return REQUEST_TOKEN_RESOURCE;
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
}
Can somebody help me?
I answer my question. This code will work good with scribe-java library:
MainActivity:
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.vasyaevstropov.oauthtest.ucoz.UcozApi;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
Button button;
public WebView webView;
String verifier;
OAuth1RequestToken requestToken = null;
OAuth10aService service;
OAuth1AccessToken accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
service = new ServiceBuilder("murka1")
.apiSecret("DqUQJzeCPmwD9CRqbHo6sGBzKCb5U4")
.debug()
.build(UcozApi.instance());
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
String PROTECTED_RESOURCE_URL = "http://artmurka.com/uapi/shop/request?page=categories";
try {
requestToken = service.getRequestToken();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
String url = service.getAuthorizationUrl(requestToken);
return url;
}
#Override
protected void onPostExecute(String result) {
loadURL(result);
}
}.execute();
}
});
}
public void loadURL(final String url) {
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (url.contains("oauth_verifier")) {
webView.setVisibility(webView.GONE);
Log.d("Log.d", url);
verifier = uri.getQueryParameter("oauth_verifier");
Toast.makeText(getApplicationContext(), verifier, Toast.LENGTH_SHORT).show();
getAccessToken();
}
return false;
}
});
webView.loadUrl(url);
}
private void getAccessToken() {
new AsyncTask<Void, Void, OAuth1AccessToken>() {
protected OAuth1AccessToken doInBackground(Void... params) {
try {
accessToken = service.getAccessToken(requestToken, verifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return accessToken;
}
#Override
protected void onPostExecute(OAuth1AccessToken result) {
Toast.makeText(getApplicationContext(), "Token = " + result.getToken() + "Secret = " + result.getTokenSecret(), Toast.LENGTH_LONG).show();
}
}.execute();
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
UcozApi
public class UcozApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken?oauth_token=%s";
protected UcozApi() {
}
private static class InstanceHolder {
private static final UcozApi INSTANCE = new UcozApi();
}
public static UcozApi instance() {
return InstanceHolder.INSTANCE; }
#Override
public String getAccessTokenEndpoint(){
return "http://uapi.ucoz.com/accounts/oauthgetaccesstoken"; }
#Override
public String getRequestTokenEndpoint() {
return "http://uapi.ucoz.com/accounts/oauthgetrequesttoken"; }
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken()); }
#Override
public TokenExtractor<OAuth1AccessToken> getAccessTokenExtractor() {
return OAuth1AccessUcozTokenExtractor.instance();
}
#Override
public TokenExtractor<OAuth1RequestToken> getRequestTokenExtractor() {
return OAuth1RequestUcozTokenExtractor.instance();
}
}
OAuth1RequestUcozTokenExtractor
import com.github.scribejava.core.model.OAuth1RequestToken;
public class OAuth1RequestUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1RequestToken> {
protected OAuth1RequestUcozTokenExtractor() {
}
#Override
protected OAuth1RequestToken createToken(String token, String secret, String response) {
return new OAuth1RequestToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1RequestUcozTokenExtractor INSTANCE = new OAuth1RequestUcozTokenExtractor();
}
public static OAuth1RequestUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
OAuth1AccessUcozTokenExtractor
public class OAuth1AccessUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1AccessToken> {
protected OAuth1AccessUcozTokenExtractor() {
}
#Override
protected OAuth1AccessToken createToken(String token, String secret, String response) {
return new OAuth1AccessToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1AccessUcozTokenExtractor INSTANCE = new OAuth1AccessUcozTokenExtractor();
}
public static OAuth1AccessUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
AbstractOauth1UcozTokenExtractor
public abstract class AbstractOauth1UcozTokenExtractor<T extends OAuth1Token> implements TokenExtractor<T> {
private Pattern OAUTH_TOKEN_PATTERN = Pattern.compile("\"oauth_token\"\\s*:\\s*\"(\\S*?)\"");
private Pattern OAUTH_TOKEN_SECRET_PATTERN = Pattern.compile("\"oauth_token_secret\"\\s*:\\s*\"(\\S*?)\"");
#Override
public T extract(Response response) throws IOException {
final String body = response.getBody();
Preconditions.checkEmptyString(body,
"Response body is incorrect. " + "Can't extract a token from an empty string");
final String token = extract(body, OAUTH_TOKEN_PATTERN);
final String secret = extract(body, OAUTH_TOKEN_SECRET_PATTERN);
return createToken(token, secret, body);
}
private String extract(String response, Pattern p) {
final Matcher matcher = p.matcher(response);
if (matcher.find() && matcher.groupCount() >= 1) {
return OAuthEncoder.decode(matcher.group(1));
} else {
throw new OAuthException("Response body is incorrect. Can't extract token and secret from this: '"
+ response + "'", null);
}
}
protected abstract T createToken(String token, String secret, String response);
}

java.lang.ClassCastException: java.util.HashMap cannot be cast to com.backendless.services.messaging.MessageStatus

getting a crash after sending message (it's a messaging app):
AndroidRuntime: FATAL EXCEPTION: main
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.backendless.services.messaging.MessageStatus
at com.braunst.androidchatsdk.firebaseplugin.firebase.backendless.BBackendlessHandler$2.handleResponse(BBackendlessHandler.java:123)
at com.backendless.async.message.AsyncMessage$ResponseHandler.handle(AsyncMessage.java:64)
at com.backendless.async.message.AsyncMessage.handleCallback(AsyncMessage.java:41)
at com.backendless.core.AndroidCarrier$1.handleMessage(AndroidCarrier.java:37)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
When clicking on the BBackendlessHandler.java takes to the following line ( Backendless.Messaging.publish(channel, data.toString(), publishOptions, deliveryOptions, new AsyncCallback())from the code below:
/**
* Created by Erk on 27.07.2016.
*/
public class
BBackendlessHandler implements BPushHandler, BUploadHandler {
private static final String TAG = BBackendlessHandler.class.getSimpleName();
private static final boolean DEBUG = Debug.BBackendlessPushHandler;
private boolean isSubscribed;
private Context context;
private String channel;
public void setContext(Context ctx) {
context = ctx;
}
public void initWithAppKey(String appKey, String secretKey, String versionKey)
{
Backendless.initApp(context, appKey, secretKey, versionKey);
}
#Override
public boolean subscribeToPushChannel(final String channel) {
if (!BNetworkManager.sharedManager().getNetworkAdapter().backendlessEnabled())
return false;
try {
Backendless.Messaging.registerDevice(context.getString(com.braunst.amharicmessages.R.string.google_project_number), channel, new AsyncCallback<Void>() {
#Override
public void handleResponse(Void response) {
if(DEBUG) Timber.v("Device has been subscribed to channel " + channel);
}
#Override
public void handleFault(BackendlessFault fault) {
if(DEBUG) Timber.v("Device subscription failed. " + fault.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
public boolean unsubscribeToPushChannel(String channel) {
if (!BNetworkManager.sharedManager().getNetworkAdapter().backendlessEnabled())
return false;
// TODO: unsubscribe from push channel backendless
// http://support.backendless.com/topic/push-notification-unregister-from-a-specific-channel
DeviceRegistration devReg = null;
try {
devReg = Backendless.Messaging.getDeviceRegistration();
} catch (Exception e) {
e.printStackTrace();
}
if(devReg != null) {
Backendless.Messaging.unregisterDevice();
}
return true;
}
#Override
public void pushToChannels(Collection<String> channels, JSONObject data) {
// Configure the header
PublishOptions publishOptions = new PublishOptions();
try {
publishOptions.putHeader("android-ticker-text", data.getString(BDefines.Keys.CONTENT));
publishOptions.putHeader("android-content-title", "Message from " + data.getString(BDefines.Keys.MESSAGE_SENDER_NAME));
publishOptions.putHeader("android-content-text", data.getString(BDefines.Keys.MESSAGE_PAYLOAD));
publishOptions.setPublisherId(data.getString(BDefines.Keys.MESSAGE_SENDER_ENTITY_ID));
} catch (JSONException e) {
e.printStackTrace();
}
// Only push to android devices
DeliveryOptions deliveryOptions = new DeliveryOptions();
deliveryOptions.setPushPolicy(PushPolicyEnum.ONLY);
deliveryOptions.setPushBroadcast(PushBroadcastMask.ALL);
// Publish a push notification to each channel
for(final String channel : channels) {
try {
data.put(BDefines.Keys.Channel, channel);
} catch (JSONException e) {
e.printStackTrace();
}
Backendless.Messaging.publish(channel, data.toString(), publishOptions, deliveryOptions, new AsyncCallback<MessageStatus>() {
#Override
public void handleResponse(MessageStatus response) {
if(DEBUG) Timber.v("Message published to chanllel:" + channel );
}
#Override
public void handleFault(BackendlessFault fault) {
if (DEBUG) Timber.v("Publish failed, " + fault.getMessage());
}
});
}
}
#Override
public Promise uploadFile(byte[] data, String name, String mimeType) {
return null;
}
}

Android: Progress Bar to Upload Data to the Server

In my application some data is there which is wrapped into an object.
I am sending this object to the server. Everything work correctly.
Here I want to show progress bar when the data is loading to the server.
For this I am using this code:
ProgressThread progThread;
ProgressDialog progDialog;
int typeBar;
int delay = 40;
int maxBarValue = 200;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progDialog.setMax(maxBarValue);
progDialog.setMessage("Data uploading to the Server..");
progThread = new ProgressThread(handler);
progThread.start();
return progDialog;
default:
return null;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// Get the current value of the variable total from the message data
// and update the progress bar.
int total = msg.getData().getInt("total");
progDialog.setProgress(total);
if (total <= 0) {
dismissDialog(typeBar);
progThread.setState(ProgressThread.DONE);
}
}
};
private class ProgressThread extends Thread {
final static int DONE = 0;
final static int RUNNING = 1;
Handler mHandler;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
#Override
public void run() {
mState = RUNNING;
total = maxBarValue;
while (mState == RUNNING) {
connectServerClass.saveOnServer(Object);
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total--; // Count down
}
}
public void setState(int state) {
mState = state;
}
}
When user click on button then:
typeBar = 1;
showDialog(typeBar);
connectServerClass.saveOnServer(Object)
by the above line I am sending object to the server. Actually I am sending data to the other class which is connectServerClass and this class send object to the server.
but this code not work correctly. This code connect to the server lots of time.
I use the following Code :
private class Uploader extends AsyncTask<Void, String, Integer>
{
private List<File> files;
private boolean canceled;
private int uploaded;
private Account account;
private ProgressDialog uploadSeekBar;
public Uploader(Account a, List<File> files)
{
this.account = a;
this.files = files;
}
#Override
protected void onPreExecute()
{
uploadSeekBar.setMax(files.size());
uploadSeekBar.setProgress(0);
uploadSeekBar.setVisibility(View.VISIBLE); //Error: the method setVisibility is undefined
}
#Override
protected void onPostExecute(Integer result)
{
uploadSeekBar.setVisibility(View.INVISIBLE);
Toast.makeText(Upload.this, result + " files uploaded", // Error: Upload cannot be resolved to a type
Toast.LENGTH_LONG).show();
}
#Override
protected void onCancelled()
{
// XXX need a way to actually cancel the last upload
Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
.show();
this.canceled = true;
uploadSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected Integer doInBackground(Void... voids)
{
uploaded = 0;
try
{
Iterator<File> it = this.files.iterator();
while (!canceled && it.hasNext())
{
File file = it.next();
it.remove();
String msg = "";
try
{
if (debugMode) // what is this debugMode
{
//Put your uploading code here.
msg = ("fake uploading " + file);
Thread.sleep(3000);
} else
{
msg = ("uploading: " + file);
controller.uploadFile(file, this.account); //Error: controller cannot be resolved
}
uploaded++;
publishProgress(msg);
} catch (IOException e)
{
controller.te("error uploading file: " + file);
controller.te("error uploading file: " + e);
} catch (InterruptedException e)
{
}
}
} catch (Exception e)
{
publishProgress("error uploading: " + e);
}
return uploaded;
}
#Override
protected void onProgressUpdate(String... strings)
{
uploadSeekBar.setProgress(uploaded);
updateUploadMessage(files.size());
Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show(); //Error: The method updateUploadMessage(int) is undefined for the type FirstActivity.Uploader
}
}
But I facing some error which I mention as comment in the right side of that line. Please suggest me.
I will strongly recommend you to Use AsyncTask.
Below Code snippet will help you on How your AsyncTask should look like.
package org.sample;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import android.accounts.Account;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Toast;
private class Uploader extends AsyncTask<Void, String, Integer>
{
private List<File> files;
private boolean canceled;
private int uploaded;
public Uploader(Account a, List<File> files)
{
this.account = a;
this.files = files;
}
#Override
protected void onPreExecute()
{
uploadSeekBar.setMax(files.size());
uploadSeekBar.setProgress(0);
uploadSeekBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Integer result)
{
uploadSeekBar.setVisibility(View.INVISIBLE);
Toast.makeText(Upload.this, result + " files uploaded",
Toast.LENGTH_LONG).show();
}
#Override
protected void onCancelled()
{
// XXX need a way to actually cancel the last upload
Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
.show();
this.canceled = true;
uploadSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected Integer doInBackground(Void... voids)
{
uploaded = 0;
try
{
Iterator<File> it = this.files.iterator();
while (!canceled && it.hasNext())
{
File file = it.next();
it.remove();
String msg = "";
try
{
if (debugMode)
{
//Put your uploading code here.
msg = ("fake uploading " + file);
Thread.sleep(3000);
} else
{
msg = ("uploading: " + file);
controller.uploadFile(file, this.account);
}
uploaded++;
publishProgress(msg);
} catch (IOException e)
{
controller.te("error uploading file: " + file);
controller.te("error uploading file: " + e);
} catch (InterruptedException e)
{
}
}
} catch (Exception e)
{
publishProgress("error uploading: " + e);
}
return uploaded;
}
#Override
protected void onProgressUpdate(String... strings)
{
uploadSeekBar.setProgress(uploaded);
updateUploadMessage(files.size());
Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show();
}
}

Categories

Resources