I am assigned a project on vehicle tracking system to be developed as an android app.
Project Brief:
A vehicle driver is been given a GPRS powered android OS installed phone so that the location is tracked. The assumption is that all route coordinates (latitude & longitude) are already stored in DB.Such that when the driver crosses a particular place, there should be an alert (change of status) in the DB.In this way, the tracking shall be made efficiently.
My Issue:
I have developed the program but unable to get it executed. I am wondering if my coding is totally wrong or I had left something in between. I have attached/pasted the program for your consideration.
I shall be too glad to receive inputs from you & see the dawn of the project's execution.
You shall reach me at inbasharu#gmail.com
Alternately, if you are magnanimous in helping me outright do buzz me # 9659709092/7305738685
My codes are:
1.proximity Alert Receiver
public class ProximityAlertReceiver extends BroadcastReceiver {
private static final String ACTIVE_TASK_LOC = "com.android.model.TaskLoc";
private static final String ACTIVE_TASK_TEXT = "com.android.model.TaskText";
private static final String ACTIVE_TASK_USER_ID = "com.android.model.TaskUserid";
private static final String ACTIVE_TASK_ROUTE_NUM = "com.android.model.TaskRoutenum";
private static final String ACTIVE_TASK_TOWARDS = "com.android.model.TaskTowards";
Ringtone r;
private static String url_create = "";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
int id;
String taskLoc, taskText, taskRoutenum, taskUserid, taskTowards;
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
ComponentName comp = new ComponentName(context.getPackageName(),
LocationProxyService.class.getName());
ComponentName service = context.startService(new Intent()
.setComponent(comp));
if (null == service) {
} else {
}
} else {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
Bundle bundle = intent.getExtras();
taskLoc = bundle.getString(ACTIVE_TASK_LOC);
String taskText = bundle.getString(ACTIVE_TASK_TEXT);
String taskRoutenum = bundle.getString(ACTIVE_TASK_VEHICLE_NUM);
String taskUserid = bundle.getString(ACTIVE_TASK_USER_ID);
String taskTowards = bundle.getString(ACTIVE_TASK_TOWARDS);
if (entering) {
try {
enterLocation(context, "Task : \"" + taskText + "\"",
"You are Near to " + taskLoc, "UserId : \""
+ taskUserid + "\"", "Vehicle_no : \""
+ taskRoutenum + "\"", "Towrads : \""
+ taskTowards);
enterLocation(context, "Task : \"" + taskText + "\"",
"You are Near to " + taskLoc, "UserId : \""
+ taskUserid + "\"", "Vehicle_no : \""
+ taskRoutenum + "\"", "Towrads : \""
+ taskTowards);
} catch (Exception e) {
}
} else {
exitLocation(context, "Task : \"" + taskText + "\"",
"You are Leaving " + taskLoc + " already!");
}
}
}
public void enterLocation(Context context, String contentText,
String contentTitle, String contentUserid, String contentVehicle_no,
String contentTowards) {
Toast.makeText(context, contentText + "" + contentTitle,
Toast.LENGTH_SHORT).show();
Intent service = new Intent(context, set_routes.class);
context.startService(service);
new Ajax().execute();
}
public void exitLocation(Context context, String contentText,
String contentTitle) {
Toast.makeText(context, contentText + "" + contentTitle,
Toast.LENGTH_SHORT).show();
}
class Ajax extends AsyncTask<String, String, String> {// JSON STARTS HERE
// new CreateNewProduct().execute();
protected ArrayList<NameValuePair> parameters;
protected String v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11;
boolean success;
String msg = "";
public Ajax() {
super();
v1 = taskUserid;
v2 = taskRoutenum;
v3 = taskLoc;
v4 = taskTowards;
parameters = new ArrayList<NameValuePair>();
NameValuePair name = new BasicNameValuePair("user_id", v1);
NameValuePair mobile_no = new BasicNameValuePair("Vehicle_no", v2);
NameValuePair email = new BasicNameValuePair("current_stop", v3);
NameValuePair password = new BasicNameValuePair("towards", v4);
// NameValuePair address = new BasicNameValuePair("address", v9);
parameters.add(name);
parameters.add(mobile_no);
parameters.add(email);
parameters.add(password);
// parameters.add(address);
success = false;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
* pDialog = new ProgressDialog(Newproduct.this);
* pDialog.setMessage("Creating Product..");
* pDialog.setIndeterminate(false); pDialog.setCancelable(true);
* pDialog.show();
*/
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create, "POST",
this.parameters);
// check log cat fro response
Log.d("Create Response", "asdf" + json.toString());
// check for success tag
try {
success = json.getBoolean(TAG_SUCCESS);
msg = json.getString("message");
if (success) {
id = json.getInt("id");
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
if (success) {
Toast.makeText(getBaseContext(), "Sucessfully inserted" + id,
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), set_vehicles.class);
startActivity(i);
} else {
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Main.class);
startActivity(i);
}
}
private Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
private void startActivity(Intent i) {
// TODO Auto-generated method stub
}
}
}
Related
experts
can you help me in seemless integration with PayUmoney payment Gateway in android
also if you have any sample of seemless integration please share
i have tried like this but showing me error of Marchentkey and salt is incorrect but i copied both from my account
below is code detail
MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Payu.setInstance(this);
proceedtopay();
}
public void proceedtopay(){
PaymentParams mPaymentParams = new PaymentParams();
String merchant_key="rjQUPktU"; // test gtkFFx XmOFYRT3
String salt="e5iIg1jwi8"; // test eCwWELxi aTZEImxcYO
mPaymentParams.setKey(merchant_key);
mPaymentParams.setAmount("15.0");
mPaymentParams.setProductInfo("Tshirt");
mPaymentParams.setFirstName("Waseem");
mPaymentParams.setEmail("waseemahmad241#gmail.com");
mPaymentParams.setTxnId("0123479543689");
mPaymentParams.setSurl("https://www.payumoney.com/mobileapp/payumoney/success.php");
mPaymentParams.setFurl("https://www.payumoney.com/mobileapp/payumoney/failure.php");
mPaymentParams.setUdf1("udf1l");
mPaymentParams.setUdf2("udf2");
mPaymentParams.setUdf3("udf3");
mPaymentParams.setUdf4("udf4");
mPaymentParams.setUdf5("udf5");
String hashSequence = merchant_key+"|0123479543689|15.0|productinfo|Waseem|waseemahmad241#gmail.com|udf1|udf2|udf3|udf4|udf5||||||"+salt;
String serverCalculatedHash= hashCal("SHA-512", hashSequence);
mPaymentParams.setHash(serverCalculatedHash);
mPaymentParams.setCardNumber("4012001037141112");
mPaymentParams.setCardName("test");
mPaymentParams.setNameOnCard("test");
mPaymentParams.setExpiryMonth("05");// MM
mPaymentParams.setExpiryYear("2020");// YYYY
mPaymentParams.setCvv("123");
mPaymentParams.setEnableOneClickPayment(1);
PostData postData = null;
try {
postData = new PaymentPostParams(mPaymentParams, PayuConstants.CC).getPaymentPostParams();
} catch (Exception e) {
e.printStackTrace();
}
if (postData.getCode() == PayuErrors.NO_ERROR) {
// launch webview
PayuConfig payuConfig = new PayuConfig();
payuConfig.setEnvironment(PayuConstants.STAGING_ENV);
payuConfig.setData(postData.getResult());
Intent intent = new Intent(this,PaymentsActivity.class);
intent.putExtra(PayuConstants.PAYU_CONFIG,payuConfig);
startActivityForResult(intent, PayuConstants.PAYU_REQUEST_CODE);
} else {
// something went wrong
Toast.makeText(this,postData.getResult(), Toast.LENGTH_LONG).show();
}
}
public static String hashCal(String type, String hashString) {
StringBuilder hash = new StringBuilder();
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance(type);
messageDigest.update(hashString.getBytes());
byte[] mdbytes = messageDigest.digest();
for (byte hashByte : mdbytes) {
hash.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hash.toString();
}
and MyWebview Activity is
PaymentsActivity extends AppCompatActivity {
//String base_url="https://test.payumoney.in/_payment";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
Bundle bundle =getIntent().getExtras();
PayuConfig payuConfig =bundle.getParcelable(PayuConstants.PAYU_CONFIG);
WebView mWebView =(WebView) findViewById(R.id.webview);
// String url =//payuConfig.getEnvironment() == PayuConstants.PRODUCTION_ENV ? PayuConstants.PRODUCTION_PAYMENT_URL :PayuConstants.MOBILE_TEST_PAYMENT_URL;
byte[] encodedData = EncodingUtils.getBytes(payuConfig.getData(), "base64");
mWebView.postUrl(PayuConstants.TEST_PAYMENT_URL,encodedData);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {});
mWebView.setWebViewClient(new WebViewClient() {});
#SuppressLint("SetJavaScriptEnabled")
public class Payment extends AppCompatActivity {
WebView webView;
Context activity;
int mId;
/*private String mMerchantKey ="your marchant key"
private String mSalt = "your salt key"*/
private String mBaseURL = "https://test.payu.in";
private String mAction = ""; // For Final URL
private String mTXNId; // This will create below randomly
private String mHash; // This will create below randomly
private String mProductInfo = "product name"; //Passing String only
private String mFirstName; // From Previous Activity
private String mEmailId; // From Previous Activity
private double mAmount; // From Previous Activity
private String mPhone; // From Previous Activity
private String mServiceProvider = "";// "payu_paisa";
private String mSuccessUrl = "success url";
private String mFailedUrl = "failure url";
String MAM_ID = "mem_id";
String EMAIL = "email";
String ADD1 = "address_line1";
String ADD2 = "address_line2";
String REGION_ID = "region_id";
String CITY_ID = "city_id";
String PROMOCODE = "promocode";
String PIN_CODE = "pin_code";
String ADD_DATE = "add_date";
String PRICE = "price";
String CARD_DISCOUNT = "card_discount";
String PROMOCODE_DISCOUNT = "promocode_discount";
String TXNID = "tnx_id";
String DEVICE_ID = "device_id";
String PRODUCT_ID = "product_id";
boolean isFromOrder;
/*
Handler
*/
Handler mHandler = new Handler();
Bundle bundle;
SharedPreferences spfs;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
/**
* #param savedInstanceState
*/
#SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled", "JavascriptInterface"})
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview_for_payumoney);
spfs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
webView = (WebView) findViewById(R.id.payumoney_webview);
activity = getApplicationContext();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
// enabling action bar app icon and behaving it as toggle button
ab.setHomeButtonEnabled(true);
ab.setTitle("Payment Gateaway");
bundle = getIntent().getExtras();
if (bundle != null) {
Log.e("Bndle Data:- ", bundle.toString());
mFirstName = bundle.getString("Name");//NAME
mEmailId = bundle.getString("Email");// lOGIN IN PAYUMONEY ID
mAmount = 1.0;//bundle.getDouble("Price");// AMOUNT
mPhone = bundle.getString("Mobile"); // MOBILE ! REQUIRED
mId = 1;//bundle.getInt("id");
isFromOrder = true;// bundle.getBoolean("isFromOrder");
Log.e("Tag payment ", "" + mFirstName + " : " + mEmailId + " : " + mAmount + " : " + mPhone);
Random rand = new Random();
String randomString = Integer.toString(rand.nextInt()) + (System.currentTimeMillis() / 1000L);
mTXNId = hashCal("SHA-256", randomString).substring(0, 20);
mAmount = new BigDecimal(mAmount).setScale(0, RoundingMode.UP).intValue();
mHash = hashCal("SHA-512", mMerchantKey + "|" +
mTXNId + "|" +
mAmount + "|" +
mProductInfo + "|" +
mFirstName + "|" +
mEmailId + "|||||||||||" +
mSalt);
mAction = mBaseURL.concat("/_payment");
try {
Class.forName("com.payu.custombrowser.Bank");
} catch (Exception e) {
}
webView.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Handle the error
Log.e("WEB_VIEW_TEST", "error code:" + errorCode);
super.onReceivedError(view, errorCode, description, failingUrl);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
Log.e("onReceivedError", "error code:" + rerr);
Toast.makeText(activity, "Oh no! " + rerr.getDescription().toString(), Toast.LENGTH_SHORT).show();
}
/*#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(activity, "Oh no! " + error, Toast.LENGTH_SHORT).show();
}*/
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Toast.makeText(activity, "SSL Error! " + error, Toast.LENGTH_SHORT).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (url.equals(mSuccessUrl)) {
RecepetUpload();
} else if (url.equals(mFailedUrl)) {
Log.e("Payment STatus", "failure");
Custom_Toast.show(getApplication(), "Payment Transcation Failed");
Intent intent = new Intent(Payment.this, MainActivity.class);
intent.putExtra("status", false);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
super.onPageFinished(view, url);
}
});
webView.setVisibility(View.VISIBLE);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
webView.setInitialScale(1);
webView.addJavascriptInterface(new PayUJavaScriptInterface(Payment.this), "PayUMoney");
/**
* Mapping Compulsory Key Value Pairs
*/
Map<String, String> mapParams = new HashMap<>();
mapParams.put("key", mMerchantKey);
mapParams.put("txnid", mTXNId);
mapParams.put("amount", String.valueOf(mAmount));
mapParams.put("productinfo", mProductInfo);
mapParams.put("firstname", mFirstName);
mapParams.put("email", mEmailId);
mapParams.put("phone", mPhone);
mapParams.put("surl", mSuccessUrl);
mapParams.put("furl", mFailedUrl);
mapParams.put("hash", mHash);
mapParams.put("service_provider", mServiceProvider);
Log.e("Url WEb View", mAction);
webViewClientPost(webView, mAction, mapParams.entrySet());
} else {
Toast.makeText(activity, "Something went wrong, Try again.", Toast.LENGTH_LONG).show();
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* Posting Data on PayUMoney Site with Form
*
* #param webView
* #param url
* #param postData
*/
public void webViewClientPost(WebView webView, String url,
Collection<Map.Entry<String, String>> postData) {
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
Log.d("TAG", "webViewClientPost called: " + sb.toString());
webView.loadData(sb.toString(), "text/html", "utf-8");
}
/**
* Hash Key Calculation
*
* #param type
* #param str
* #return
*/
public String hashCal(String type, String str) {
byte[] hashSequence = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashSequence);
byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1)
hexString.append("0");
hexString.append(hex);
}
} catch (NoSuchAlgorithmException NSAE) {
}
Log.e("Hex String", "" + hexString);
return hexString.toString();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onPressingBack();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
onPressingBack();
}
/**
* On Pressing Back
* Giving Alert...
*/
private void onPressingBack() {
final Intent intent;
if (isFromOrder)
intent = new Intent(Payment.this, MainActivity.class);
else
intent = new Intent(Payment.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Payment.this);
// Setting Dialog Title
alertDialog.setTitle("Warning");
// Setting Dialog Message
alertDialog.setMessage("Do you cancel this transaction?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Payment Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://https://secure.payu.in"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.local/https/https://secure.payu.in")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Payment Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://https://secure.payu.in"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.local/https/https://secure.payu.in")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
public class PayUJavaScriptInterface {
Context mContext;
/**
* Instantiate the interface and set the context
*/
PayUJavaScriptInterface(Context c) {
mContext = c;
}
public void success(long id, final String paymentId) {
mHandler.post(new Runnable() {
public void run() {
mHandler = null;
Toast.makeText(Payment.this, "Payment Successfully.", Toast.LENGTH_SHORT).show();
}
});
}
}
private void RecepetUpload() {
final ProgressDialog progDialog;
progDialog = ProgressDialog.show(Payment.this, "", "waiting");
try {
if (!progDialog.isShowing()) {
progDialog.show();
}
StringRequest postRequest = new StringRequest(Request.Method.POST,
"http://www.local.com/club-app/api-order-details", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Payment Status:--", "Success , " + mTXNId);
Custom_Toast.show(getApplication(), "Payment Transcation Success");
Intent intent = new Intent(Payment.this, MainActivity.class);
intent.putExtra("status", true);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
try {
if (progDialog.isShowing()) {
progDialog.dismiss();
}
Log.e("res Payment", "" + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(MAM_ID, "" + spfs.getString("mem_id", ""));
params.put(EMAIL, "" + mEmailId);
params.put(ADD1, "" + bundle.getString(ADD1));
params.put(ADD2, "" + bundle.getString(ADD2));
params.put(REGION_ID, "" + bundle.getString(REGION_ID));
params.put(CITY_ID, "" + bundle.getString(CITY_ID));
params.put(PIN_CODE, "" + bundle.getString(PIN_CODE));
params.put(ADD_DATE, "" + bundle.getString(ADD_DATE));
params.put(PRICE, "" + mAmount);
params.put(CARD_DISCOUNT, "" + bundle.getString(CARD_DISCOUNT));
params.put(PROMOCODE_DISCOUNT, "" + bundle.getString(PROMOCODE_DISCOUNT));
params.put(PROMOCODE, "" + bundle.getString(PROMOCODE));
params.put(TXNID, "" + mTXNId);
params.put(DEVICE_ID, "" + Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID));
params.put(PRODUCT_ID, "" + bundle.getString(PRODUCT_ID));
Log.e("Bndle Params:- ", params.toString());
return params;
}
};
int socketTimeout = 60000;// 30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
Volley.newRequestQueue(this).add(postRequest);
} catch (Exception e) {
if (progDialog.isShowing()) {
progDialog.dismiss();
}
Log.e("", " Exception Occurs - " + e);
}
}
}
public void signInWithLinkedIn(View view) {
//First check if user is already authenticated or not and session is valid or not
if (!LISessionManager.getInstance(this).getSession().isValid()) {
//if not valid then start authentication
LISessionManager.getInstance(getApplicationContext()).init(LinkedInActivity.this, buildScope()//pass the build scope here
, new AuthListener() {
#Override
public void onAuthSuccess() {
// Authentication was successful. You can now do
// other calls with the SDK.
Toast.makeText(LinkedInActivity.this, "Successfully authenticated with LinkedIn.", Toast.LENGTH_SHORT).show();
//on successful authentication fetch basic profile data of user
//LISessionManager.getInstance(getApplicationContext()).clearSession();
fetchBasicProfileData();
}
#Override
public void onAuthError(LIAuthError error) {
// Handle authentication errors
//LISessionManager.getInstance(getApplicationContext()).clearSession();
Log.e("AUTH ERROR", "Auth Error :" + error.toString());
Toast.makeText(LinkedInActivity.this, "Failed to authenticate with LinkedIn. Please try again.", Toast.LENGTH_SHORT).show();
}
}, true);//if TRUE then it will show dialog if
// any device has no LinkedIn app installed to download app else won't show anything
} else {
//LISessionManager.getInstance(getApplicationContext()).clearSession();
Toast.makeText(this, "You have already been authenticated.", Toast.LENGTH_SHORT).show();
//if user is already authenticated fetch basic profile data for user
fetchBasicProfileData();
}
}
private static Scope buildScope() {
//Check Scopes in Application Settings before passing here else you won't able to read that data
// Scope.R_CONTACTINFO
return Scope.build(Scope.R_BASICPROFILE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
Log.d("Access token->", LISessionManager.getInstance(getApplicationContext()).getSession().getAccessToken().getValue());
}
/**
* method to fetch basic profile data
*/
private void fetchBasicProfileData() {
//In URL pass whatever data from user you want for more values check below link
//LINK : https://developer.linkedin.com/docs/fields/basic-profile
String url = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,public-profile-url,picture-url,email-address,picture-urls::(original))";
APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
apiHelper.getRequest(this, url, new ApiListener() {
#Override
public void onApiSuccess(ApiResponse apiResponse) {
// Success!
JSONObject responseObject = apiResponse.getResponseDataAsJson();
try {
profileURL = responseObject.getString("publicProfileUrl");
imgURL = responseObject.getString("pictureUrl");
fetchConnectionsData();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onApiError(LIApiError liApiError) {
// Error making GET request!
Log.e("FETCH PROFILE ERROR", "Fetch profile Error :" + liApiError.getLocalizedMessage());
Toast.makeText(LinkedInActivity.this, "Failed. Please try again.", Toast.LENGTH_SHORT).show();
}
});
}
Linkedin returns "No value for accessTokenValue" and "access toke is not set". It was working like last month but suddenly it does not work and I could not find anything wrong with the code. After much digging on Google, I am still unable to find a solution. Or am I using the v1 api which I should not? Any help will be greatly appreciated.
This is because the token generated by Linkedin SDK can not be verified by backend. The best solution is to open a webview and use Linkedin web apis- Step 1 - Create a new Class LinkedinActivity
public class LinkedinActivity {
/****FILL THIS WITH YOUR INFORMATION*********/
//This is the public api key of our application
private static final String API_KEY = "apikey";
//This is the private api key of our application
private static final String SECRET_KEY = "secretcode";
//This is any string we want to use. This will be used for avoiding CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/
private static final String STATE = "123456789";
//This is the url that LinkedIn Auth process will redirect to. We can put whatever we want that starts with http:// or https:// .
//We use a made up url that we will intercept when redirecting. Avoid Uppercases.
private static final String REDIRECT_URI = "https://example.com";
/*********************************************/
//These are constants used for build the urls
private static final String AUTHORIZATION_URL = "https://www.linkedin.com/oauth/v2/authorization";
private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/uas/oauth2/accessToken";
private static final String SECRET_KEY_PARAM = "client_secret";
private static final String RESPONSE_TYPE_PARAM = "response_type";
private static final String GRANT_TYPE_PARAM = "grant_type";
private static final String GRANT_TYPE = "authorization_code";
private static final String RESPONSE_TYPE_VALUE = "code";
private static final String CLIENT_ID_PARAM = "client_id";
private static final String STATE_PARAM = "state";
private static final String REDIRECT_URI_PARAM = "redirect_uri";
/*---------------------------------------*/
private static final String QUESTION_MARK = "?";
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";
private WebView webView;
private ImageView close_icon;
private ProgressDialog pd;
//private OauthInterface oauthInterface;
String accessToken;
Context context;
Dialog dialog;
public LinkedinActivity(#NonNull Context context) {
this.context = context;
}
public void showLinkedin() {
dialog = new Dialog(context, R.style.AppTheme);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.setContentView(R.layout.linkedin_activity);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
pd = ProgressDialog.show(context, "", "Loading...", true);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LinkedinData linkedinData = (LinkedinData) context;
linkedinData.linkedCancel();
dialog.dismiss();
}
return true;
}
});
//oauthInterface = new OauthPresenter(this);
//get the webView from the layout
webView = (WebView) dialog.findViewById(R.id.activity_web_view);
close_icon = (ImageView) dialog.findViewById(R.id.close_icon);
close_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinkedinData linkedinData = (LinkedinData) context;
linkedinData.linkedCancel();
dialog.dismiss();
}
});
//Request focus for the webview
webView.requestFocus(View.FOCUS_DOWN);
//Show a progress dialog to the user
//Set a custom web view client
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
//This method will be executed each time a page finished loading.
//The only we do is dismiss the progressDialog, in case we are showing any.
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String authorizationUrl) {
//This method will be called when the Auth proccess redirect to our RedirectUri.
//We will check the url looking for our RedirectUri.
if (authorizationUrl.startsWith(REDIRECT_URI)) {
Log.i("Authorize", "");
Uri uri = Uri.parse(authorizationUrl);
//We take from the url the authorizationToken and the state token. We have to check that the state token returned by the Service is the same we sent.
//If not, that means the request may be a result of CSRF and must be rejected.
String stateToken = uri.getQueryParameter(STATE_PARAM);
if (stateToken == null || !stateToken.equals(STATE)) {
Log.e("Authorize", "State token doesn't match");
return true;
}
//If the user doesn't allow authorization to our application, the authorizationToken Will be null.
String authorizationToken = uri.getQueryParameter(RESPONSE_TYPE_VALUE);
if (authorizationToken == null) {
Log.i("Authorize", "The user doesn't allow authorization.");
return true;
}
Log.i("Authorize", "Auth token received: " + authorizationToken);
//Generate URL for requesting Access Token
String accessTokenUrl = getAccessTokenUrl(authorizationToken);
//We make the request in a AsyncTask
new PostRequestAsyncTask().execute(accessTokenUrl);
} else {
//Default behaviour
Log.i("Authorize", "Redirecting to: " + authorizationUrl);
webView.loadUrl(authorizationUrl);
}
return true;
}
});
//Get the authorization Url
String authUrl = getAuthorizationUrl();
Log.i("Authorize", "Loading Auth Url: " + authUrl);
//Load the authorization URL into the webView
webView.loadUrl(authUrl);
dialog.show();
}
private static String getAccessTokenUrl(String authorizationToken) {
return ACCESS_TOKEN_URL
+ QUESTION_MARK
+ GRANT_TYPE_PARAM + EQUALS + GRANT_TYPE
+ AMPERSAND
+ RESPONSE_TYPE_VALUE + EQUALS + authorizationToken
+ AMPERSAND
+ CLIENT_ID_PARAM + EQUALS + API_KEY
+ AMPERSAND
+ REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI
+ AMPERSAND
+ SECRET_KEY_PARAM + EQUALS + SECRET_KEY;
}
/**
* Method that generates the url for get the authorization token from the Service
*
* #return Url
*/
private static String getAuthorizationUrl() {
return AUTHORIZATION_URL
+ QUESTION_MARK + RESPONSE_TYPE_PARAM + EQUALS + RESPONSE_TYPE_VALUE
+ AMPERSAND + CLIENT_ID_PARAM + EQUALS + API_KEY
+ AMPERSAND + REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI
+ AMPERSAND + STATE_PARAM + EQUALS + STATE
+ AMPERSAND + "scope=r_emailaddress";
}
private class PostRequestAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(context, "", "loading", true);
}
#Override
protected String doInBackground(String... urls) {
if (urls.length > 0) {
String url = urls[0];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
try {
HttpResponse response = httpClient.execute(httpost);
if (response != null) {
//If status is OK 200
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
//Convert the string result to a JSON Object
JSONObject resultJson = new JSONObject(result);
//Extract data from JSON Response
int expiresIn = resultJson.has("expires_in") ? resultJson.getInt("expires_in") : 0;
accessToken = resultJson.has("access_token") ? resultJson.getString("access_token") : null;
Log.e("Tokenm", "" + accessToken);
if (expiresIn > 0 && accessToken != null) {
Log.i("Authorize", "This is the access Token: " + accessToken + ". It will expires in " + expiresIn + " secs");
//Calculate date of expiration
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, expiresIn);
long expireDate = calendar.getTimeInMillis();
////Store both expires in and access token in shared preferences
SharedPreferences preferences = context.getSharedPreferences("user_info", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("expires", expireDate);
editor.putString("accessToken", accessToken);
//oauthInterface.oauthAuthentication(accessToken, "linkedin", new HackedPrefence(getApplicationContext()).getDevice_token());
editor.commit();
return accessToken;
}
}
}
} catch (IOException e) {
Log.e("Authorize", "Error Http response " + e.getLocalizedMessage());
} catch (ParseException e) {
Log.e("Authorize", "Error Parsing Http response " + e.getLocalizedMessage());
} catch (JSONException e) {
Log.e("Authorize", "Error Parsing Http response " + e.getLocalizedMessage());
}
}
return accessToken;
}
#Override
protected void onPostExecute(String status) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
LinkedinData linkedinData = (LinkedinData) context;
linkedinData.LinkedinSuccess(status);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
interface LinkedinData {
void linkedCancel();
void LinkedinSuccess(String Token);
}
}
Step 2 - Call LinkdinActivity.java class using the following code
new LinkedinActivity(this).showLinkedin();
You can call the above code on the click of a button. Example
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new LinkedinActivity(this).showLinkedin();
}
});
Here is linkedin_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/activity_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/close_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginRight="10dp"
android:layout_marginTop="22dp"
android:src="#drawable/ic_close_black"
android:layout_alignParentRight="true"/>
</RelativeLayout>
I've created this code to access user from my database for Login purpose. I can access the object 'st' when I'm inside OnResponse method but when I try to return return the object, it gives me null. Also when I try to access this st object before returning, it gives NullPointerException. What is the exact problem?
public class ServerRequests {
ProgressDialog progressDialog;
public static user_Student st;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://prem-pc:8989/";
Context ct;
public ServerRequests(Context context) {
ct = context;
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please Wait....");
}
public ServerRequests() {
}
public user_Student fetchUserDataInBackground(user_Student user) {
progressDialog.show();
Toast.makeText(ct, "Data in background: ", Toast.LENGTH_SHORT).show();
user_Student ust = doInBackground(user);
progressDialog.dismiss();
return ust;
}
public user_Student doInBackground(user_Student user) {
String URL = SERVER_ADDRESS + "connect.php?prn=" + user.prn + "&password=" + user.password;
RequestQueue req = Volley.newRequestQueue(ct);
Toast.makeText(ct, "Do in Background", Toast.LENGTH_SHORT).show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jObject) {
try {
// Parsing json object response
// response will be a json object
if (jObject.length() == 0) {
st = null;
Toast.makeText(ct, "Null JSON Object", Toast.LENGTH_SHORT).show();
} else {
String prn = jObject.getString("prn");
String fname = jObject.getString("fname");
String mname = jObject.getString("mname");
String lname = jObject.getString("lname");
String clas = jObject.getString("clas");
String dept = jObject.getString("dept");
String batch = jObject.getString("batch");
String scontact = jObject.getString("scontact");
String pcontact = jObject.getString("pcontact");
String email = jObject.getString("email");
String password = jObject.getString("password");
String dob = jObject.getString("dob");
st = new user_Student(prn, fname, mname, lname, clas, dept, batch, scontact, pcontact, email, password, dob);
Toast.makeText(ct, "JSON Object:" + st.fname, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ct, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ct, error.getMessage(), Toast.LENGTH_SHORT).show(); // hide the progress dialog
}
});
req.add(jsonObjReq);
//Toast.makeText(ct,"DO in back End"+st.fname,Toast.LENGTH_SHORT).show();
return st;
}
}
You can't return from anonymous inner classes, but you could create a method inside ServerRequests that takes a user_Student as a parameter and call that method from within onResponse. This method could then do whatever you need.
You must use AsyncTask to do funtion doInBackground(user_Student user)
You can view this post to understand AsyncTask:
How to use AsyncTask correctly in Android
what is the procedure to login throw twitter api1.1.
i have used old api that will show me twitter connection failed because of api 1 is deprecated.
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener()
{
public void onComplete(String value)
{
getTwitterDetail();
}
public void onError(String value) {
Toast.makeText(LoginActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
LOG
{"errors": [{"message": "The Twitter REST API v1 is no longer active.
Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}
As you see from error log API v.1 is no longer active and everybody must migrate to v1.1. In API v1.1. you must log in via OAUTH to get connected. So you also have to register your app on dev.twitter.com.
You can find below example here
public class Main extends Activity{
public static final String TAG = Main.class.getSimpleName();
public static final String TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT = "..."; //cannot share more then 2 lins, sorry
public static final String TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT = "...";
public static final String TWITTER_OAUTH_AUTHORIZE_ENDPOINT = "...";
private CommonsHttpOAuthProvider commonsHttpOAuthProvider;
private CommonsHttpOAuthConsumer commonsHttpOAuthConsumer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonsHttpOAuthProvider = new CommonsHttpOAuthProvider(TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT,
TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT, TWITTER_OAUTH_AUTHORIZE_ENDPOINT);
commonsHttpOAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
commonsHttpOAuthProvider.setOAuth10a(true);
TwDialog dialog = new TwDialog(this, commonsHttpOAuthProvider, commonsHttpOAuthConsumer,
dialogListener, R.drawable.android);
dialog.show();
}
private Twitter.DialogListener dialogListener = new Twitter.DialogListener() {
public void onComplete(Bundle values) {
String secretToken = values.getString("secret_token");
Log.i(TAG,"secret_token=" + secretToken);
String accessToken = values.getString("access_token");
Log.i(TAG,"access_token=" + accessToken);
new Tweeter(accessToken,secretToken).tweet(
"Tweet from sample Android OAuth app. unique code: " + System.currentTimeMillis());
}
public void onTwitterError(TwitterError e) { Log.e(TAG,"onTwitterError called for TwitterDialog",
new Exception(e)); }
public void onError(DialogError e) { Log.e(TAG,"onError called for TwitterDialog", new Exception(e)); }
public void onCancel() { Log.e(TAG,"onCancel"); }
};
public static final Pattern ID_PATTERN = Pattern.compile(".*?\"id_str\":\"(\\d*)\".*");
public static final Pattern SCREEN_NAME_PATTERN = Pattern.compile(".*?\"screen_name\":\"([^\"]*).*");
public class Tweeter {
protected CommonsHttpOAuthConsumer oAuthConsumer;
public Tweeter(String accessToken, String secretToken) {
oAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
oAuthConsumer.setTokenWithSecret(accessToken, secretToken);
}
public boolean tweet(String message) {
if (message == null && message.length() > 140) {
throw new IllegalArgumentException("message cannot be null and must be less than 140 chars");
}
// create a request that requires authentication
try {
HttpClient httpClient = new DefaultHttpClient();
Uri.Builder builder = new Uri.Builder();
builder.appendPath("statuses").appendPath("update.json")
.appendQueryParameter("status", message);
Uri man = builder.build();
HttpPost post = new HttpPost("http://twitter.com" + man.toString());
oAuthConsumer.sign(post);
HttpResponse resp = httpClient.execute(post);
String jsonResponseStr = convertStreamToString(resp.getEntity().getContent());
Log.i(TAG,"response: " + jsonResponseStr);
String id = getFirstMatch(ID_PATTERN,jsonResponseStr);
Log.i(TAG,"id: " + id);
String screenName = getFirstMatch(SCREEN_NAME_PATTERN,jsonResponseStr);
Log.i(TAG,"screen name: " + screenName);
final String url = MessageFormat.format("https://twitter.com/#!/{0}/status/{1}",screenName,id);
Log.i(TAG,"url: " + url);
Runnable runnable = new Runnable() {
public void run() {
((TextView)Main.this.findViewById(R.id.textView)).setText("Tweeted: " + url);
}
};
Main.this.runOnUiThread(runnable);
return resp.getStatusLine().getStatusCode() == 200;
} catch (Exception e) {
Log.e(TAG,"trying to tweet: " + message, e);
return false;
}
}
}
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
public static String getFirstMatch(Pattern pattern, String str){
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
return matcher.group(1);
}
return null;
}
I use this sample to login Twitter, post status and photo. I used it for a long time. Now Twitter requires upgrading from Twitter API 1.0 to Twitter API 1.1. What do I have to do to upgrade it? I tried to replace the old lib with this lib and there is no problem so far but I'm scared of I didn't do the change completely.
You must log in via OAUTH (https://dev.twitter.com/docs/auth/using-oauth) to get connected. So you also have to register your app on dev.twitter.com.
You can find below example here https://github.com/browep/Android-OAuth-Twitter-Example.
public class Main extends Activity{
public static final String TAG = Main.class.getSimpleName();
public static final String TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT = "..."; //cannot share more then 2 lins, sorry
public static final String TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT = "...";
public static final String TWITTER_OAUTH_AUTHORIZE_ENDPOINT = "...";
private CommonsHttpOAuthProvider commonsHttpOAuthProvider;
private CommonsHttpOAuthConsumer commonsHttpOAuthConsumer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonsHttpOAuthProvider = new CommonsHttpOAuthProvider(TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT,
TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT, TWITTER_OAUTH_AUTHORIZE_ENDPOINT);
commonsHttpOAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
commonsHttpOAuthProvider.setOAuth10a(true);
TwDialog dialog = new TwDialog(this, commonsHttpOAuthProvider, commonsHttpOAuthConsumer,
dialogListener, R.drawable.android);
dialog.show();
}
private Twitter.DialogListener dialogListener = new Twitter.DialogListener() {
public void onComplete(Bundle values) {
String secretToken = values.getString("secret_token");
Log.i(TAG,"secret_token=" + secretToken);
String accessToken = values.getString("access_token");
Log.i(TAG,"access_token=" + accessToken);
new Tweeter(accessToken,secretToken).tweet(
"Tweet from sample Android OAuth app. unique code: " + System.currentTimeMillis());
}
public void onTwitterError(TwitterError e) { Log.e(TAG,"onTwitterError called for TwitterDialog",
new Exception(e)); }
public void onError(DialogError e) { Log.e(TAG,"onError called for TwitterDialog", new Exception(e)); }
public void onCancel() { Log.e(TAG,"onCancel"); }
};
public static final Pattern ID_PATTERN = Pattern.compile(".*?\"id_str\":\"(\\d*)\".*");
public static final Pattern SCREEN_NAME_PATTERN = Pattern.compile(".*?\"screen_name\":\"([^\"]*).*");
public class Tweeter {
protected CommonsHttpOAuthConsumer oAuthConsumer;
public Tweeter(String accessToken, String secretToken) {
oAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
oAuthConsumer.setTokenWithSecret(accessToken, secretToken);
}
public boolean tweet(String message) {
if (message == null && message.length() > 140) {
throw new IllegalArgumentException("message cannot be null and must be less than 140 chars");
}
// create a request that requires authentication
try {
HttpClient httpClient = new DefaultHttpClient();
Uri.Builder builder = new Uri.Builder();
builder.appendPath("statuses").appendPath("update.json")
.appendQueryParameter("status", message);
Uri man = builder.build();
HttpPost post = new HttpPost("http://twitter.com" + man.toString());
oAuthConsumer.sign(post);
HttpResponse resp = httpClient.execute(post);
String jsonResponseStr = convertStreamToString(resp.getEntity().getContent());
Log.i(TAG,"response: " + jsonResponseStr);
String id = getFirstMatch(ID_PATTERN,jsonResponseStr);
Log.i(TAG,"id: " + id);
String screenName = getFirstMatch(SCREEN_NAME_PATTERN,jsonResponseStr);
Log.i(TAG,"screen name: " + screenName);
final String url = MessageFormat.format("https://twitter.com/#!/{0}/status/{1}",screenName,id);
Log.i(TAG,"url: " + url);
Runnable runnable = new Runnable() {
public void run() {
((TextView)Main.this.findViewById(R.id.textView)).setText("Tweeted: " + url);
}
};
Main.this.runOnUiThread(runnable);
return resp.getStatusLine().getStatusCode() == 200;
} catch (Exception e) {
Log.e(TAG,"trying to tweet: " + message, e);
return false;
}
}
}
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
public static String getFirstMatch(Pattern pattern, String str){
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
return matcher.group(1);
}
return null;
}