Missing access tokens - java

This is the code i have currently, but I am unable to get the access tokens from my callback, any tips or hints will be appreciated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweetr);
Button tweetr = (Button)findViewById(R.id.tweetr);
//create a new twitter configuration using user details
tweetTwitter = new TwitterFactory().getInstance();
tweetTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//create a twitter instance
// tweetTwitter = new TwitterFactory(twitConf).getInstance();
tweetr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dt.execute();
}
});
}
public class TweetTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object... values) {
/* try {
//requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
*/
try {
requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("URI", "DONE");
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
final Uri uri = getIntent().getData();
if(uri != null ){
Log.d("URI", uri.toString());
Thread th = new Thread(){
public void run(){
AccessToken accessToken;
try {
String verifier = uri.getQueryParameter("oauth_verifier");
String oauthToken = uri.getQueryParameter("oauth_token");
accessToken = tweetTwitter.getOAuthAccessToken(verifier);
//String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}};
th.start();
}else
Log.d("URI", "FAILED");
}
}

I had to use the same requestToken in order to gain access with my app, so I had to edit the manifest file to allow only one instance of the activity to run after returning from webview login panel. That solved it for me.

Related

I have got the google Client Id How to integrate it with my eclipse?

//on creation
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signinButton = (SignInButton) findViewById(R.id.signin);
signinButton.setOnClickListener(this);
image = (ImageView) findViewById(R.id.image);
username = (TextView) findViewById(R.id.username);
emailLabel = (TextView) findViewById(R.id.email);
profileFrame = (LinearLayout) findViewById(R.id.profileFrame);
signinFrame = (LinearLayout) findViewById(R.id.signinFrame);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(Plus.API, Plus.PlusOptions.builder().build()).addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
//connecting google
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
//on failure
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
mConnectionResult = result;
if (signedInUser) {
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
switch (requestCode) {
case RC_SIGN_IN:
if (responseCode == RESULT_OK) {
signedInUser = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
break;
}
}
#Override
public void onConnected(Bundle arg0) {
signedInUser = false;
Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();
getProfileInformation();
}
//updating profile
private void updateProfile(boolean isSignedIn) {
if (isSignedIn) {
signinFrame.setVisibility(View.GONE);
profileFrame.setVisibility(View.VISIBLE);
} else {
signinFrame.setVisibility(View.VISIBLE);
profileFrame.setVisibility(View.GONE);
}
}
//getting profile info
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
username.setText(personName);
emailLabel.setText(email);
new LoadProfileImage(image).execute(personPhotoUrl);
// update profile frame with new info about Google Account
// profile
updateProfile(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
updateProfile(false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.signin:
googlePlusLogin();
break;
}
}
public void signIn(View v) {
googlePlusLogin();
}
public void logout(View v) {
googlePlusLogout();
}
private void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
resolveSignInError();
}
}
private void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateProfile(false);
}
}
// download Google Account profile image, to complete profile
private class LoadProfileImage extends AsyncTask {
ImageView downloadedImage;
public LoadProfileImage(ImageView image) {
this.downloadedImage = image;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return icon;
}
protected void onPostExecute(Bitmap result) {
downloadedImage.setImageBitmap(result);
}
#Override
protected Object doInBackground(Object... arg0) {
// TODO Auto-generated method stub
return null;
}
}
}
First of all add error reporting in your file:
error_reporting(-1);
ini_set('error_reporting', E_ALL);
Than note that this condition:
if($res==$upass)
$res will returns the resource id its can not equal to $upass because $upass is equal to your input field password.
Second, read manual for mysqli_query you missed the link identifier in your query like
mysqli_query($connectionLink,"Your query");
Third, how can you compare the password input with database value?
$res = mysqli_query($connectionLink, "SELECT Password FROM tbl_user WHERE Username='$uname'");
$row_cnt = mysqli_num_rows($res); // check the records
if($row_cnt){
$row = mysqli_fetch_array($res); // fetch the data
if($row['Password'] == $upass){ // check condition (bad practice)
// your stuff
}
}
Fourth, Are you saving simple alphabets in Password field? this is not a good practice, always use encrypted password.
Password Hashing Manuals:
password_hash (PHP 5 >= 5.5.0, PHP 7)
md5

Android Java progressdialog from Baseadapter

On my android app, I have my own BaseAdapter, in this I have a click button listener with the following code:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
final String id = videoIDs[position];
videoActions = new VideoActions();
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
String downloadResult = videoActions.downloadToShare(token, activity, id, videoPathURL[position], finalVideoName);
if (downloadResult.equalsIgnoreCase("POST_FAILURE") || downloadResult.equalsIgnoreCase("FAILURE_102")) {
Toast.makeText(
activity,
activity.getString(R.string.someErrorOccurred),
Toast.LENGTH_SHORT).show();
}
/*if(hfu.Download_File_To_Share(finalVideoName, videoPathURL[position])){
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
} else {
Toast.makeText(activity, "ERRO", Toast.LENGTH_LONG).show();
}*/
}
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
} catch (Exception e) {
pDialog.dismiss();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
Now here you have the function downloadToShare from the class VideoActions:
public String downloadToShare(String token, Activity activity, String videoID, String videoPath, String videoName) {
this.token = token;
this.activity = activity;
this.videoId = videoID;
this.videoPath = videoPath;
this.videoName = videoName;
DownloadToShareClass downloadAction = new DownloadToShareClass();
try {
return downloadAction.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
} // Close download
And now the downloadToShare class:
class DownloadToShareClass extends AsyncTask<String, String, String> {
String response = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
HttpFileUpload hfu = new HttpFileUpload(videoPath, token);
hfu.Download_File_To_Share(videoName, videoPath);
return "SUCESSFULLY";
}
} // Close DownloadClass
Now the download_file_to_share:
boolean Download_File_To_Share(String fileName, String urlToDownload) {
boolean downloadResult;
try {
downloadResult = DownloadFileToShare(fileName, urlToDownload);
return downloadResult;
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
And for the last the DownloadFileToShare:
// Download video
boolean DownloadFileToShare(String filename, String urlToDownload)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL url = new URL(urlToDownload);
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
System.out.println(count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
return true;
}
My Problem is as you can see on my BaseAdapter code, I'm showing a progress dialog, but it only is shown after all the rest finish (the video download). What is the problem here ? I want that the progressDialog shows when the video is being downloaded...
Thanks in advance
I've found a solution to my own problem. From my BaseAdapter I changed my click listener code to the following and it's working perfectly now:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getResources().getString(R.string.preparingVideoToShare));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
final File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
(new Thread(new Runnable() {
#Override
public void run() {
final String a = hfu.Download_File_To_Share(finalVideoName, videoPathURL[position]);
activity.runOnUiThread(new Runnable() {
public void run() {
if (!a.equalsIgnoreCase("ok")){
pDialog.dismiss();
Toast.makeText(activity,
activity.getResources().getString(R.string.someErrorOccurred),
Toast.LENGTH_LONG).show();
} else {
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
}
});
}
})).start();
} else {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
} catch (Exception e) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
e.printStackTrace();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
I hope it can help someone too.
Can you add code to show progressbar in onPreExecute in class DownloadToShareClass which extends AsyncTask ?
Please refer to http://developer.android.com/reference/android/os/AsyncTask.html
From the above link --
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
class DownloadToShareClass extends AsyncTask<String, String, String> {
private ProgressDialog mdialog;
public DownloadToShareClass(yourActivity activity) {
mdialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
mdialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mdialog.isShowing()) {
mdialog.dismiss();
}
}
}

Asynctask w/ ProgressDialog

I know that have a lot of answers about this, but I can't find exactly what I need:
1) When users click on the button, shows a progress Dialog;
2) Executes a class AsyncTask and wait for the answer (it's a response using HTTPUrlConnection);
3) Dismiss Progress Dialog;
I tried a lot of things, but the progress dialog is not "appearing". My code:
public class MainActivity extends Activity implements OnTaskCompleted{
..
private ProgressDialog progressDialog;
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Scanning Please Wait", true);
try {
String param1 = "testParam1";
String param2 = "testParam2";
String response = new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2).get(); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public void onTaskCompleted()
{
progressDialog.dismiss();
}
public class SyncHelper extends AsyncTask<Object, Void, String>
{
..
private OnTaskCompleted listener;
..
protected String doInBackground(Object... url) {
String response = "";
try {
response = getRequest((String) url[0],(String) url[1], (String) url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
}
protected void onPostExecute(String result) {
listener.onTaskCompleted();
}
}
public interface OnTaskCompleted{
void onTaskCompleted();
}
public class MainActivity extends Activity{
..
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String param1 = "testParam1";
String param2 = "testParam2";
new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public class SyncHelper extends AsyncTask<String, Void, String>
{
..
Context context;
private ProgressDialog pd;
..
public SyncHelper (Context c)
{
context = c;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
protected String doInBackground(String... url) {
String response = "";
try {
response = getRequest(url[0], url[1], url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result) {
// here you will be getting the response in String result.
if (pd.isShowing())
pd.dismiss();
}
}
When you are using get, using AsyncTask doesn't make any sense. Because get() will block the UI Thread, maybe thats why are not able to see the progress dialog. If you want to send the response back to the MainActivity then use the callback interface as you were using beofre.

Adding attachments?

Can you help me please, The following code work perfectly on eclipse, but I want to add an attachments to it and I don't know how or where!?:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button addImage = (Button) findViewById(R.id.send_email);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SendEmailAsyncTask().execute();
}
class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
Mail m = new Mail("****#gmail.com", "Password");
public SendEmailAsyncTask() {
if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "SendEmailAsyncTask()");
String[] toArr = {"****#gmail.com", "*****#gmail.com"};
m.setTo(toArr);
m.setFrom("****#gmail.com");
m.setSubject("Email from Android");
m.setBody("Email body.");
}
#Override
protected Boolean doInBackground(Void...params ) {
if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
try {
// m.addAttachment("root/test.txt");
Is it right to add it here? btw i tried and it is not working.
m.send();
return true;
} catch (AuthenticationFailedException e) {
Log.e(SendEmailAsyncTask.class.getName(),"Bad account details");
e.printStackTrace();
return false;
} catch (MessagingException e) {
// Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null) + "failed");
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
Log.e("MailApp", "Could not send email", e);
return false;
}
}
}
});
}
}

Bump API Android crash

I have a huge problem with the bump API on Android. I setup everything like in the example, the first time I start my activity containing the bump code it works great, now if I go back and start it again it just crash due to a Fatal signal error... It happen right after I call the configure of the bump API.
May I need to not call it again ? But there is nothing to check if it already configured or not.
public class BumpActivity extends Activity {
private IBumpAPI api;
private ProgressDialog mDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bump);
mDialog = ProgressDialog.show(BumpActivity.this, "Preparing bump", "Loading");
bindService(new Intent(IBumpAPI.class.getName()), connection,
Context.BIND_AUTO_CREATE);
IntentFilter filter = new IntentFilter();
filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED);
filter.addAction(BumpAPIIntents.DATA_RECEIVED);
filter.addAction(BumpAPIIntents.NOT_MATCHED);
filter.addAction(BumpAPIIntents.MATCHED);
filter.addAction(BumpAPIIntents.CONNECTED);
registerReceiver(receiver, filter);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed(){
Intent resultIntent = new Intent();
setResult(Activity.RESULT_CANCELED, resultIntent);
super.onBackPressed();
}
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.i("BumpTest", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
new Thread() {
public void run() {
try {
api.configure("9b17d663752843a1bfa4cc72d309339e",
"Bump User");
} catch (RemoteException e) {
Log.w("BumpTest", e);
}
}
}.start();
Log.d("Bump Test", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d("Bump Test", "Service disconnected");
}
};
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
try {
if (action.equals(BumpAPIIntents.DATA_RECEIVED)) {
getUserDetailFromBump(new String(
intent.getByteArrayExtra("data")));
} else if (action.equals(BumpAPIIntents.MATCHED)) {
long channelID = intent
.getLongExtra("proposedChannelID", 0);
Log.i("Bump Test",
"Matched with: "
+ api.userIDForChannelID(channelID));
api.confirm(channelID, true);
Toast toast = Toast.makeText(
getApplicationContext(),
"Matched with: "
+ api.userIDForChannelID(channelID),
Toast.LENGTH_SHORT);
toast.show();
} else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) {
long channelID = intent.getLongExtra("channelID", 0);
api.send(channelID, CurrentUserManager.getSharedManager()
.getCurrentUser().getUserId().toString().getBytes());
} else if (action.equals(BumpAPIIntents.NOT_MATCHED)) {
Toast toast = Toast.makeText(getApplicationContext(),
"No match", Toast.LENGTH_SHORT);
toast.show();
} else if (action.equals(BumpAPIIntents.CONNECTED)) {
mDialog.dismiss();
api.enableBumping();
}
} catch (RemoteException e) {
}
}
};
public void getUserDetailFromBump(String data) {
Log.i("User Id", data);
LoginRequest login = new LoginRequest(getApplicationContext());
Log.i("Token", login.getArchivedToken());
AsyncHttpClient restRequest = new AsyncHttpClient();
PersistentCookieStore cookie = new PersistentCookieStore(getApplicationContext());
restRequest.setCookieStore(cookie);
RequestParams params = new RequestParams();
params.put("auth_token", login.getArchivedToken());
params.put("user_id", data);
Log.i("Request", "Preparing");
restRequest.get(Constantes.API_URL + "users/show.json", params, new AsyncHttpResponseHandler(){
public void onSuccess(String response) {
Log.i("Reponse", response);
try {
User user = new User(new JSONObject(response));
Log.i("User", user.toString());
//Driver
if (CurrentUserManager.getSharedManager().getCurrentUser().getType() == 1){
CurrentRouteManager.getSharedManager().getCurrentRoute().addPassanger(user);
Intent resultIntent = new Intent(BumpActivity.this, DriverActivity.class);
resultIntent.putExtra("PASSENGER_ADDED", true);
setResult(1, resultIntent);
finish();
}
else{
Intent p = new Intent(BumpActivity.this, RoutePassenger.class);
p.putExtra("driver", user);
startActivity(p);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable e) {
Log.i("Error", e.toString());
}
});
}
public void onStart() {
Log.i("BumpTest", "onStart");
super.onStart();
}
public void onRestart() {
Log.i("BumpTest", "onRestart");
super.onRestart();
}
public void onResume() {
Log.i("BumpTest", "onResume");
super.onResume();
}
public void onPause() {
Log.i("BumpTest", "onPause");
try {
api.disableBumping();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPause();
}
public void onStop() {
Log.i("BumpTest", "onStop");
try {
api.disableBumping();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onStop();
}
public void onDestroy() {
Log.i("BumpTest", "onDestroy");
try {
api.disableBumping();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
unbindService(connection);
unregisterReceiver(receiver);
super.onDestroy();
}
}
I finally resolved it few days ago. As I'm not a JAVA expert I think the bug is located within the Bump library.
If you do api.configure when it is already configured it simply crash. So I ended up making a singleton, ensuring that it is called only once
Here is the code
public class BumpConnection {
protected Context context;
private IBumpAPI api;
private static BumpConnection sharedManager;
public static synchronized BumpConnection getSharedManager(Context context) {
if (sharedManager == null) {
sharedManager = new BumpConnection(context);
}
return sharedManager;
}
private BumpConnection(Context context){
this.context = context;
context.bindService(new Intent(IBumpAPI.class.getName()), connection,
Context.BIND_AUTO_CREATE);
}
public IBumpAPI getApi() {
return api;
}
public void setApi(IBumpAPI api) {
this.api = api;
}
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.i("BumpTest", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
new Thread() {
public void run() {
try {
api.configure("9b17d663752843a1bfa4cc72d309339e",
"Bump User");
} catch (RemoteException e) {
Log.w("BumpTest", e);
}
}
}.start();
Log.d("Bump Test", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d("Bump Test", "Service disconnected");
}
};
}
Use Latest bump api , available at git hub, read the README.md file carefully.
There is clearly mentioned that by using .aidl file (that is available in src folder) first compile it by using command
android update project -t android-15 -l path_to/bump-api-library -p path_to_your_project/
in your terminal..
If you are a Linux user then set path up to platform-tools then use this command with ./adb .
Then refresh the project , set this Library project as library in your test bump project..
Also replace your bumpapi key that you received via email

Categories

Resources