Thread-safe asynchronous Retrofit request - android

I'm struggling for few weeks now with this issue. I'm posting geolocation points to a server using Retrofit 2.0. I'm using a IntentService that I call every now and then when I have a new point to post.
For some reason, the server record the same point multiple time creating LOTS of duplicates. It seems that when I call my service and it's already active, it's will query the points and start a new request using some of the same points as was queried by the previous request. I also delete the point only when the request succeed. Is there a way to wait until executing the next batch of points?
How can I wait until all the processed point are sent to the server?
private String postAmazonPoints() throws IOException, JSONException {
ArrayList<EntityPoint> points = new ArrayList<>(GenericDAO.getInstance(EntityPoint.class).queryForAll());
if (points.size() == 0) {
return RESULT_OK;
}
if (connectAmazonApi()) {
int pointSize = points.size();
if(pointSize>5){
for(int i = 0; i<pointSize; i+=5){
int end = i+5;
if( end > pointSize ){
end = pointSize;
}
paginatePostPoint(points.subList(i, end-1));
}
}else{
paginatePostPoint(points.subList(0, pointSize-1));
}
}
return RESULT_OK;
}
private void paginatePostPoint(final List<EntityPoint> points) throws IOException, JSONException {
EntityPoints mPoints = new EntityPoints(points);
Call<ResponseBody> call = amazonServices.postGeopoints(mPoints);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
JSONObject json;
try {
json = (response != null ? new JSONObject(response.body().string()) : null);
Log.e(TAG, json.toString());
if(RESULT_OK.equals(handleJsonRequest(json))){
deleteDatabasePoints(points);
Log.e(TAG, "Point are correctly posted");
}else{
addFirebaseMsg(json.toString());
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
} else {
try {
addFirebaseMsg(response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
addFirebaseMsg(t.getMessage());
}
});
}
private void addFirebaseMsg(String message){
isConnectedToAmz = false;
Bundle params = new Bundle();
params.putString(FirebaseAnalytics.Param.VALUE, message.substring(0, Math.min(message.length(), 30)));
mFirebaseAnalytics.logEvent(Constants.EVENT_TAG_ERROR, params);
Log.d(TAG, message);
}
private boolean connectAmazonApi() {
if (isConnectedToAmz) {
return true;
}
Call<ResponseBody> call = amazonServices.postAuthenticate(settings.getString("token", ""),settings.getString(MyInstanceIDFireService.FIREBASE_TOKEN, ""), settings.getString("id", ""));
String errMsg = "";
try {
ResponseBody response = call.execute().body();
JSONObject json = (response != null ? new JSONObject(response.string()) : null);
if (json != null) {
Log.e(TAG, "Response: " + json.toString());
RetrofitCreator.setAmazonToken(json.getString("token"));
isConnectedToAmz = true;
return true;
}
Log.w(TAG, "Impossible to connect to Amazon API : " + json);
} catch (JSONException e) {
errMsg = e.getMessage();
} catch (IOException e) {
errMsg = e.getMessage();
}
Log.w(TAG, "Impossible to connect to Amazon API");
Bundle params = new Bundle();
params.putLong(FirebaseAnalytics.Param.VALUE, 1);
params.putString(FirebaseAnalytics.Param.VALUE, errMsg.substring(0, Math.min(errMsg.length(), 30)));
mFirebaseAnalytics.logEvent(Constants.EVENT_AMAZON_UNAVAILABLE, params);
return false;
}

You can use .execute instead of .enqueue and request will be synchronous, but in this case you should care about creating another thread for it. Create some service with asynсtask for example with queue.

Related

Android studio web socket - Error receiving multiple JSON objects at once

I am struggling with something that really p*sses me off for several hours.
My android app manages to connect to a websoket, and receives json data which for now has worked perfectly, and here is the code for this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
This code above as I said works perfectly, and i get the data in everytime. HOWEVER, HOWEVER, HOWEVER: If i try to receive 2 json-objects at the sametime through this emittener, it does not work!!!!
Here is example when i try to receive multiple JSON objects, and NONE of them works!
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetFromSensor = new JSONObject( (String) args[0]);
int targetNum = incomingTargetFromSensor.getInt("target_number_count");
showTargetRep(targetNum); //NOT WORKING!
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position); //NOT WORKING!
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
In the first example I could receive the position data, and the code is exactly similar as the example above, but for some reasons it can not recevice data when i try to receive another JSON object.
Another example of why I always disliked JSON object.
Any help plz?
The solution at the end was to add multiple try/catches like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetRepFromSensor = new JSONObject((String ) args[0]);
int target_rep = incomingTargetRepFromSensor.getInt("target_repetition_count");
showTargetRep(target_rep);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingDataFromSensor = new JSONObject((String ) args[0]);
double the_position = incomingDataFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingTargetSetFromSensor = new JSONObject((String ) args[0]);
int target_set = incomingTargetSetFromSensor.getInt("target_set_count");
showTargetSet(target_set);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingRepsFromSensor = new JSONObject((String ) args[0]);
int the_repetitions = incomingRepsFromSensor.getInt("repetitions");
showCurrentReps(the_repetitions);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingSetsFromSensor = new JSONObject((String ) args[0]);
int the_sets = incomingSetsFromSensor.getInt("sets");
showCurrentSets(the_sets);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}

Not able to upload the audio file along with the data to the server through nougat version of android

I'm not able to upload the audio file to the server through the nougat version of android, The audio is recorded through the media recorder and saved on the device.Here is the code, the same is working for all the versions of android except nogat ,though in nogat the media is recorded and saved in device , but it not being uploaded on the server.
private void submitRecording() {
CallLogsModel.idle++;
final String filename = "file.MP3";
final String path = Environment.getExternalStorageDirectory() + "/" + filename;
JSONObject jObject = new JSONObject();
String json = "";
try {
String uniquecode = PreferenceConfigration.getPreference(Constants.PreferenceConstants.UNIQUE_CODE);
String token= UtilityMethods.tokenValue();
Log.e("Token",token);
jObject.put("uniquecode",uniquecode);
jObject.put("lead_id", CallLogsModel.leads);
jObject.put("duration",getAudioDuratiion());
jObject.put("date_of_call", getDate());
jObject.put("time_of_call",startTime);
jObject.put("device", PreferenceConfigration.getPreference(Constants.PreferenceConstants.DEVICE).toString());
jObject.put("token", token);
Log.e("formed",jObject.toString());
if (path.equals("") || path.equals(null) || path.equals("null")) {
jObject.put("aboutphoto", "nophoto");
}
else
{
}
json = jObject.toString();
} catch (Exception e) {
}
Log.e("raisetic", json);
OKhttpConnect.doPosttRequestWithMutipart("all_data", "attachment", "http://armsenterprise.com/api-new/kre-app/save_call_log.php", json, Environment.getExternalStorageDirectory() + "/" + filename, new HTTPcallback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e("Failure",e.toString());
}
#Override
public void onResponse(final String response) {
if (response != null && !(response.isEmpty())) {
final JSONObject jsonObject;
try
{
CallLogsModel.idle++;
jsonObject = new JSONObject(response);
Log.e("ResponseCall", response);
} catch (Exception e)
{
e.printStackTrace();
}
} else {
((Activity) MainActivity.context).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Error in submission", Toast.LENGTH_SHORT).show();
}
});
}
}
});
((Activity) MainActivity.context).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.context, "Raising Ticket ...", Toast.LENGTH_SHORT).show();
}
});
}

Getting JSONException with Retrofit 2 on Android

I am using Fabric.io Twitter Kit. Created a custom service class and used Retrofit to convert the interface within that class. Code at the bottom (CustomTwitterApiClient Class).
I either get NullPointerException and if I catch that, I get JSONException. As can be seen in the log, I can get trends response but I cant read it. If I try to readLine() it and append it to a StringBuilder, I get null.
I wrote the code with the guidance of this SO answer.
What I am doing wrong ?
Thanks in advance.
PS: Those extra exception handlers just to get a clean log.
D/LOG-DEBUG: Line 86 : [{"trends":[{"name":"#Worlds","url":"http:\/\/twitter.com\/search?q=%23Worlds","promoted_content":null,"query":"%23Worlds","tweet_volume":99974},{"name":"#LaNocheDeML","url":"http:\/\/twitter.com\/search?q=%23LaNocheDeML","promoted_content":null,"query":"%23LaNocheDeML","tweet_volume":56697},{"name":"#CLEMVSFSU","url":"http:\/\/twitter.com\/search?q=%23CLEMVSFSU","promoted_content":null,"query":"%23CLEMVSFSU","tweet_volume":10016},{"name":"#\u0634\u064A_\u062A\u062D\u0628_\u062A\u0634\u0645\u0647","url":"http:\/\/twitter.com\/search?q=%23%D8%B4%D9%8A_%D8%AA%D8%AD%D8%A8_%D8%AA%D8%B4%D9%85%D9%87","promoted_content":null,"query":"%23%D8%B4%D9%8A_%D8%AA%D8%AD%D8%A8_%D8%AA%D8%B4%D9%85%D9%87","tweet_volume":52441},{"name":"#DiosdadoEsPueblo","url":"http:\/\/twitter.com\/search?q=%23DiosdadoEsPueblo","promoted_content":null,"query":"%23DiosdadoEsPueblo","tweet_volume":44538},{"name":"Juanma","url":"http:\/\/twitter.com\/search?q=Juanma","promoted_content":null,"query":"Juanma","tweet_volume":13642},{"name":"Vince Vaughn","url":"http:\/\/twitter.com\/search?q=%22Vince+Vaughn%22","promoted_content":null,"query":"%22Vince+Vaughn%22","tweet_volume":10409},{"name":"Florida State","url":"http:\/\/twitter.com\/search?q=%22Florida+State%22","promoted_content":null,"query":"%22Florida+State%22","tweet_volume":10936},{"name":"Francois","url":"http:\/\/twitter.com\/search?q=Francois","promoted_content":null,"query":"Francois","tweet_volume":24324},{"name":"HOJE TEM TWD","url":"http:\/\/twitter.com\/search?q=%22HOJE+TEM+TWD%22","promoted_content":null,"query":"%22HOJE+TEM+TWD%22","tweet_volume":null},{"name":"Atividade Paranormal 4","url":"http:\/\/twitter.com\/search?q=%22Atividade+Paranormal+4%22","promoted_content":null,"query":"%22Atividade+Paranormal+4%22","tweet_volume":null},{"name":"BELIEBERS VOTANDO","url":"http:\/\/twitter.com\/search?q=%22BELIEBERS+VOTANDO%22","promoted_content":null,"query":"%22BELIEBERS+VOTANDO%22","tweet_volume":56259},{"name":"South Carolina","url":"http:\/\/twitter.com\/search?q=%22South+Carolina%22","promoted_content":null,"query":"%22South+Carolina%22","tweet_volume":16795},{"name":"Deshaun Watson","url":"http:\/\/twitter.com\/search?q=%22Deshaun+Watson%22","promoted_content":null,"query":"%22Deshaun+Watson%22","tweet_volume":12224},{"name":"Soulja Boy","url":"http:\/\/twitter.com\/search?q=%22Soulja+Boy%22","promoted_content":null,"query":"%22Soulja+Boy%22","tweet_volume":196642},{"name":"\uB864\uB4DC\uCEF5","url":"http:\/\/twitter.com\/search?q=%EB%A1%A4%EB%93%9C%EC%BB%B5","promoted_content":null,"query":"%EB%A1%A4%EB%93%9C%EC%BB%B5","tweet_volume":null},{"name":"Racing","url":"http:\/\/twitter.com\/search?q=Racing","promoted_content":null,"query":"Racing","tweet_volume":69655},{"name":"Jimbo","url":"http:\/\/twitter.com\/search?q=Jimbo","promoted_content":null,"query":"Jimbo","tweet_volume":null},{"name":"Silver Scrapes","url":"http:\/\/twitter.com\/search?q=%22Silver+Scrapes%22","promoted_content":null,"query":"%22Silver+Scrapes%22","tweet_volume":null},{"name":"#\u0627\u0646\u0627_\u0645\u0648\u0627\u0637\u0646_\u0645\u062B\u0644\u064A_\u0645\u062B\u0644\u0643\u0645","url":"http:\/\/twitter.com\/search?q=%23%D8%A7%D9%86%D8%A7_%D9%85%D9%88%D8%A7%D8%B7%D9%86_%D9%85%D8%AB%D9%84%D9%8A_%D9%85%D8%AB%D9%84%D9%83%D9%85","promoted_content":null,"query":"%23%D8%A7%D9%86%D8%A7_%D9%85%D9%88%D8%A7%D8%B7%D9%86_%D9%85%D8%AB%D9%84%D9%8A_%D9%85%D8%AB%D9%84%D9%83%D9%85","tweet_volume":23899},{"name":"#\u0627\u0637\u0631\u062F\u0648_\u0627\u0635\u062D\u0627\u0628_\u0627\u0644\u0642\u0647\u0648\u0647_\u0627\u0644\u0633\u0648\u062F\u0627\u0621","url":"http:\/\/twitter.com\/search?q=%23%D8%A7%D8%B7%D8%B1%D8%AF%D9%88_%D8%A7%D8%B5%D8%AD%D8%A7%D8%A8_%D8%A7%D9%84%D9%82%D9%87%D9%88%D9%87_%D8%A7%D9%84%D8%B3%D9%88%D8%AF%D8%A7%D8%A1","promoted_content":null,"query":"%23%D8%A7%D8%B7%D8%B1%D8%AF%D9%88_%D8%A7%D8%B5%D8%AD%D8%A7%D8%A8_%D8%A7%D9%84%D9%82%D9%87%D9%88%D9%87_%D8%A7%D9%84%D8%B3%D9%88%D8%AF%D8%A7%D8%A1","tweet_volume":null},{"name":"#\u0627\u0646\u0627_\u0645\u062F\u0627\u0648\u0
D/LOG-DEBUG: Line 111:
W/System.err: org.json.JSONException: End of input at character 0 of
W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:92)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err: at .MainActivity$1$1.onResponse(MainActivity.java:113)
W/System.err: at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
And this the code block the error pointing :
#Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
CustomTwitterApiClient customTwitterApiClient = new CustomTwitterApiClient(session);
Call<ResponseBody> cevap = customTwitterApiClient.getCustomService().show(1);
cevap.enqueue(new retrofit2.Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
BufferedReader reader = null;
StringBuilder stringBuilder2 = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
} catch (Exception e) {
e.printStackTrace();
}
try {
Log.d("READER", "86 : reader.readLine() : "+reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
String line= "";
try{
while ((line = reader.readLine())!= null)
{
try {
stringBuilder2.append(line);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
catch(IOException e){
e.printStackTrace();
}
try {
Log.d("READER", "111: stringBuilder2.toString(): " +stringBuilder2.toString());
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONArray sonucJsonArray = new JSONArray(stringBuilder2.toString());
JSONObject sonucJsonObject = sonucJsonArray.getJSONObject(0);
JSONArray trendsJsonArray = sonucJsonObject.getJSONArray("trends");
JSONObject trendJson;
for(int i=0; i < trendsJsonArray.length() ; i++){
TrendTopic trend = new TrendTopic();
trendJson = trendsJsonArray.getJSONObject(i);
trend.set_id(i+1);
trend.set_trendName(trendJson.getString("name"));
trend.set_trendQuery(trendJson.getString("query"));
trend.set_trendURL(trendJson.getString("url"));
trendTopics.add(i,trend);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is the CustomTwitterApiClient Class :
public class CustomTwitterApiClient extends TwitterApiClient {
public CustomTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {
#GET("/1.1/trends/place.json")
Call<ResponseBody> show(#Query("id") int id);
}

Showing loading for a UI freezing async task like this one

I have an Async task class which gets the name of a web method and run it and I have to wait for the result of that web method, so I used task.execute.get() method which is freezing my UI. the problem is that I want to show a loading dialog when task is executing but when I'm trying to call this method 10 times for 10 web methods, the UI freezes and after executing 10 web methods, loading dialog appears for 1 second.
What can I do to show loading without moving all of my codes into doInBackground? I want to have a class which gets web method info and returns the result. this is my class code:
public class AsyncCallWs extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public String methodName="";
private WebService ws;
private ArrayList<ServiceParam> paramsList;
private boolean hasParams;
public AsyncCallWs(Activity activity,String methodName) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
hasParams = false;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
this.paramsList = params;
hasParams = true;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage(PersianReshape.reshape("Loading..."));
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
xLog.position();
String result = "No async task result!";
try {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
if (!hasParams){
result = ws.CallMethod(methodName);
}
else{
xLog.info("THIS METHOD IS: "+ methodName);
result = ws.CallMethod(methodName,paramsList);
xLog.info("THIS RESULT IS: "+ result);
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
xLog.position();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
xLog.info("Output of current AsyncTask is:"+ result);
}
}
And this is the way I'm calling web methods using this class:
public void doSync(String method){
xLog.position();
AsyncCallWs t;
ArrayList<ServiceParam> serviceParams = new ArrayList<ServiceParam>();
String result="";
Settings settings = new Settings(activity);
PublicVariable.pGuid = Login(settings.getValue("Username"), settings.getValue("Password"));
xLog.info("pGuid in doSync is:" + PublicVariable.pGuid);
serviceParams.add(new ServiceParam("pGuid", PublicVariable.pGuid, String.class));
if (method=="all" || method=="person"){
try {
t = new AsyncCallWs(activity,"GetPersonInfo",serviceParams);
result = t.execute().get();
xLog.info("Sync Person=>"+ result);
String fields[] = result.split(PublicVariable.FIELD_SPLITTER);
Person person = new Person(activity,fields);
person.empty();
person.insert();
settings.update("PersonId",String.valueOf(person.getId()));
PublicVariable.personId = person.getId();
xLog.info("Person inserted...");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
if (method=="all" || method=="personImage"){
try {
t = new AsyncCallWs(activity,"GetPersonImage",serviceParams);
result = t.execute().get();
if (!result.equals("Nothing")){
settings.update("picture", result);
xLog.info("Picture updatted...");
}
else
xLog.error("NO PERSON IMAGE FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="lawyers"){
try {
t = new AsyncCallWs(activity,"GetLawyers",serviceParams);
result = t.execute().get();
xLog.info("Sync Lawyer=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Lawyer lawyer= new Lawyer(activity);
lawyer.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
lawyer = new Lawyer(activity, fields);
lawyer.insert();
}
xLog.info("Lawyers inserted...");
}
else
xLog.error("NO LAWYER FOUND!");
}catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="news"){
try {
t = new AsyncCallWs(activity,"GetNews",serviceParams);
result = t.execute().get();
String fields[];
Log.d("Ehsan","Sync News=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
News news = new News(activity);
news.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
news= new News(activity,fields);
news.insert();
}
xLog.info("News inserted...");
}
else
xLog.error("NO NEWS FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="messages"){
try {
t = new AsyncCallWs(activity,"GetMessagesInbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Inbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Inbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
try {
t = new AsyncCallWs(activity,"GetMessagesOutbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Outbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Outbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="requests"){
try {
t = new AsyncCallWs(activity,"GetAllRequests",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync share buy sell requests=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Share share = new Share(activity);
share.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
share= new Share(activity,fields);
share.insert();
}
xLog.info("Shares inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="financials"){
try {
t = new AsyncCallWs(activity,"GetFinancials",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync Financials=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Financial financial = new Financial(activity);
financial.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
financial= new Financial(activity,fields);
financial.insert();
}
xLog.info("Financials inserted...");
}
else{
Log.e("Ehsan", "NOT FINANCIALS FOUND!");
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
Here
result = t.execute().get(); //<<< calling get method
as in doc AsyncTask.get() :
Waits if necessary for the computation to complete, and then retrieves
its result.
so to avoid freezing of Main UI Thread during execution of doInBackground start AsyncTask without calling get method as|:
t.execute();
I want to have a class which gets web method info and returns the
result
For this you should implement callback with AsyncTask which report to Activity. see following examples :
android asynctask sending callbacks to ui
How to implement callback with AsyncTask

Display the posts in facebook application

How Display the posts in facebook application. I tried to work with sample android API for Facebook. But nothing worked fine. I need to display a post that i post on my Facebook wall in android emulator. I need a sample code to run and display the JSON response as my post.
Please send me few working links.
Attach the given code with your facebook login class
public void postOnWall() {
try {
String response = Config.facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", Config.myAccessToken);
parameters.putString("message", "I am Now On FB");
parameters.putString("description", "");
response = Config.facebook.request("me/feed", parameters,
"POST");
if (response == null || response.equals("") ||
response.equals("false")) {
}
} catch(Exception e) {
e.printStackTrace();
}
}
Below is the code and sdk official for facebook on android
https://github.com/facebook/facebook-android-sdk/blob/master/examples/stream/src/com/facebook/stream/StreamHandler.java
public class StreamHandler extends Handler {
private static final String CACHE_FILE = "cache.txt";
/**
* Called by the dispatcher to render the stream page.
*/
public void go() {
dispatcher.getWebView().addJavascriptInterface(
new StreamJsHandler(this), "app");
// first try to load the cached data
try {
String cached = FileIO.read(getActivity(), CACHE_FILE);
if (cached != null) {
JSONObject obj = new JSONObject(cached);
dispatcher.loadData(StreamRenderer.render(obj));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Facebook fb = Session.restore(getActivity()).getFb();
new AsyncFacebookRunner(fb).request("me/home",
new StreamRequestListener());
}
public class StreamRequestListener implements RequestListener {
public void onComplete(String response, final Object state) {
try {
JSONObject obj = Util.parseJson(response);
// try to cache the result
try {
FileIO.write(getActivity(), response, CACHE_FILE);
} catch (IOException e) {
e.printStackTrace();
}
// Convert the result into an HTML string and then load it
// into the WebView in the UI thread.
final String html = StreamRenderer.render(obj);
getActivity().runOnUiThread(new Runnable() {
public void run() {
dispatcher.loadData(html);
}
});
} catch (JSONException e) {
Log.e("stream", "JSON Error:" + e.getMessage());
} catch (FacebookError e) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
}
public void onFacebookError(FacebookError e, final Object state) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("stream", "Resource not found:" + e.getMessage());
}
public void onIOException(IOException e, final Object state) {
Log.e("stream", "Network Error:" + e.getMessage());
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("stream", "Invalid URL:" + e.getMessage());
}
}
}

Categories

Resources