how to fetch result from asynctask into mainactivity - android

I am trying to make a translater app and all code is working fine but at the last part my app is crashed while fetching the result from asynctask into mainactivity,what I'm doing wrong here
enter code here
MainActivity.java
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1)
{
// TODO: Implement this method
texttotranslate = et.getText().toString();
Log.d("text:", "" + texttotranslate);
OkhttpHandler myTask = new OkhttpHandler(new AsyncResponse(){
#Override
public void processFinish(String output)
{
// TODO: Implement this method
Log.d("Response from asynctask", (String) output);
t.setText((String)output);
}
});
myTask.execute(texttotranslate, lang_pair);
}
});
I already created an interface AsyncResponse and added a method processFinish(String output) into it
enter code here
OkHttpHandler.java
public class OkhttpHandler extends AsyncTask<String,Void,String>
{
String res;
String transres;
String finalres;
public AsyncResponse delegate;
public OkhttpHandler(AsyncResponse delegate)
{
this.delegate = delegate;
}
#Override
protected String doInBackground(String[] values)
{
// TODO: Implement this method
OkHttpClient client = new OkHttpClient();
String texttotranslate = values[0];
String lang_pair = values[1];
String key = "my-key";
String url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + key
+ "&text=" + texttotranslate + "&lang=" + lang_pair;
Request request = new Request.Builder().url(url).build();
try
{
Response response = client.newCall(request).execute();
res = response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
if (res != null)
{
try
{
JSONObject jsonobj = new JSONObject(res);
transres = jsonobj.getString("text");
String f = transres.replace("[", "");
String s = f.replace("]", "");
finalres = s.replace("\"", "");
Log.d("final result", "" + finalres);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return finalres;
}
#Override
protected void onPostExecute(String result)
{
// TODO: Implement this method
super.onPostExecute(result);
delegate.processFinish(result);
Log.d("result:", "" + result);
}
}
My app is crashed while launching and there is no any error showing in my logcat.

You should replace my-key with your yandex API_KEY
String key = "my-key";
Everything else is fine I tried your code
https://github.com/naveendew/yandex_translate_example

I had accidentally deleted okio library from libs folder that's why my app was crashing, so now it's solved.
So if anyone using okhttp library then add okio library too.

Related

Running Async in a fragment is not even being ran

I am running the commands like so:
new GetGameScoresFromFuhantikAPI()
And my method for this is ->
private class GetGameScoresFromFuhantikAPI extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
MethodContants.showLog(TAG, "Loading FUHNATIK API", true);
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = API_URL + jsonFile;
// String url = "http://www.nfl.com/liveupdate/game-center/" + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from FUHNATIK API: " + url);
if (jsonStr != null) {
try {
//JSONObject object = new JSONObject(json);
JSONObject object = new JSONObject(jsonStr);
currentWeek = object.getString("pypwk");
currentWeekDB = object.getString("mdb");
JSONArray array = (JSONArray) object.get("g");
scheduleModelList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
//TODO IF WE DONT PLAY THURSDAY GAMES PUT LIST.ADD IN HERE
// if (!array.getJSONObject(i).getString("-d").equals("Thu")){
//
// }
scheduleModelList.add(new ScheduleModel(array.getJSONObject(i).getString("-v"),
array.getJSONObject(i).getString("-h"),
array.getJSONObject(i).getString("-t"),
array.getJSONObject(i).getString("-d"),
array.getJSONObject(i).getString("-eid").substring(0, 8),
array.getJSONObject(i).getString("-t") + array.getJSONObject(i).getString("-q"),
array.getJSONObject(i).getString("-vnn"),
array.getJSONObject(i).getString("-hnn"),
"...select a team...",
array.getJSONObject(i).getString("-eid"),
array.getJSONObject(i).getString("-vs"),
array.getJSONObject(i).getString("-hs"),
array.getJSONObject(i).getString("-w")));
}
} catch (final JSONException e) {
Log.e(TAG, "FUHNATIK API: Json parsing error: " + e.getMessage());
}
} else {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "FUHNATIK API: Couldn't get json from server.");
Toast.makeText(getContext(), "Getting from ESPN", Toast.LENGTH_SHORT).show();
//new GetGameScoresFromESPN().execute();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final ListViewAdapterResults adapter = new ListViewAdapterResults(listView.getContext(), scheduleModelList);
listView.setAdapter(adapter);
MethodContants.showLog(TAG, "DONE WITH LOADING FUHNATIK API", false);
}
}
I can't seem to figure out why the code never get ran. I ran through the debugger but I really can't pinpoint where this is failing out. Any help on this would be appreciated.
Eventually if the json file is not at this URL, I will be getting the json from NFL. However, Without this working, the ESPN won't work either, and I really can not figure out where the error is on my end. I have to assume this will be a pretty easy fix.
Again, as said before, any help would be very appreciated!!
In the above line of code you call the Class but you forgot to execute your asynctask. So no Overriden methods are called. Try this:
new GetGameScoresFromFuhantikAPI().execute();
If you want to pass something as argument, give parameters separated by coma like this:
new GetGameScoresFromFuhantikAPI().execute(arg0, arg1);

Paytm Sdk Version 2 - Paytm integration in Android App throwing OOPS error in doInBackground

I am integrating Paytm SDK in my Android Application. I have to POST ORDER ID and callbackurl along with other paytm credentials. All values are passing correctly. But OOPS error is displaying.
Code
public class Paytmgateway extends Activity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
String myorder = "ORDER7999883";
String mycallback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+myorder;
PostAsync postAsync= new PostAsync();
postAsync.execute(myorder,mycallback);
}
class PostAsync extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String LOGIN_URL = "http://192.168.1.4/paytmtest/generateChecksum.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> para = new HashMap<>();
para.put("myorder", args[0]);
para.put("mycallback", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", para);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
PaytmPGService Service = PaytmPGService.getProductionService();
if (json != null) {
Toast.makeText(Paytmgateway.this,"Server Response"+json.toString(), Toast.LENGTH_LONG).show();
String finalresult=json.toString();
try {
JSONObject mJsonObject=new JSONObject(finalresult);
Map paramMap = new HashMap();
System.out.println("Hi");
paramMap.put("MID", mJsonObject.getString("MID"));
System.out.println(mJsonObject.getString("MID"));
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", mJsonObject.getString("ORDER_ID"));
System.out.println(mJsonObject.getString("ORDER_ID"));
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",mJsonObject.getString("CUST_ID"));
System.out.println(mJsonObject.getString("CUST_ID"));
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",mJsonObject.getString("INDUSTRY_TYPE_ID"));
System.out.println(mJsonObject.getString("INDUSTRY_TYPE_ID"));
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", mJsonObject.getString("CHANNEL_ID"));
System.out.println(mJsonObject.getString("CHANNEL_ID"));
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", "1");
System.out.println(mJsonObject.getString("TXN_AMOUNT"));
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , mJsonObject.getString("WEBSITE"));
System.out.println(mJsonObject.getString("WEBSITE"));
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , mJsonObject.getString("CALLBACK_URL"));
System.out.println(mJsonObject.getString("CALLBACK_URL"));
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",mJsonObject.getString("CHECKSUMHASH"));
System.out.println("MYCHECK"+mJsonObject.getString("CHECKSUMHASH"));
PaytmOrder Order = new PaytmOrder(paramMap);
System.out.println("sumithra"+paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(Paytmgateway.this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"UI Error" , Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
Toast.makeText(getApplicationContext(),"No Network Available" , Toast.LENGTH_LONG).show();
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"Client Authentication Failed" , Toast.LENGTH_LONG).show();
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
Toast.makeText(getApplicationContext(),"Error Loading Webpage" , Toast.LENGTH_LONG).show();
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed" + inErrorMessage);
Toast.makeText(getBaseContext(),"Payment Transaction Failed", Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
My Android Studio Monitor output of
System.out.println(paramMap);
is
05-22 15:43:33.801 15328-15328/com.example.merchantapp I/System.out: {MID=Bigfix12826731009600, CALLBACK_URL=https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=ORDER7999883, TXN_AMOUNT=1.00, ORDER_ID=ORDER7999883, WEBSITE=BigfixGadgetWAP, INDUSTRY_TYPE_ID=Retail109, CHECKSUMHASH=HxSimAQAYRsDhJ7XX6JXT+cilxFNdSc4Pb3jr5AE5dddSavv6UD3DJffBHtcHVwQbBMYYHc850/OdZretSWIeo3m/uC0/FUA9wpO1Hgs/jY=, CHANNEL_ID=WAP, CUST_ID=25654}
Which means the two parameter values are posting successfully and i can be able to GET them also. But the following error is displaying
enter image description here
But if if i use the below code , It is working successfully
public class Paytm extends Activity {
String callback,website;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
PaytmPGService Service = PaytmPGService.getProductionService();
Map paramMap = new HashMap();
String mid="",order_id="",cust_id="",industry_type="",txn_amount="",checksum="";
Log.d("before request", "some");
JSONObject mJsonObject = null;
// String url="http://paytmtest.azurewebsites.net/APP/generateChecksum.php";
String url="http://192.168.1.4/paytmtest/generateChecksum.php";
MyAsyncTask myAsyncTask=new MyAsyncTask();
// String json = myAsyncTask.execute(url).get();
String json = (String) myAsyncTask.execute(url).get();
try {
mJsonObject=new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
try {
//mid = mJsonObject.getString("MID");
mid="Bigfix12826731009600";
// order_id=mJsonObject.getString(“ORDER_ID”);
order_id=mJsonObject.getString("ORDER_ID");
// cust_id = mJsonObject.getString(“CUST_ID”);
cust_id=mJsonObject.getString("CUST_ID");
//callback = mJsonObject.getString("CALLBACK_URL");
callback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+order_id;
//website = mJsonObject.getString("WEBSITE");
website="BigfixGadgetWAP";
//industry_type = mJsonObject.getString("INDUSTRY_TYPE_ID");
industry_type="Retail109";
txn_amount = mJsonObject .getString("TXN_AMOUNT");
// checksum = mJsonObject.getString(“CHECKSUMHASH”);
checksum = mJsonObject.getString("CHECKSUMHASH");
} catch (JSONException e) {
e.printStackTrace();
}
// Log.d(“after request”, “some”);
Log.d("after request", "some");
// paramMap.put(“MID”, mid);
paramMap.put("MID", mid);
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", order_id);
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",cust_id);
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",industry_type);
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", "WAP");
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", txn_amount);
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , website);
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , callback);
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",checksum);
System.out.println("sumithra"+paramMap);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed" + inErrorMessage);
Toast.makeText(getBaseContext(),"Payment Transaction Failed", Toast.LENGTH_LONG).show();
}
});
}
class MyAsyncTask extends AsyncTask {
#Override
protected String doInBackground(Object[] params) {
URL url = null;
try {
url = new URL((String) params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection httpConn = null;
try {
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = httpConn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
} catch (Exception e) {
}
Log.d("Response", result);
}
}
}
[enter image description here][2]
I just used the second code to test the trasaction. But i have to use the first posted code because i have to post the ORDERID and CALLBACKURL from android application to server . Any help would be appreciable.
**Here is the solution for all :**
Be sure to send equal number of parameters to your server (For checksum generator) And then to paytm server for payment.
**For example:**
If you are sending 6 params for checksum generator, then send these 6 same parameters including Checksum to Paytm...
It will resolve your problem.
**CODE EXAMPLE :**
**Generate checksum.php**
$paramList = array();
$paramList["MID"] = 'Provided by Paytm'; //Provided by Paytm
$paramList["ORDER_ID"] = 'hIquwhzvzTG7gvT'; //unique OrderId for every request
$paramList["CUST_ID"] = 'CUST0001453'; // unique customer identifier
$paramList["INDUSTRY_TYPE_ID"] = 'Retail'; //Provided by Paytm
$paramList["CHANNEL_ID"] = 'WAP'; //Provided by Paytm
$paramList["TXN_AMOUNT"] = '10.00'; // transaction amount
$paramList["WEBSITE"] = 'APP_STAGING';//Provided by Paytm
$paramList["CALLBACK_URL"] = 'https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp';
**Android Activity.java**
paramMap.put("MID" , "#########");
paramMap.put( "ORDER_ID" , "hIquwhzvzTG7gvT");
paramMap.put( "CUST_ID" , "CUST0001453");
paramMap.put( "CHANNEL_ID" , "WAP");
paramMap.put( "TXN_AMOUNT" , "10.00");
paramMap.put( "WEBSITE" , "APP_STAGING");
paramMap.put( "CALLBACK_URL" , "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp");
paramMap.put( "CHECKSUMHASH" , "dR5OtEkuNkgamHTZDCHmF+CF3j9RdG1520mlHEb85oSZP1CaxVUsRY2sYric90HLm/vElaPZKoQ7b5/SyFpi3oBWXf2BQNy+r6iiBwg4AH4=");
paramMap.put("INDUSTRY_TYPE_ID" , "Retail");
**NOTE : Please keep in mind to send paytm server exact parameters plus one checksum.....**

Async not working while sending image to server?

I need to send image to service, pre-execute method working where as do in background not working. Code is below for same:
private class SendImageAsync extends AsyncTask<String, String, String> {
private Context context;
private String serverUrl;
private String path;
public SendImageAsync(Context context, String serverUrl,
String path) {
this.context = context;
this.serverUrl = serverUrl;
this.path = path;
}
#Override
protected void onPreExecute() {
LogWrite.i(TAG, "onPreExecute method enters!!");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
LogWrite.i(TAG, "doInBackground method enters!!");
byte[] imageBytes = getFileBytes(path);
ImageToSend sendImage = new ImageToSend();
boolean responseStatus = sendImage.send(context, serverUrl,
imageBytes );
String responseString = responseStatus ? "Success!" : "Fail!";
LogWrite.e(TAG, "Response " + responseString);
return "";
}
#Override
protected void onPostExecute(String result) {
LogWrite.i(TAG, "onPostExecute method enters!!");
super.onPostExecute(result);
}
}
Help me on same, why it is not working?
Update code:
I had created an interface, that will notify on image click and provide me path of file:
#Override
public void onImageCapture(File file) {
if (file != null) {
LogWrite.d(TAG, "File Path ::: " + file.getAbsolutePath());
if (isFromCommand) {
LogWrite.d(TAG, "Is from command : "+ isFromCommand);
try {
SendImageAsync async = new SendImageAsync (activity,
serverUrl, file.getAbsolutePath());
async.execute("");
} catch (Exception e) {
LogWrite.e(TAG, "SendImageAsync Exception : " + e.toString());
}
}
Bitmap myBitmap = showBitmapFromFile(file.getAbsolutePath());
myBitmap = RotateBitmap(myBitmap, 90);
Drawable ob = new BitmapDrawable(getResources(), myBitmap);
saveImageView.setBackgroundDrawable(ob);
}
// saveImageView.setImageBitmap(myBitmap);
}
I'm not sure but you probably want to send a request and not a response...
I found the solution, I was using this AsyncTask on another AsyncTask, So its not working, even it was not giving any exception.
Here are the basic sample code you can refer, hope this help
/**
* Async task to post file to remote web api
*/
public class PostFileToWebAPI extends AsyncTask<String, Integer, Object> {
...
#Override
protected Object doInBackground(String... params) {
String filePath = params[1];
try {
return postFile(mAPI_URL, filePath);
} catch (Exception e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
private String postFile(String apiUrl, String filePath) throws Exception {
// init httpClient, httpPost...
...
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filePath);
FileBody fileBody = new FileBody(file);
final long totalSize = fileBody.getContentLength();
builder.addPart("file", fileBody);
httpEntity = builder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
return httpResponse.getStatusLine().toString();
} else {
return getStringContent(httpResponse);
}
}

Asyntask not executing onPostExecute()

This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.
Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.
Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.

Rest with Android 4.0

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like thishttp://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
WSTaxiShare ws = new WSTaxiShare();
response = ws.login(login, password);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
}
and here is the call button
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});
}

Categories

Resources