I want to send text file to dropbox but it is showing DropboxUnlinkedException.
Solution ::
First, let your program get fully authenticated. Just after mDBApi.getSession.startAuthentication() method, onResume method will get called automatically. Let the full authentication get completed and then do what do you want to do.
MainActivity
public class MainActivity extends Activity implements LocationListener{
TextView date;
TextView lati;
TextView longi;
Button b1;
private DropboxAPI<AndroidAuthSession> mDBApi;
private LocationManager locationManager;
private String provider;
final static public String ACCOUNT_PREFS_NAME = "GPS_File";
final static public String APP_KEY = "5qiq4z06ikagxfb";
final static public String APP_SECRET = "f6mbf1hnn0re2ni";
final static public AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
boolean mIsLoggedIn = false;
#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, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
//this is start authentication
mDBApi.getSession().startAuthentication(MainActivity.this);
//after this it will call onResume
date = (TextView)findViewById(R.id.textView2);
lati = (TextView)findViewById(R.id.textView4);
longi = (TextView)findViewById(R.id.textView6);
b1 = (Button)findViewById(R.id.button1);
createFile("abcd", "12345", "54321");
toDropbox();
setLoggedIn(mDBApi.getSession().isLinked());
}
void createFile(String str1,String str2,String str3)
{
String data = str1+"\t"+str2+"\t"+str3;
try{
File myFile = new File("/sdcard/DropboxFile1.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
}
catch(Exception e)
{e.printStackTrace();}
}
void toDropbox()
{
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/DropboxFile1.txt";
File file = new File(filePath);
mDBApi.getSession().startAuthentication(MainActivity.this);
try {
mDBApi.putFileOverwrite(filePath, new FileInputStream(file), file.length(), null);
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
//This get call after StartAuthentication..
protected void onResume() {
super.onResume();
AndroidAuthSession session = mDBApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(true);
} catch (IllegalStateException e) {
//Keep this toast.. It will show you the completed authentication..
Toast.makeText(getBaseContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.i("Dropbox", "Error authenticating", e);
}
}
}
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(APP_KEY, key);
edit.putString(APP_SECRET, secret);
edit.commit();
}
public void setLoggedIn(boolean loggedIn) {
mIsLoggedIn = loggedIn;
}
public boolean isLoggedIn() {
return mIsLoggedIn;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}//MainActivity Ends..`
`
After authentication get completed do your another stuff.
You're calling startAuthentication but then immediately trying to call API methods (before authentication has actually happened). You can only use the API once the user has authenticated. In your code, here's the part that runs after the user has authenticated and returns to your app:
protected void onResume() {
...
if (session.authenticationSuccessful()) {
...
This error might also come when you miss calling this in onResume() of your activity :
mDBApi.getSession().finishAuthentication();
Related
I have a service which registers a shared preference change listener. The shared preference belongs to another app and is world readable. Despite of keeping a global instance of listener as suggested here, My onSharedPreferenceChanged() is not getting called .
The code of the service is as follows:
public class ClientService extends Service {
public static FileObserver observer;
public static final String addr = "127.0.0.1";
public static final int port = 5001;
public Socket socket = null;
InputStream inputStream;
OutputStream outputStream;
String buffer = new String();
OnSharedPreferenceChangeListener listener;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG, "killing service");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG, "Starting Activity");
Context context = null;
/*try {
socket = new Socket(addr, port);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e(MainActivity.TAG, "Error in opening Socket");
}*/
Log.d(MainActivity.TAG,"Carrying on...");
final MyClientTask clientTask = new MyClientTask(addr, port);
SharedPreferences sp = null;
try {
context = getApplicationContext().createPackageContext("net.osmand.plus", Context.MODE_WORLD_WRITEABLE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Log.e(MainActivity.TAG,"OSMAnd Package not found");
}
if(context != null) {
sp = context.getSharedPreferences("net.osmand.settings", Context.MODE_WORLD_READABLE);
Log.d(MainActivity.TAG, ""+sp.getFloat("last_known_map_lat", 0));
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG,"Shared preference "+key+" changed");
if(key == "last_known_map_lat" || key == "last_known_map_lon") {
/* Send this via socket */
float data = sharedPreferences.getFloat(key, 0);
Log.d(MainActivity.TAG, "Sending data: "+data);
clientTask.execute(""+data);
}
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
}
observer = new FileObserver("/data/data/net.osmand.plus/shared_prefs/net.osmand.settings.xml" ) {
#Override
public void onEvent(int event, String path) {
// TODO Auto-generated method stub
if(event == FileObserver.MODIFY) {
Log.d(MainActivity.TAG, "Changed");
}
}
};
return super.onStartCommand(intent, flags, startId);
}
public class MyClientTask extends AsyncTask<String, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(String... buffer) {
try {
byte[] bytes = buffer[0].getBytes();
//outputStream.write(bytes);
Log.d(MainActivity.TAG, "blah");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
The shared preference related code is in onStartCommand().
Anyone has any clue what is wrong ?
Note that in the actual Sharedpreferences file, I can observe the value changing when I see using adb shell
context = getApplicationContext().createPackageContext("net.osmand.plus", Context.MODE_WORLD_WRITEABLE);
your context is null
your con just use "this" service is itself a context
or you can try getSharedPreferences("net.osmand.settings", Context.MODE_WORLD_READABLE);
It seems from this post that what I am trying to do is unsupported in Android. WORLD_READABLE flag for SharedPreferences does not support multi-thread support which might be causing the inconsistencies. In the Android developer site also it is mentioned that multiple process support for SharedPreferences is not available for WORLD_READABLE preferences.
i have made an application that gives user option to upload and download dropbox application. i am giving my app secret and app key. the question is when some one else use my application do they need to enter their app secret and app key?
if yes, why? and if no then whats the actual purpose of app secret and app key. i am sharing the code as well:
upload file:
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.UploadRequest;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxFileSizeException;
import com.dropbox.client2.exception.DropboxIOException;
import com.dropbox.client2.exception.DropboxParseException;
import com.dropbox.client2.exception.DropboxPartialFileException;
import com.dropbox.client2.exception.DropboxServerException;
import com.dropbox.client2.exception.DropboxUnlinkedException;
/**
* Here we show uploading a file in a background thread, trying to show
* typical exception handling and flow of control for an app that uploads a
* file from Dropbox.
*/
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private final ProgressDialog mDialog;
private String mErrorMsg;
public UploadFile(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + file.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
if (mRequest != null) {
mRequest.upload();
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("File successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
Download file:
/**
* Here we show getting metadata for a directory and downloading a file in a
* background thread, trying to show typical exception handling and flow of
* control for an app that downloads a file from Dropbox.
*/
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI<?> mApi;
private String mPath;
private ImageView mView;
private Drawable mDrawable;
private FileOutputStream mFos;
private boolean mCanceled;
private Long mFileLen;
private String mErrorMsg;
// Note that, since we use a single file name here for simplicity, you
// won't be able to use this code for two simultaneous downloads.
private final static String IMAGE_FILE_NAME = "dbroulette.png";
private String localFilePath;
private String dropboxPath;
public DownloadFile(Context context, DropboxAPI<?> api,
String dropboxPath, String localFilePath) {
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
this.localFilePath = localFilePath;
this.dropboxPath= dropboxPath;
mApi = api;
mPath = dropboxPath;
mDialog = new ProgressDialog(context);
mDialog.setMessage("Downloading File");
mDialog.setButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mCanceled = true;
mErrorMsg = "Canceled";
// This will cancel the getThumbnail operation by closing
// its stream
if (mFos != null) {
try {
mFos.close();
} catch (IOException e) {
}
}
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try{
File localFile = new File(localFilePath);
File fileSelected = new File(dropboxPath);
if (!localFile.exists()) {
localFile.createNewFile();
} else {
//copy(fileSelected, localFile);
//mApi.copy("/Test/test.png", "/sdcard/testfile.png");
BufferedInputStream br = null;
BufferedOutputStream bw = null;
DropboxInputStream fd;
try {
fd = mApi.getFileStream(fileSelected.getPath(), null);
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}/*
else {
showToast("File already exists");
}*/
}
catch (IOException e) {
showToast("Exception");
e.printStackTrace();
}
catch (Exception e) {
showToast("Exception");
e.printStackTrace();
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
// Set the image now that we have it
//mView.setImageDrawable(mDrawable);
showToast("Successful download");
} else {
// Couldn't download it, so show an error
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
main activity:
public class MainActivity extends Activity {
// Replace this with your app key and secret assigned by Dropbox.
// Note that this is a really insecure way to do this, and you shouldn't
// ship code which contains your key & secret in such an obvious way.
// Obfuscation is good.
final static private String APP_KEY = "";
final static private String APP_SECRET = "";
// You don't need to change these, leave them alone.
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";
private static final boolean USE_OAUTH1 = false;
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
private Button mSubmit;
private Button btnUpload;
private Button btnDownload;
private LinearLayout mDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
setContentView(R.layout.main);
mSubmit = (Button)findViewById(R.id.auth_button);
btnDownload = (Button)findViewById(R.id.roulette_button);
btnUpload = (Button)findViewById(R.id.photo_button);
mDisplay = (LinearLayout)findViewById(R.id.logged_in_display);
mSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
if (USE_OAUTH1) {
mApi.getSession().startAuthentication(MainActivity.this);
} else {
mApi.getSession().startOAuth2Authentication(MainActivity.this);
}
}
}
});
// Upload File
String testFile = "DeviceAdmin.apk";
String outPath = new File(Environment.getExternalStorageDirectory(), testFile).getPath();
Toast.makeText(MainActivity.this, outPath, Toast.LENGTH_LONG).show();
final File outFile = new File(outPath);
btnUpload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try{
UploadFile upload = new UploadFile(MainActivity.this, mApi, "/Test/", outFile);
upload.execute();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_LONG).show();
}
}
});
// Download File
final String localFilePath = "/sdcard/testfile.txt";
final String dropboxPath= "/abc.txt";
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DownloadFile download = new DownloadFile(MainActivity.this, mApi, dropboxPath, localFilePath);
download.execute();
}
});
setLoggedIn(mApi.getSession().isLinked());
}
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
Toast.makeText(MainActivity.this, "Successful login", Toast.LENGTH_LONG).show();
mDisplay.setVisibility(View.VISIBLE);
} else {
Toast.makeText(MainActivity.this, "logged out", Toast.LENGTH_LONG).show();
mDisplay.setVisibility(View.GONE);
}
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
loadAuth(session);
return session;
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void loadAuth(AndroidAuthSession session) {
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 || key.length() == 0 || secret.length() == 0) return;
if (key.equals("oauth2:")) {
// If the key is set to "oauth2:", then we can assume the token is for OAuth 2.
session.setOAuth2AccessToken(secret);
} else {
// Still support using old OAuth 1 tokens.
session.setAccessTokenPair(new AccessTokenPair(key, secret));
}
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
storeAuth(session);
setLoggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(MainActivity.this, "Couldn't authenticate with Dropbox:" + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
Log.i("Exception: ", "Error authenticating", e);
}
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is one.
String oauth2AccessToken = session.getOAuth2AccessToken();
if (oauth2AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, "oauth2:");
edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
edit.commit();
return;
}
// Store the OAuth 1 access token, if there is one. This is only necessary if
// you're still using OAuth 1.
AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
if (oauth1AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
edit.commit();
return;
}
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
// Clear our stored keys
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
}
this is the code for reference, please have a look and give some suggestion.my main task is to retrieve a file, encrypt and upload it on dropbox.
No, users don't have to enter a different app key and secret. The app key and secret identifies your app. For example, when a user authorizes your app, they see the name of the app they're authorizing. That comes from the app key.
I am currently working on a project which requires me to enter and store user's input. Is there any way that I could do so that I can retrieve the previous records as well rather than the current record?
Code
package com.example;
// imports
public class Testing extends Activity {
String tag = "Testing";
EditText amount;
Uri rResult = null;
int request_Code = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testyourself);
amount = (EditText) findViewById(R.id.etUserInput);
Button saveButton = (Button) findViewById(R.id.btnSave);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.example.Result");
Bundle extras = new Bundle();
extras.putString("amount", amount.getText().toString());
intent.putExtras(extras);
startActivityForResult(intent, request_Code);
}
});
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
saveAsText(); // Step E.1
Log.d(tag, "In the onPause() event");
}
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
retrieveText(); // Step E.1
Log.d(tag, "In the onResume() event");
}
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
public void saveAsText() {
String line = amount.getText().toString();
if (rResult != null)
line += "|" + rResult;
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter pw = null;
try {
String path = Environment.getExternalStorageDirectory().getPath();
fw = new FileWriter(path + "/exercise.txt");
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
pw.println(line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pw != null)
pw.close();
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}// saveAsText
public void retrieveText() {
FileReader fr = null;
BufferedReader br = null;
try {
String line;
String path = Environment.getExternalStorageDirectory().getPath();
fr = new FileReader(path + "/exercise.txt");
br = new BufferedReader(fr);
line = br.readLine();
StringTokenizer st = new StringTokenizer(line, "|");
pullup.setText(st.nextToken());
bench.setText(st.nextToken());
String rResult;
if (st.hasMoreTokens())
rResult = st.nextToken();
else
rResult = "";
Log.d(tag, "readAsText: " + line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Results Page
public class Result extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
Bundle bundle = getIntent().getExtras();
int amount = Integer.parseInt(bundle.getString("amount"));
TextView ResultView = (TextView) findViewById(R.id.userInput);
ResultView.setText(String.valueOf(amount));
}
}
Instead of writing to a file you can use SharedPreferences which allows you to store information such as user inputs or statistics until explicitly removed. Even if you close your app and re-open it the information that you save using SharedPreferences will remain.
The selected answer for this question is a great example of creating a helper class for SharedPreferences that will allow you to easily save, retrieve, and delete information.
Assuming that you want to save an int value.
If your save and retrieve methods in your helper class are:
public void saveAmount(String key, int amount) {
_prefsEditor.putInt(key,amount);
_prefsEditor.commit();
}
public int getAmount(String key) {
return _sharedPrefs.getInt(key,0); //returns 0 if nothing is found
}
and you have an ArrayList of ints like so:
ArrayList<int> arrayList = new ArrayList<int>();
arrayList.add(123);
arrayList.add(231);
arrayList.add(312); //These are just placeholder values.
then you can create a loop to save:
private AppPreferences _appPrefs;
.
.
.
for(int i = 0; i < arrayList.size(); i++) {
_appPrefs.saveAmount(i,arrayList.get(i));
}
Note that in the above method the keys for the elements are just the indices of the elements within the array.
In order to retrieve the information and recreate the ArrayList you need to first save the length of the ArrayList in shared preferences as well.
public void saveLength(int length) {
_prefsEditor.putInt("length", length);
_prefsEditor.commit();
}
public int getLength() {
return _sharedPrefs.getInt("length",0);
}
then you can create a loop to retrieve:
ArrayList<int> arrayList = new ArrayList<int>();
.
.
.
for(int i = 0; i < _appPrefs.getLength(); i++) {
arrayList.add(getAmount("" + i));
}
So far i have created a demo project. Registered the project in Flickr and got the key and secret. I created 1 xml with username/email[EditText] and password[EditText] and submit[Button]. I searched a lot for Flickr api where i can give username and password as input and get some responce , but failed. So please guide me what to do to login into Flickr.
thanks in advance..
You can use following code :
public class MainActivity extends Activity implements OnClickListener {
private Button loginTumblrBtn;
private CommonsHttpOAuthConsumer consumer;
private CommonsHttpOAuthProvider provider;
private SharedPreferences preferences;
private Uri uri;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("tumblr", Context.MODE_PRIVATE);
loginTumblrBtn = (Button) findViewById(R.id.login_tumblr);
loginTumblrBtn.setOnClickListener(this);
consumer = new CommonsHttpOAuthConsumer(Constant.CONSUMER_KEY,
Constant.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(Constant.REQUEST_TOKEN_URL,
Constant.ACCESS_TOKEN_URL, Constant.AUTH_URL);
uri = this.getIntent().getData();
if (uri != null
&& uri.getScheme().equals(Constant.OAUTH_CALLBACK_SCHEME)) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
consumer.setTokenWithSecret(
preferences.getString("requestToken", ""),
preferences.getString("requestSecret", ""));
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer,
uri.getQueryParameter(OAuth.OAUTH_VERIFIER));
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", consumer.getToken());
editor.putString("token_secret",
consumer.getTokenSecret());
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_tumblr:
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", null);
editor.putString("token_secret", null);
editor.commit();
} else {
progressDialog = ProgressDialog.show(this, "Loading",
"Please Wait...");
new Thread(new Runnable() {
#Override
public void run() {
try {
String authUrl = provider.retrieveRequestToken(
consumer, Constant.CALLBACK_URL);
SharedPreferences.Editor editor = preferences
.edit();
editor.putString("requestToken",
consumer.getToken());
editor.putString("requestSecret",
consumer.getTokenSecret());
editor.commit();
startActivity(new Intent(
"android.intent.action.VIEW", Uri
.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
If you want to share image and video on Tumblr then check this
I was trying to do a service sample program and i am getting following exception
09-10 20:57:57.871: E/AndroidRuntime(280): FATAL EXCEPTION: main 09-10
20:57:57.871: E/AndroidRuntime(280): java.lang.RuntimeException:
Unable to instantiate service com.example.demoservice.DownloadService:
java.lang.InstantiationException:
com.example.demoservice.DownloadService
I have seen many solutions to this type of execption like passing string to constructor etc.But those solutions didnt solved this issue.
Code sample is given below
public class MainActivity extends Activity {
TextView textView ;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if(bundle != null){
String filepath = bundle.getString(DownloadService.FILEPATH);
int result = bundle.getInt(DownloadService.RESULT);
if(result == Activity.RESULT_OK){
Toast.makeText(context, "Sucess" + filepath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Sucess", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
Intent i = new Intent(this, DownloadService.class);
i.putExtra(DownloadService.FILENAME, "index.html");
i.putExtra(DownloadService.URL, "http://www.vogella.com/index.html");
startService(i);
textView.setText("Service started");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
}
Service class
public class DownloadService extends IntentService{
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String urlpath = intent.getStringExtra(URL);
String filename = intent.getStringExtra(urlpath);
File output = new File(Environment.getExternalStorageDirectory(), filename);
if(output.exists()){
output.delete();
}
InputStream input = null;
FileOutputStream fout = null;
try {
java.net.URL url = new java.net.URL(urlpath);
input = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(input);
fout = new FileOutputStream(output.getPath());
int next = -1;
while((next = reader.read())!= -1){
fout.write(next);
}
result = Activity.RESULT_OK;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fout != null){
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
publishResult( output.getAbsoluteFile(), result);
}
private void publishResult(File absoluteFile, int result2) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,DownloadService.class);
intent.putExtra(FILEPATH, absoluteFile);
intent.putExtra(RESULT, result2);
sendBroadcast(intent);
}
}
I am running app using Emulator.Is it possible to run this problem in emulator,because writing to external directory
Can anyone help me?
Use
public DownloadService() {
super("DownloadService");
// TODO Auto-generated constructor stub
}
Instead of
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
UPDATE:
You have to declare a default constructor which calls the public IntentService (String name) super constructor of the IntentService class you extend. ie. In simple words, you need to provide no-argument constuctor for your service ,without which android wont be able to instantiate your service.
you start the intentservice using startService(your_intent); And as per the documentation
You should not override onStartCommand() method for your
IntentService. Instead, override onHandleIntent(Intent), which the
system calls when the IntentService receives a start request.
IntentService