I am using the Dropbox core API I have successfully written the code, but when I am trying to run app an alertbox appear and show this error"the app you were using submitted a bad request" I really don't know what to do I tried to search this error but could not find any this is my code please tell me what is wrong with my code???
public class MainActivity extends AppCompatActivity {
final static private String APP_KEY = "xxxxxxxx";
final static private String APP_SECURIT = "xxxxxxxx\n";
private static final String ACCESS_TOKEN = "-xxxxxxxxxx-";
private static final Session.AccessType ACCESS_TYPE = Session.AccessType.DROPBOX;
public DropboxAPI dropboxAPI;
Button login_btn, uploadfile_btn;
Boolean isuserislogin;
private final static String DROPBOX_FILE_DIRECTORY = "/DropboxDemo/";
private final static String DROPBOX_NAME = "dropbox_prefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login_btn = (Button) findViewById(R.id.login);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isuserislogin) {
dropboxAPI.getSession().unlink();
loggedIn(false);
} else {
((AndroidAuthSession) dropboxAPI.getSession()).startAuthentication(MainActivity.this);
}
}
});
uploadfile_btn = (Button) findViewById(R.id.upload);
uploadfile_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UploadFile uploadFile = new UploadFile(dropboxAPI, DROPBOX_FILE_DIRECTORY, MainActivity.this);
uploadFile.execute();
}
});
loggedIn(false);
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECURIT);
AndroidAuthSession session;
SharedPreferences sharedPreferences = getSharedPreferences(DROPBOX_NAME, 0);
String key = sharedPreferences.getString(APP_KEY, null);
String securit = sharedPreferences.getString(APP_SECURIT, null);
if (key != null && securit != null) {
AccessTokenPair tokenPair = new AccessTokenPair(key, securit);
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, tokenPair);
} else {
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
}
dropboxAPI = new DropboxAPI(session);
}
private void loggedIn(boolean userislogin) {
isuserislogin = userislogin;
uploadfile_btn.setEnabled(userislogin);
login_btn.setText(userislogin ? "logout" : "log in");
}
#Override
public void onResume() {
super.onResume();
AndroidAuthSession session = (AndroidAuthSession) dropboxAPI.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokenPair = session.getAccessTokenPair();
SharedPreferences preferences = getSharedPreferences(DROPBOX_NAME, 0);
SharedPreferences.Editor editor=preferences.edit();
editor.putString(APP_KEY,tokenPair.key);
editor.putString(APP_SECURIT,tokenPair.secret);
editor.commit();
loggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(this, "error in outh", Toast.LENGTH_LONG).show();
}
}
}
}
this is my uploadfile class
public class UploadFile extends AsyncTask<Void, Void, Boolean> {
private DropboxAPI dropboxAPI;
private String path;
private Context context;
public UploadFile(DropboxAPI dropboxAPI, String path, Context context) {
this.dropboxAPI = dropboxAPI;
this.path = path;
this.context = context;
}
#Override
protected Boolean doInBackground(Void... voids) {
final File tempDropboxDirectory = context.getCacheDir();
File tempFileUploader;
FileWriter fileWriter = null;
try {
tempFileUploader = File.createTempFile("file", ".txt", tempDropboxDirectory);
fileWriter = new FileWriter(tempFileUploader);
fileWriter.write("hellow world");
fileWriter.close();
FileInputStream fileInputStream = new FileInputStream(tempFileUploader);
dropboxAPI.putFile(path + "hellow_world.txt", fileInputStream,
tempFileUploader.length(), null, null);
tempFileUploader.delete();
return true;
} catch (IOException ieo) {
} catch (DropboxException de) {
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(context, "file has uploaded", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "error", Toast.LENGTH_LONG).show();
}
}
}
Related
I am trying to create app that can connect to a MS SQL database when the user enters his username and password, I have tried multiple times and just cannot succeed. What would be the best way to connect my app?
This is the code that I have tried below.
public class LoginActivity extends AppCompatActivity {
private static String ip = "myip";
private static String port = "myportnum";
private static String Class = "net.sourceforge.jtds.jtbc.Driver";
private static String database = "name";
private static String username = "name";
private static String password = "password";
private static String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;
private Connection connection = null;
private EditText userNameET, passwordEt;
private Button loginBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userNameET = findViewById(R.id.userNameEditText);
passwordEt = findViewById(R.id.passEditText);
loginBTN = findViewById(R.id.loginBtn);
StrictMode.ThreadPolicy policy = null;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// #android.support.annotation.RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
private class DoLoginForUser extends AsyncTask<String, Void, String> {
String emailId, password;
#Override
protected void onPreExecute() {
super.onPreExecute();
emailId = userNameET.getText().toString();
password = passwordEt.getText().toString();
// progressBar.setVisibility(View.VISIBLE);
loginBTN.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
try {
ConnectionHelper con = new ConnectionHelper();
Connection connect = ConnectionHelper.CONN();
String query = "Select * from testDatabase where UserId='" + emailId + "'";
PreparedStatement ps = connect.prepareStatement(query);
Log.e("query",query);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String passcode = rs.getString("password");
connect.close();
rs.close();
ps.close();
if (passcode != null && !passcode.trim().equals("") && passcode.equals(password))
return "success";
else
return "Invalid Credentials";
} else
return "User does not exists.";
} catch (Exception e) {
return "Error:" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(signup.this, result, Toast.LENGTH_SHORT).show();
// ShowSnackBar(result);
// progressBar.setVisibility(View.GONE);
loginBTN.setVisibility(View.VISIBLE);
if (result.equals("success")) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("userdetails",0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("email",userNameET.getText().toString());
editor.commit();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
} else {
//ShowSnackBar(result);
}
}
}
//public void ShowSnackBar(String message) {
// Snackbar.make(lvparent, message, Snackbar.LENGTH_LONG)
// .setAction("CLOSE", new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//// }
// })
// .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
// .show();
// }
public void DoLogin(View v)
{
DoLoginForUser login = null;
login = new DoLoginForUser();
login.execute("");
}
I am expecting it to connect and then take me to the next screen.
Please help ... the download function is running till the Toast "Downloading.." but not after that and an empty file is created in the destination folder.
I think dropbox must not have been authenticated please see.
The source i have chosen is inside my app folder which is generated when creating the project in Dropbox developers......Please check whether it is correct
final static private String APP_KEY = "xxxxxx";
final static private String APP_SECRET = "xxxxxx";
final static private String ACCESS_TOKEN = "xxxxxx";
public static String DropboxDownloadPathFrom = "MyFolder/Get Started with Dropbox.pdf"; //This is my source inside the app folder
public static String DropboxDownloadPathTo = "/storage/emulated/0/DropboxItems/hello"; //This is my destination
public static String dropboxdirpath="/storage/emulated/0/DropboxItems/";
public static File dir=new File(dropboxdirpath);
// In the class declaration section:
static private DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
session.setOAuth2AccessToken(ACCESS_TOKEN); //I am using access token so no need for other authentication
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(click);
}
private View.OnClickListener click=new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadFromDropboxFromPath(DropboxDownloadPathTo,DropboxDownloadPathFrom);
}};
//This is the download function
private void DownloadFromDropboxFromPath (String downloadPathTo, String downloadPathFrom)
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
private void DownloadFromDropboxFromPath(){
{ dir.mkdirs();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
MainActivity.mDBApi.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
}
public MainActivity getMain()
{
return this;
}
}
i want to upload my SQlite databse file to dropbox below is my code
public class DropboxActivity extends Activity {
private DropboxAPI<AndroidAuthSession> dropbox;
private final static String FILE_DIR = Environment.getExternalStorageDirectory()+"/MyFolder/BD/Demo.sqlite";
private final static String DROPBOX_NAME = "dropbox_prefs";
private final static String ACCESS_KEY = "key";
private final static String ACCESS_SECRET = "sec_key";
private boolean isLoggedIn;
private Button logIn;
private Button uploadFile;
private Button listFiles;
private LinearLayout container;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
logIn = (Button) findViewById(R.id.dropbox_login);
uploadFile = (Button) findViewById(R.id.upload_file);
listFiles = (Button) findViewById(R.id.list_files);
container = (LinearLayout) findViewById(R.id.container_files);
uploadFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("UPload");
UploadFileToDropbox upload = new UploadFileToDropbox(DropboxActivity.this, dropbox, FILE_DIR);
upload.execute();
}
});
logIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (isLoggedIn) {
dropbox.getSession().unlink();
loggedIn(false);
} else {
dropbox.getSession().startAuthentication(DropboxActivity.this);
}
}
});
listFiles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,
handler);
list.execute();
}
});
loggedIn(false);
AndroidAuthSession session;
AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
String key = prefs.getString(ACCESS_KEY, null);
String secret = prefs.getString(ACCESS_SECRET, null);
if (key != null && secret != null) {
AccessTokenPair token = new AccessTokenPair(key, secret);
session = new AndroidAuthSession(pair, AccessType.APP_FOLDER, token);
} else {
session = new AndroidAuthSession(pair, AccessType.APP_FOLDER);
}
dropbox = new DropboxAPI<AndroidAuthSession>(session);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = dropbox.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
Editor editor = prefs.edit();
editor.putString(ACCESS_KEY, tokens.key);
editor.putString(ACCESS_SECRET, tokens.secret);
editor.commit();
loggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(this, "Error during Dropbox authentication",
Toast.LENGTH_SHORT).show();
}
}
}
public void loggedIn(boolean isLogged) {
isLoggedIn = isLogged;
uploadFile.setEnabled(isLogged);
listFiles.setEnabled(isLogged);
logIn.setText(isLogged ? "Log out" : "Log in");
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
ArrayList<String> result = msg.getData().getStringArrayList("data");
for (String fileName : result) {
Log.i("ListFiles", fileName);
TextView tv = new TextView(DropboxActivity.this);
tv.setText(fileName);
container.addView(tv);
}
}
};
}
UploadFileToDropbox.java
public class UploadFileToDropbox extends AsyncTask<Void, Void, Boolean> {
private DropboxAPI<?> dropbox;
private String path;
private Context context;
public UploadFileToDropbox(Context context, DropboxAPI<?> dropbox,
String path) {
this.context = context.getApplicationContext();
this.dropbox = dropbox;
this.path = path;
}
#Override
protected Boolean doInBackground(Void... params) {
final File tempDir = context.getCacheDir();
File tempFile;
FileWriter fr;
try {
tempFile=new File(path);
System.out.println("path "+path);
FileInputStream fileInputStream = new FileInputStream(tempFile);
dropbox.putFile(path, fileInputStream,tempFile.length(), null, null);
tempFile.delete();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(context, "File Uploaded Sucesfully!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed to upload file", Toast.LENGTH_LONG)
.show();
}
}
}
when i run above cod ei t gave me error like as below in my logcat
DropboxServerException (nginx): 403 None (Forbidden)
at com.dropbox.client2.RESTUtility.parseAsJSON(RESTUtility.java:265)
at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:415)
at com.dropbox.client2.DropboxAPI$BasicUploadRequest.upload(DropboxAPI.java:1119)
at com.dropbox.client2.DropboxAPI.putFile(DropboxAPI.java:1460)
at com.example.dropdemo.UploadFileToDropbox.doInBackground(UploadFileToDropbox.java:42)
at com.example.dropdemo.UploadFileToDropbox.doInBackground(UploadFileToDropbox.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Removing a connection that never existed!
getSelectedText on inactive InputConnection
setComposingText on inactive InputConnection
Above error give line at below
dropbox.putFile(path, fileInputStream,tempFile.length(), null, null);
any idea how can i solve this ?
I am getting some issue when image is uploaded to flickr,oath token as well as user credentials get stored in the web browser cache.As a result am not being able to sign out from it.So when I go to flickr to upload my image again,it automatically uploads it rather than opening the login page.Now when I clear all the default browser cookies,then it ask for the login page.Is there any other way to sign out it automatically when I am redirected back to my application.Any kind of support will be appreciated.
Thanks in advance...
try this ,here....,FlickerHelper.java
public final class FlickrHelper {
private static FlickrHelper instance = null;
private static final String API_KEY = ""; //$NON-NLS-1$
public static final String API_SEC = ""; //$NON-NLS-1$
private FlickrHelper() {
}
public static FlickrHelper getInstance() {
if (instance == null) {
instance = new FlickrHelper();
}
return instance;
}
public Flickr getFlickr() {
try {
Flickr f = new Flickr(API_KEY, API_SEC, new REST());
return f;
} catch (ParserConfigurationException e) {
return null;
}
}
public Flickr getFlickrAuthed(String token, String secret) {
Flickr f = getFlickr();
RequestContext requestContext = RequestContext.getRequestContext();
OAuth auth = new OAuth();
auth.setToken(new OAuthToken(token, secret));
requestContext.setOAuth(auth);
return f;
}
public InterestingnessInterface getInterestingInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getInterestingnessInterface();
} else {
return null;
}
}
public PhotosInterface getPhotosInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getPhotosInterface();
} else {
return null;
}
}
}
FlickerjActivity.java
public class FlickrjActivity extends Activity {
public static final String CALLBACK_SCHEME = "flickrj-android-sample-oauth"; //$NON-NLS-1$
public static final String PREFS_NAME = "flickrj-android-sample-pref"; //$NON-NLS-1$
public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; //$NON-NLS-1$
public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; //$NON-NLS-1$
public static final String KEY_USER_NAME = "flickrj-android-userName"; //$NON-NLS-1$
public static final String KEY_USER_ID = "flickrj-android-userId"; //$NON-NLS-1$
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("flickImagePath")) {
path = getIntent().getStringExtra("flickImagePath");
}
}
new Thread() {
public void run() {
h.post(init);
};
}.start();
}
Handler h = new Handler();
Runnable init = new Runnable() {
#Override
public void run() {
OAuth oauth = getOAuthToken();
if (oauth == null || oauth.getUser() == null) {
OAuthTask task = new OAuthTask(getContext());
task.execute();
} else {
load(oauth);
}
}
};
private void load(OAuth oauth) {
if (oauth != null) {
UploadPhotoTask taskUpload = new UploadPhotoTask(this, new File(
path));
taskUpload.setOnUploadDone(new UploadPhotoTask.onUploadDone() {
#Override
public void onComplete() {
finish();
}
});
taskUpload.execute(oauth);
}
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String scheme = intent.getScheme();
OAuth savedToken = getOAuthToken();
if (CALLBACK_SCHEME.equals(scheme)
&& (savedToken == null || savedToken.getUser() == null)) {
Uri uri = intent.getData();
String query = uri.getQuery();
String[] data = query.split("&"); //$NON-NLS-1$
if (data != null && data.length == 2) {
String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
String oauthVerifier = data[1]
.substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
OAuth oauth = getOAuthToken();
if (oauth != null && oauth.getToken() != null
&& oauth.getToken().getOauthTokenSecret() != null) {
GetOAuthTokenTask task = new GetOAuthTokenTask(this);
task.execute(oauthToken, oauth.getToken()
.getOauthTokenSecret(), oauthVerifier);
}
}
}
}
public void onOAuthDone(OAuth result) {
if (result == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
} else {
User user = result.getUser();
OAuthToken token = result.getToken();
if (user == null || user.getId() == null || token == null
|| token.getOauthToken() == null
|| token.getOauthTokenSecret() == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
return;
}
String message = String
.format(Locale.US,
"Authorization Succeed: user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
saveOAuthToken(user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
load(result);
}
}
public OAuth getOAuthToken() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
if (oauthTokenString == null && tokenSecret == null) {
// logger.warn("No oauth token retrieved"); //$NON-NLS-1$
return null;
}
OAuth oauth = new OAuth();
String userName = settings.getString(KEY_USER_NAME, null);
String userId = settings.getString(KEY_USER_ID, null);
if (userId != null) {
User user = new User();
user.setUsername(userName);
user.setId(userId);
oauth.setUser(user);
}
OAuthToken oauthToken = new OAuthToken();
oauth.setToken(oauthToken);
oauthToken.setOauthToken(oauthTokenString);
oauthToken.setOauthTokenSecret(tokenSecret);
return oauth;
}
public void saveOAuthToken(String userName, String userId, String token,
String tokenSecret) {
SharedPreferences sp = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(KEY_OAUTH_TOKEN, token);
editor.putString(KEY_TOKEN_SECRET, tokenSecret);
editor.putString(KEY_USER_NAME, userName);
editor.putString(KEY_USER_ID, userId);
editor.commit();
}
private Context getContext() {
return this;
}
}
GetAouthToken.java
public class GetOAuthTokenTask extends AsyncTask<String, Integer, OAuth> {
private FlickrjActivity activity;
public GetOAuthTokenTask(FlickrjActivity context) {
this.activity = context;
}
#Override
protected OAuth doInBackground(String... params) {
String oauthToken = params[0];
String oauthTokenSecret = params[1];
String verifier = params[2];
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthInterface oauthApi = f.getOAuthInterface();
try {
return oauthApi.getAccessToken(oauthToken, oauthTokenSecret,
verifier);
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(OAuth result) {
if (activity != null) {
activity.onOAuthDone(result);
}
}
}
Oauthtask.java
public class OAuthTask extends AsyncTask<Void, Integer, String> {
private static final Uri OAUTH_CALLBACK_URI = Uri
.parse(FlickrjActivity.CALLBACK_SCHEME + "://oauth"); //$NON-NLS-1$
private Context mContext;
private ProgressDialog mProgressDialog;
public OAuthTask(Context context) {
super();
this.mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext,
"", "Generating the authorization request..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
OAuthTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(Void... params) {
try {
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
OAUTH_CALLBACK_URI.toString());
saveTokenSecrent(oauthToken.getOauthTokenSecret());
URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
Permission.WRITE, oauthToken);
return oauthUrl.toString();
} catch (Exception e) {
return "error:" + e.getMessage(); //$NON-NLS-1$
}
}
private void saveTokenSecrent(String tokenSecret) {
FlickrjActivity act = (FlickrjActivity) mContext;
act.saveOAuthToken(null, null, null, tokenSecret);
}
#Override
protected void onPostExecute(String result) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (result != null && !result.startsWith("error")) { //$NON-NLS-1$
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(result)));
} else {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
}
}
uploadphototask.java
public class UploadPhotoTask extends AsyncTask<OAuth, Void, String> {
private final FlickrjActivity flickrjAndroidSampleActivity;
private File file;
public UploadPhotoTask(FlickrjActivity flickrjAndroidSampleActivity,
File file) {
this.flickrjAndroidSampleActivity = flickrjAndroidSampleActivity;
this.file = file;
}
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(flickrjAndroidSampleActivity,
"", "Uploading..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
UploadPhotoTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(OAuth... params) {
OAuth oauth = params[0];
OAuthToken token = oauth.getToken();
try {
Flickr f = FlickrHelper.getInstance().getFlickrAuthed(
token.getOauthToken(), token.getOauthTokenSecret());
UploadMetaData uploadMetaData = new UploadMetaData();
uploadMetaData.setTitle("" + file.getName());
return f.getUploader().upload(file.getName(),
new FileInputStream(file), uploadMetaData);
} catch (Exception e) {
Log.e("boom!!", "" + e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (response != null) {
Log.e("", "" + response);
} else {
}
if (monUploadDone != null) {
monUploadDone.onComplete();
}
Toast.makeText(flickrjAndroidSampleActivity.getApplicationContext(),
response, Toast.LENGTH_SHORT).show();
}
onUploadDone monUploadDone;
public void setOnUploadDone(onUploadDone monUploadDone) {
this.monUploadDone = monUploadDone;
}
public interface onUploadDone {
void onComplete();
}
}
mainactivty.java
public class MainActivity extends Activity {
File fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnFlickr = (Button) findViewById(R.id.btnFlickr);
btnFlickr.setOnClickListener(mFlickrClickListener);
Button btnPick = (Button) findViewById(R.id.btnPick);
btnPick.setOnClickListener(mPickClickListener);
}
View.OnClickListener mPickClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivityForResult(intent, 102);
}
};
View.OnClickListener mFlickrClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fileUri == null) {
Toast.makeText(getApplicationContext(), "Please pick photo",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(getApplicationContext(),
FlickrjActivity.class);
intent.putExtra("flickImagePath", fileUri.getAbsolutePath());
startActivity(intent);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 102) {
if (resultCode == Activity.RESULT_OK) {
Uri tmp_fileUri = data.getData();
((ImageView) findViewById(R.id.imageView1))
.setImageURI(tmp_fileUri);
String selectedImagePath = getPath(tmp_fileUri);
fileUri = new File(selectedImagePath);
Debug.e("", "fileUri : " + fileUri.getAbsolutePath());
}
}
};
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
usercard.java
public class UserCard {
public String name;
public String url;
public int upVotes;
public int downVotes;
}
debug.java
public class Debug {
private static final boolean DEBUG = true;
public static void e(String tag, String msg) {
if (DEBUG) {
Log.e(tag, msg);
}
}public static void i(String tag, String msg) {
if (DEBUG) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (DEBUG) {
Log.w(tag, msg);
}
}
public static void d(String tag, String msg) {
if (DEBUG) {
Log.d(tag, msg);
}
}
}
i have implemented Parceleble but still it shows error in the putExtra. can anyone help me to figure out what is wrong with the code and how to rectify it.i want to use mApi object in another activity . if any other way is possible then please help me out.
public class DropboxActivity extends Activity implements Parcelable {
private static final String TAG = "DropboxActivity";
final static private String APP_KEY = "----------------";
final static private String APP_SECRET = "-------------";
final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
private Button mSubmit;
private LinearLayout mDisplay;
private Button upload;
private Button download;
private ImageView mImage;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
setContentView(R.layout.main);
checkAppKeySetup();
mSubmit = (Button)findViewById(R.id.auth_button);
mSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mLoggedIn) {
logOut();
} else {
mApi.getSession().startAuthentication(DropboxActivity.this);
}
}
});
mDisplay = (LinearLayout)findViewById(R.id.logged_in_display);
mImage = (ImageView)findViewById(R.id.image_view);
upload = (Button)findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("upload");
intent.putExtra("object", mApi);
startActivity(intent);
}
});
download = (Button)findViewById(R.id.download);
setLoggedIn(mApi.getSession().isLinked());
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
private void logOut() {
mApi.getSession().unlink();
clearKeys();
setLoggedIn(false);
}
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Unlink from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Link with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
if (APP_KEY.startsWith("CHANGE") ||
APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
finish();
return;
}
Intent testIntent = new Intent(Intent.ACTION_VIEW);
String scheme = "db-" + APP_KEY;
String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
testIntent.setData(Uri.parse(uri));
PackageManager pm = getPackageManager();
if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
showToast("URL scheme in your app's " +
"manifest is not set up correctly. You should have a " +
"com.dropbox.client2.android.AuthActivity with the " +
"scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
private void storeKeys(String key, String secret) {
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
} else {
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
}
return session;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
I think it is a bad idea to make your activity parcelable. Activities are not supposed to be transported via intents. And if your activities are inside the same application, you do not need transport via intent at all - just stick with standard java mechanisms.