Method to AsyncTask Android OAuth2Client - android

I am trying to use this code:
public static Token getAccessToken(OAuth2Config oauthDetails) {
HttpPost post = new HttpPost(oauthDetails.getTokenEndPointUrl());
String clientId = oauthDetails.getClientId();
String clientSecret = oauthDetails.getClientSecret();
String scope = oauthDetails.getScope();
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair(OAuthConstants.GRANT_TYPE,
oauthDetails.getGrantType()));
parametersBody.add(new BasicNameValuePair(OAuthConstants.USERNAME,
oauthDetails.getUsername()));
parametersBody.add(new BasicNameValuePair(OAuthConstants.PASSWORD,
oauthDetails.getPassword()));
if (isValid(clientId)) {
parametersBody.add(new BasicNameValuePair(OAuthConstants.CLIENT_ID,
clientId));
}
if (isValid(clientSecret)) {
parametersBody.add(new BasicNameValuePair(
OAuthConstants.CLIENT_SECRET, clientSecret));
}
if (isValid(scope)) {
parametersBody.add(new BasicNameValuePair(OAuthConstants.SCOPE,
scope));
}
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = null;
Token accessToken = null;
try {
post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code >= 400) {
Log.d(TAG, "Authorization server expects Basic authentication");
// Add Basic Authorization header
post.addHeader(
OAuthConstants.AUTHORIZATION,
getBasicAuthorizationHeader(oauthDetails.getUsername(),
oauthDetails.getPassword()));
Log.d(TAG, "Retry with login credentials");
try {
response.getEntity().consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = client.execute(post);
code = response.getStatusLine().getStatusCode();
if (code >= 400) {
Log.d(TAG, "Retry with client credentials");
post.removeHeaders(OAuthConstants.AUTHORIZATION);
post.addHeader(
OAuthConstants.AUTHORIZATION,
getBasicAuthorizationHeader(
oauthDetails.getClientId(),
oauthDetails.getClientSecret()));
try {
response.getEntity().consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = client.execute(post);
code = response.getStatusLine().getStatusCode();
if (code >= 400) {
throw new RuntimeException(
"Could not retrieve access token for user: "
+ oauthDetails.getUsername());
}
}
}
Map map = handleResponse(response);
accessToken = new Token(Long.valueOf((Integer) map.get(OAuthConstants.EXPIRES_IN)), (String) map.get(OAuthConstants.TOKEN_TYPE), (String) map.get(OAuthConstants.REFRESH_TOKEN), (String) map.get(OAuthConstants.ACCESS_TOKEN));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accessToken;
}
Is part of an OAuth2Client that i am using in my Android app.
I am getting this error:
android.os.NetworkOnMainThreadException
and i was reading that i should use AsyncTask, but i have no idea how to convert this method to a AsyncTask.
I will apreciate some help.
Thanks

First of All you need a Fragment to wrap your asynctask so if the device rotates you do not create multiple requests and leak that. And also you need listener (GetAccessTokenCallbacks) to inform your activity that you have done and returning the result.
public class GetAccessTokenFragment extends Fragment {
OAuth2Config mOauthDetails;
static interface GetAccessTokenCallbacks {
void onPostExecute(Token token);
}
private GetAccessTokenCallbacks mCallbacks;
private AccessTokenTask mTask;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (GetAccessTokenCallbacks) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
// you must do it as follow
// first create new instance
// mOauthDetails = new OAuth2Config(....)
// then use the values of MainActivity.this.mOauthDetails to initialize it
mTask = new AccessTokenTask();
mTask.execute();
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
private class AccessTokenTask extends AsyncTask<Void, Void, Token> {
#Override
protected Token doInBackground(Void... param) {
Token token = TheClassOfThisFunction.getAccessToken(mOauthDetails);
return token;
}
#Override
protected void onPostExecute(Token token) {
if (mCallbacks != null) {
mCallbacks.onPostExecute(token[0]);
}
}
}
}
and in your MainActivity you must implement GetAccessTokenFragment.GetAccessTokenCallbacks and creating the GetAccessTokenFragment.
public class MainActivity extends FragmentActivity implements GetAccessTokenFragment.GetAccessTokenCallbacks {
public OAuth2Config mOauthDetails;
private static final String TAG_GetAccessTokenFragment = "GetAccessToken";
private GetAccessTokenFragment mGetAccessTokenFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize mOauthDetails here
FragmentManager fm = getSupportFragmentManager();
mGetAccessTokenFragment = (GetAccessTokenFragment) fm.findFragmentByTag(TAG_GetAccessTokenFragment);
if (mGetAccessTokenFragment == null) {
mGetAccessTokenFragment = new GetAccessTokenFragment();
fm.beginTransaction().add(mGetAccessTokenFragment, TAG_GetAccessTokenFragment).commit();
}
}
#Override
public void onPostExecute(Token token) {
//you got your token here
}
}
Seems that OAuthConfig is called in the following:
public class OAuth2Client {
private final String username;
private final String password;
private final String clientId;
private final String clientSecret;
private final String site;
public OAuth2Client(String username, String password, String clientId, String clientSecret, String site) {
this.username = username;
this.password = password;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.site = site;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getClientId() {
return clientId;
}
public String getClientSecret() {
return clientSecret;
}
public String getSite() {
return site;
}
public Token getAccessToken() {
OAuth2Config oauthConfig = new OAuth2Config.OAuth2ConfigBuilder(username, password, clientId, clientSecret, site)
.grantType("password").build();
return OAuthUtils.getAccessToken(oauthConfig);
}
}

Related

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.....**

Retrieving JSON Data using extras as a parameter of a constructor

Hi guys I am trying to retrieve some movie information in JSON format but I cannot seem to work out what the problem of my code is. The data retrieving and processing itself all works but the problem is that when I pass my title input in the EditText and retrieve that data from another activity, I cannot seem to be able to utilize it. I passed the extra retrieved into the parameter of my data processing class ParseJsonData. However, I get a null pointer exception at where I set title.setText(parseJsonData.getMovie().getTitle()). The strange aspect of this is that if I just run ParseJsonData in the MainActivity by passing in the title myself, I am able to retrieve the title of the data, observed through log. Is there anything that I should be aware of when I am passing an extra as a parameter of a constructor?
public class ResultsPage extends AppCompatActivity {
private final String LOG_TAG = getClass().getSimpleName();
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTextViews();
}
private void setTextViews () {
Bundle bundle = getIntent().getExtras();
String movieTitle = bundle.getString("title");
Log.v(LOG_TAG, "title recieved is : " + movieTitle);
ParseJsonData parseJsonData = new ParseJsonData(movieTitle);
parseJsonData.execute();
title.setText(parseJsonData.getMovie().getTitle());
}
}
Below is ParseJsonData
public class ParseJsonData extends GetRawData{
private String mUrl;
private String title;
private static final String LOG_TAG = "ParseJsonData";
private Movie movie;
public ParseJsonData(String title) {
this.title = title;
processUrl();
}
#Override
public void execute() {
super.setUrl(mUrl);
ParseJsonDataBackground parseJsonDataBackground = new ParseJsonDataBackground();
parseJsonDataBackground.execute(mUrl);
}
public Movie getMovie() {
return movie;
}
private void processUrl () {
final String BASE_URL = "http://www.omdbapi.com/";
final String MOVIE_TITLE = "t";
final String MOVIE_YEAR = "y";
final String MOVIE_PLOT = "plot";
final String MOVIE_DATA_TYPE = "r";
mUrl = Uri.parse(BASE_URL).buildUpon().appendQueryParameter(MOVIE_TITLE, title).appendQueryParameter(MOVIE_YEAR, "").appendQueryParameter(MOVIE_PLOT, "short").appendQueryParameter(MOVIE_DATA_TYPE, "json").build().toString();
Log.v(LOG_TAG, "New Url address is : " + mUrl);
}
public class ParseJsonDataBackground extends GetRawDataBackground {
#Override
protected String doInBackground(String... params) {
return super.doInBackground(params);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
processData(getmData());
}
private void processData (String mData){
try {
final String MOVIE_TITLE = "Title";
JSONObject jsonObject = new JSONObject(mData);
Log.v(LOG_TAG, mData);
String title = jsonObject.getString(MOVIE_TITLE);
movie = new Movie(title);
Log.v(LOG_TAG, "Title of the movie is " + movie.getTitle());
}catch (JSONException e){
Log.e(LOG_TAG, "Error retrieving JsonData");
e.printStackTrace();
}
}
}
}
This is an extension of GetRawData which is below
public class GetRawData {
private String url;
private String mData;
private static final String LOG_TAG = "GetRawData";
public GetRawData() {
}
public String getmData() {
return mData;
}
public void setUrl(String url) {
this.url = url;
}
public void execute () {
GetRawDataBackground getRawDataBackground = new GetRawDataBackground();
getRawDataBackground.execute(url);
}
public class GetRawDataBackground extends AsyncTask<String, Void, String>{
private StringBuffer stringBuffer;
#Override
protected String doInBackground(String... params) {
mData = processDownloads (params[0]);
if (mData == null){
Log.e(LOG_TAG, "Null returned during processing");
return null;
}
return mData;
}
#Override
protected void onPostExecute(String s) {
Log.v(LOG_TAG, "Data retrieved is : " + s);
super.onPostExecute(s);
}
private String processDownloads (String mUrl){
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
if (mUrl == null){
return null;
}
URL url = new URL(mUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
Log.d(LOG_TAG, "Response code is : " + responseCode);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuffer = new StringBuffer();
String line = new String();
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "MalformedURLException");
return null;
} catch (IOException e){
Log.e(LOG_TAG, "IOException in making connection");
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error attempting to close reader");
}
}
}
}
}
}
It's because you're instantiating movie in the background task. It happens in a parallel thread (Thread 2). Your main thread calls getMovite().getTitle(); but movie is not set yet as Thread 2 is still running.
You should pass a callback to ParseJsonData from MainActivity and call the callback in onPostExecute. Make sure you return to the MainThread when you update the text view though.
public class ParseJsonDataBackground extends GetRawDataBackground {
public interface ParseJsonCallback{
void onJsonReady(Movie movie);
}
private ParseJsonCallback callback;
ParseJsonDataBackground(ParseJsonCallback callback){
this.callback = callback;
}
.....
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
processData(getmData());
callback.onJsonReady(movie);
}
.....
}
And in MainActivity
....
ParseJsonData parseJsonData = new ParseJsonData(movieTitle, new ParseJsonCallback(){
void onJsonReady(Movie movie){
runOnUiThread(new Runnable() {
#Override
public void run() {
title.setText(movie.getTitle());
}
});
}
});
parseJsonData.execute();
....

Strange error on android app

I do not know what to call this error. My app uses a self written shared preferences class. After a few times of running my app, nothing can be retrieved from my remote server. I'll post my shared preferences and one my my async tasks. There is no error within the logcat when the app does not retrieve anything.
Shared Preferences class:
public class SharedPreferences{
static final String PREF_USER_NAME = "username";
static final String PREF_USER_ID = "userid";
static android.content.SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static void setUserId(Context ctx, String userId)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_ID, userId);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
public static String getUserId(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_ID, "");
}
public static void clearUserName(Context ctx)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.clear(); //clear all stored data
editor.commit();
}
}
Item retrieval async task:
public class GetEventsAsyncTask extends AsyncTask<String, Integer, Boolean>{
ProgressDialog progressDialog;
MainActivity activityMain;
List<Event> eventList = new ArrayList<Event>();
MyDbAdapter db;
public GetEventsAsyncTask(MainActivity parent)
{
activityMain = parent;
}
#Override
protected void onPreExecute() {
// progressDialog = null;
//
// if (progressDialog == null)
// {
// progressDialog = new ProgressDialog(activityMain);
// progressDialog.setMessage("download events, please wait...");
// progressDialog.show();
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// }
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean error = false;
try {
error = postData(params[0]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
protected void onPostExecute(Boolean error){
/* if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
} */
if(error==true)
{
Log.i("GetEvents", "Error at get events");
activityMain.errorOccured();
}
else
{
Log.i("onPostExecute:eventlist.count",String.valueOf(eventList.size()));
MainActivity.myDB.removeAllEvents();
for(int i=0;i<eventList.size();i++)
{
MainActivity.myDB.insertEventEntry(eventList.get(i));
}
activityMain.downloadEventsSuccess(eventList);
// progressDialog.dismiss();
}
}
protected void onProgressUpdate(Integer... progress){
}
public Boolean postData(String user_id) throws JSONException {
Boolean error = false;
HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
try {
Log.i("GetEvents", user_id);
HttpGet httpget = new HttpGet(Constants.HOST_NAME+"/"+Constants.SERVICE_NAME+"/api/Event?userId=" + user_id);
BufferedReader reader;
StringBuffer sb;
String line = "";
String NL="";
String json;
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode()==200)
{
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
sb = new StringBuffer("");
line = "";
NL = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
sb.append(line + NL);
}
reader.close();
json = sb.toString();
Log.i("event json",json);
try
{
JSONArray jsonArray = new JSONArray(json);
for (int i = 0, length = jsonArray.length(); i < length; i++)
{
JSONObject attribute = jsonArray.getJSONObject(i);
Log.i("EventsAsync", attribute.toString(i));
Event eventObj = new Event();
eventObj.setEvent_id(attribute.getString("event_id"));
eventObj.setEvent_title(attribute.getString("event_title"));
eventObj.setEvent_desc(attribute.getString("event_desc"));
eventObj.setStart_date(attribute.getString("start_date"));
eventObj.setEnd_date(attribute.getString("end_date"));
eventObj.setStart_time(attribute.getString("start_time"));
eventObj.setEnd_time(attribute.getString("end_time"));
eventObj.setLocation(attribute.getString("location"));
eventObj.setPicture_path(attribute.getString("picture_path"));
eventObj.setSmall_picture_path(attribute.getString("small_picture_path"));
eventList.add(eventObj);
// DatabaseUser.openWritable();
// DatabaseUser.insertEvent(eventObj);
eventObj = null;
}
}
catch (JSONException e)
{
e.printStackTrace();
error = true;
}
}
else
{
error = true;
}
}
catch (ClientProtocolException e)
{
// process execption
error = true;
}
catch (IOException e)
{
// process execption
error = true;
}
return error;
}
}
Most of the time, the app stops retrieving after 3 times from onStart to onDestroy.

In Android -How directly post tweet to following users of a authenticate user in android without open Tweet dialog (Message Dialog box)

I want to post tweet to following users of a Authenticate user.For authenticate using Twitter-4j library .I have get list(Name & id) of following users but not able to post tweet without open dialog.I am usingthis link for authenticate
Question-How directly post tweet to following users of a authenticate user in android wihout open Tweet dialog box(Message Dialog)
1. on twitterButton click a new Activity open with webview
twitterButton=(Button) findViewById(R.id.twitter);
twitterButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mTwitter = new TwitterFactory().getInstance();
mRequestToken = null;
mTwitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
TwitterConstants.CONSUMER_SECRET);
String callbackURL = getResources().getString(
R.string.twitter_callback);
try {
mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
System.out.println("URL"
+ mRequestToken.getAuthenticationURL());
} catch (TwitterException e) {
e.printStackTrace();
}
Intent i = new Intent(MMSExampleActivity.this,
TwitterScreen.class);
i.putExtra("URL", mRequestToken.getAuthenticationURL());
System.out.println("Url ==== "
+ mRequestToken.getAuthenticationURL());
startActivityForResult(i, TWITTER_AUTH);
}
});
2. in onActivityResult(int requestCode, int resultCode, Intent data) method
if (resultCode == Activity.RESULT_OK) {
String oauthVerifier = (String) data.getExtras().get(
"oauth_verifier");
AccessToken at = null;
try {
// Pair up our request with the response
at = mTwitter.getOAuthAccessToken(mRequestToken,
oauthVerifier);
accessToken = at.getToken();
System.out.println("access token" + accessToken);
accessTokenSecret = at.getTokenSecret();
getFollowers();
Intent twitterFriendIntent=new Intent(MMSExampleActivity.this,TwitterFriends.class);
twitterFriendIntent.putExtra("twitterfriends", twitterFriends);
startActivity(twitterFriendIntent);
} catch (TwitterException e) {
System.out.println("e........");
e.printStackTrace();
}
}
3. Getting following userList
public void getFollowers()
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
Configuration conf = builder.build();
twitter = new TwitterFactory(conf).getInstance();
try {
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
IDs followersIds=twitter.getFollowersIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
System.out.println("==========================");
do
{
for (long i : friendsIDs.getIDs())
{
FriendList friendListObj=new FriendList();
friendListObj.setTwitterId(i);
friendListObj.setTwitterUsername(twitter.showUser(i).getName());
friendListObj.setTwitterUrl(twitter.showUser(i).getScreenName());
twitterFriends.add(friendListObj);
System.out.println("follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
System.out.println(twitter.showUser(i).getProfileImageURL());
System.out.println(twitter.showUser(i).getURL());
}
}while(friendsIDs.hasNext());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4. Code for post tweets
public void updateStatus( String messageToPost) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
Configuration conf = builder.build();
Twitter twitter = new TwitterFactory(conf).getInstance();
System.out.println("in update status");
try {
// twitter.updateStatus("Hello World!");
StatusUpdate status = new StatusUpdate(messageToPost);
System.out.println("Length of Message is = = = "
+ messageToPost.trim().length());
System.out.println("App" + file);
status.setMedia(file);
System.out.println("App" + file.exists());
twitter.updateStatus(status);
System.out.println("App" + file);
} catch (TwitterException e) {
System.err.println("Error occurred while updating the status!");
e.printStackTrace();
}
}
U have got Twitter Friends ID ... now get Friends Detail(basically Screen Name)
public class FindFriendList extends AsyncTask<Integer, Integer, Void>{
private Context context;
ProgressDialog PD ;
public FindFriendList(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = ProgressDialog.show(context,"","sync Data Server to Local data.");
}
#Override
protected Void doInBackground(Integer... params) {
//getData("https://api.twitter.com/1/followers/ids.json?screen_name="+TwitterApp.UserName);
for (int i = 0; i < Friends_ID.size(); i++) {
getmethodFriendprofile(Friends_ID.get(i));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
PD.dismiss();
}
}
public void getmethodFriendprofile(String FriendsID) {
Log.d("user_ID",":-"+FriendsID);
String weburl ="https://api.twitter.com/1/users/lookup.json?user_id="+FriendsID+",twitter&include_entities=true";
Log.d("url",":-"+weburl);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(weburl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
Firendslist_Detail(stringBuilder.toString());
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second exception generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
}
public void Firendslist_Detail(String response){
try{
JSONArray jsonarray = new JSONArray(response);
JSONObject jsonobject = jsonarray.getJSONObject(0);
String Friendid_ = jsonobject.getString("id");
String Friendpic_ = jsonobject.getString("profile_image_url");
String Friendname_ = jsonobject.getString("name");
String FriendScreename_ = jsonobject.getString("screen_name");
}catch (Exception e) {
Log.d("A3", "7");
}
}
// now u have got Friend ScreenName (FriendScreename_).this ScreenName use for post tweet to paticuler Friend
public int postToTwitteragain(final String msg,String FriendScreenname) {
try {
String message = msg+"\u0040"+FriendScreenname; //there has not white space between unicode of # and Scrrenname
ConfigurationBuilder confbuilder = new ConfigurationBuilder();
confbuilder.setOAuthAccessToken(TwitterSession.token).setOAuthAccessTokenSecret(TwitterSession.tokenSecret)
.setOAuthConsumerKey(twitter_consumer_key).setOAuthConsumerSecret(twitter_secret_key);
Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(twitter_consumer_key,twitter_secret_key,TwitterApp.mAccessToken);
Log.d("review size","review"+message.length());
Status status = (Status) twitter.updateStatus(message);
Log.d("status",":"+status.toString());
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//Twitter class
public class TwitterApp {
private Twitter mTwitter;
private static TwitterSession mSession;
public static AccessToken mAccessToken;
private CommonsHttpOAuthConsumer mHttpOauthConsumer;
private OAuthProvider mHttpOauthprovider;
private String mConsumerKey;
private String mSecretKey;
private ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private Context context;
private static final String TAG = "TwitterApp";
static String oauth_verifier ;
protected static String UserName = null,UeserID = null;
static String OAUTH_CALLBACK_URL = "twitterapp://connect";
public static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
public TwitterApp(Context context, String consumerKey, String secretKey) {
this.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
mHttpOauthprovider = new DefaultOAuthProvider(REQUEST_URL,ACCESS_URL,AUTHORIZE_URL);
mAccessToken = mSession.getAccessToken();
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
private void configureToken() {
if (mAccessToken != null) {
mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
mTwitter.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public static void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public static void logoutTwitter(Context context) {
resetAccessToken();
#SuppressWarnings("unused")
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
mTwitter.updateStatus(status);
} catch (TwitterException e) {
throw e;
}
}
public void authorize() {
mProgressDlg.setMessage("Initializing ...");
mProgressDlg.show();
new Thread() {
#Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, OAUTH_CALLBACK_URL);
what = 0;
Log.d(TAG, "Request token url " + authUrl);
} catch (Exception e) {
Log.d(TAG, "Failed to get request token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing ...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
#Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
UserName = user.getName();
Log.d("user name",""+UserName);
Log.d("user ID",""+user.getId());
HttpParameters params1 = mHttpOauthprovider.getResponseParameters();
String screen_name = params1.getFirst("screen_name");
Log.d("screen_name >>>>>>>>", screen_name);
oauth_verifier = verifier;
what = 0;
} catch (Exception e){
Log.d(TAG, "Error getting access token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
#Override
public void onComplete(String value) {
processToken(value);
}
#Override
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1) {
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
} else {
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
void onComplete(String value);
void onError(String value);
}
}
TwitterDialog class
public class TwitterDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private TwDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Twitter-WebView";
public TwitterDialog(Context context, String url, TwDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
mTitle = new TextView(getContext());
mTitle.setText("Twitter");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFFbbd7e9);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(TwitterApp.OAUTH_CALLBACK_URL)) {
mListener.onComplete(url);
TwitterDialog.this.dismiss();
return true;
} else if (url.startsWith("authorize")) {
return false;
}
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
TwitterDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}**
TwitterSession
public class TwitterSession {
private SharedPreferences sharedPref;
private Editor editor;
static String token,tokenSecret;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
token = sharedPref.getString(TWEET_AUTH_KEY, null);
tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}
following jar file use
signpost-commonshttp4-1.2.1.1.jar
signpost-core-1.2.1.1.jar
twitter4j-core-2.1.11.jar
where . Friend_ID is String Arraylist..
I hope this code can help u .Enjoy This code !

AsyncTask - onPostExecute is not called

I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço HttpGet", url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?

Categories

Resources