This might be a complex problem with my application but I'll do my best to describe it as accurately as I can.
I am making an Android Client and making use of a couple of helper classes someone else handed to me at work. The helper Android classes are called TcpClient.java and PVDCAndroidClient.java. PVDCAndroidClient.java makes use out of the TcpCLient, using a tcpCLient object to connect via serverIP and port.
Here is PVDCAndroidClient.java:
public class PVDCAndroidClient {
// constants
public static final String DEFAULT_LOGIN_URI = "http://me.net:8000/";
private TcpClient tcpClient = null;
private UdpClient udpClient = null;
private boolean connected = false;
private boolean loggedin = false;
private static SimpleDateFormat sdf;
private String loginURI = DEFAULT_LOGIN_URI;
private int getUserNumber;
TcpMessageListener listener = null;
/**
* Connects to proxy server, blocks until complete or timeout
* #param serverIP
* #param port
*/
public void connect(String serverIP, int port)
{
try
{
if(serverIP.length() != 0 && port != 0)
{
tcpClient = new TcpClient();
tcpClient.addTcpListener(listener);
tcpClient.connect(serverIP, port);
}
}
catch(Exception e)
{
e.printStackTrace();
Log.d("Could not connect to server, possbile timeout...", "error");
}
}
///// Make login function a blocking call
// Default login, use last location as login location
public boolean login(String fName, String lName, String password)
{
return this.login(fName, lName, password, "last location");
}
public boolean login(String fName, String lName, String password, String region)
{
return this.login(fName, lName, password, "last location", 128, 128, 20);
}
public boolean login(String fName, String lName, String password, String region, int loginX, int loginY, int loginZ)
{ sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// Check passed values
// x, y and z should be between [0, 256]
// strings should not be null or empty(except lName which can be empty)
if((loginX >= 0 && loginX <= 256) && (loginY >=0 && loginY <= 256) && (loginZ >= 0 && loginZ <= 256))
{
if(fName.length() != 0 && fName != null)
{
// Construct packet xml structure
// Send request and wait until reply or timeout
// return false if timeout (or throw exception?)
// if not timeout, read result packet and determine return value
// getUserNumber = tcpClient.getUserNum();
StringWriter stringWriter = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(stringWriter);
// Indentation is not required, but helps with reading
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
// TODO: Remove hardcoding of strings, make either constants or place in strings.xml
// TODO: Move the header construction to other method as it is fairly constant other than request num and no need to repeat that much code
serializer.startTag("", "pvdc_pkt");
serializer.startTag("", "pvdc_header");
// TODO: replace this with a string unique to the system
serializer.startTag("", "ID");
serializer.text("838393djdjdjd");
serializer.endTag("", "ID");
// TODO: replace this with actual user number from server
serializer.startTag("", "user_num");
serializer.text("22");//get userNum from above
serializer.endTag("", "user_num");
// TODO: add a request number counter to increment this on each request
serializer.startTag("", "request_num");
serializer.text("1");
serializer.endTag("", "request_num");
serializer.startTag("", "DateTime");
serializer.text(sdf.toString()); //utc time variable.
serializer.endTag("", "DateTime");
serializer.endTag("", "pvdc_header");
serializer.startTag("", "pvdc_content");
serializer.attribute("", "type", "requestlogin");
serializer.startTag("", "name");
serializer.attribute("", "fname", fName);
serializer.attribute("", "lname", lName);
serializer.endTag("", "name");
serializer.startTag("", "password");
serializer.text(password);
serializer.endTag("", "password");
serializer.startTag("", "server");
serializer.text(this.loginURI);
serializer.endTag("", "server");
serializer.startTag("", "location");
serializer.attribute("", "region", region);
serializer.text(loginX + ";" + loginY +";" + loginZ);
serializer.endTag("", "location");
serializer.endTag("", "pvdc_content");
serializer.endTag("", "pvdc_pkt");
// Finish writing
serializer.endDocument();
// write xml data out
serializer.flush();
//
sendLogin(stringWriter);
} catch (Exception e) {
Log.e("Exception", "error occurred while creating xml file");
return false;
}
// Print out xml for debugging
Log.d("PVDCAndroidClient Login", stringWriter.toString().trim());
}
else
{
Log.d("Error in name checking", "fName either blank or null");
}
}
else
{
Log.d("login coordinates X,Y, or Z not between 0-256", "Coordinates Error");
}
return true;
}
// moveString should contain the properly formatted movement command(s)[see above move request description]
public void sendLogin(StringWriter stringWriter)
{
tcpClient.sendMessage(stringWriter.toString());
}
}
Here is the actual TcpClient.java:
public class TcpClient {
public interface TcpMessageListener{
public void onMessage(TcpClient client, String message);
}
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private Thread listenThread = null;
private boolean listening = false;
private int userNum = -1;
private List<TcpMessageListener> listeners = new ArrayList<TcpMessageListener>();
public int getUserNum()
{
return this.userNum;
}
public TcpClient() {
}
public void addTcpListener(TcpMessageListener listener)
{
synchronized(this.listeners)
{
this.listeners.add(listener);
}
}
public void removeTcpListener(TcpMessageListener listener)
{
synchronized(this.listeners)
{
this.listeners.remove(listener);
}
}
public boolean connect(String serverIpOrHost, int port) {
try {
socket = new Socket(serverIpOrHost, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.listenThread = new Thread(new Runnable(){
public void run() {
int charsRead = 0;
char[] buff = new char[4096];
while(listening && charsRead >= 0)
{
try {
charsRead = in.read(buff);
if(charsRead > 0)
{
Log.d("TCPClient",new String(buff).trim());
String input = new String(buff).trim();
synchronized(listeners)
{
for(TcpMessageListener l : listeners){
l.onMessage(TcpClient.this, input);
}
}
if (input.toLowerCase().contains("<user_num>")){
int index = input.toLowerCase().indexOf("<user_num>");
index += "<user_num>".length();
int index2 = input.toLowerCase().indexOf("</user_num>");
userNum = Integer.parseInt(input.substring(index, index2));
}
}
} catch (IOException e) {
Log.e("TCPClient", "IOException while reading input stream");
listening = false;
}
}
}
});
this.listening = true;
this.listenThread.setDaemon(true);
this.listenThread.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
return false;
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
return false;
} catch (Exception e) {
System.err.println(e.getMessage().toString());
return false;
}
return true;
}
public void sendMessage(String msg) {
if(out != null)
{
out.println(msg);
out.flush();
}
}
public void disconnect() {
try {
if(out != null){
out.close();
out = null;
}
if(in != null){
in.close();
in = null;
}
if (socket != null) {
socket.close();
socket = null;
}
if(this.listenThread != null){
this.listening = false;
this.listenThread.interrupt();
}
this.userNum = -1;
} catch (IOException ioe) {
System.err.println("I/O error in closing connection.");
}
}
}
LASTLY, here is what I have been coding today and cannot seem to get this to work. I don't get any blatant exceptions, just a warning on Logcat, that says, "Couldn't get I/O for the connection".
public class AndroidClientCompnt extends Activity {
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptPassLoginActivity;
private String getIpAddressSharedPrefs;
private String getPassword, getName, getRegionSelect, getGridSelect;
private String fName, lName;
private SharedPreferences settings;
private boolean resultCheck = false;
private int portNum;
PVDCAndroidClient client;
private String name;
private CharSequence[] getView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Intent intent = getIntent();
// getting object's properties from LoginActivity class.
getName = intent.getStringExtra("name");
getPassword = intent.getStringExtra("password");
getRegionSelect = intent.getStringExtra("regionSelect");
getGridSelect = intent.getStringExtra("gridSelect");
Log.d("VARIABLES", "getName = " + getName + "getPassword" + getPassword
+ "getRegionSelect = " + getRegionSelect + ".");
setResult(Activity.RESULT_CANCELED);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
// grid selected as well? sometime?
settings = PreferenceManager.getDefaultSharedPreferences(this);
getIpAddressSharedPrefs = settings.getString(IP_ADDRESS_SHARED_PREFS,
"");
portNum = Integer.parseInt(settings.getString(PORT_SHARED_PREFS, ""));
Log.d("SHARED" + getIpAddressSharedPrefs + "port " + portNum, "");
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
try {
// first connect attempt.
client.connect(getIpAddressSharedPrefs, portNum);
resultCheck = client.isConnected();
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not connect.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Ip preference and port blank", Toast.LENGTH_LONG).show();
}
finish();
}
private class UploadTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
// encrypting user's password with Md5Hash class.
try {
encryptPassLoginActivity = MdHashing
.MD5(getPassword.toString());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (resultCheck == true) {
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = name.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,
getRegionSelect, 128, 128, 20);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent goToInWorld = new Intent(
AndroidClientCompnt.this.getApplicationContext(),
PocketVDCActivity.class);
startActivity(goToInWorld);
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}
I know this is a super long post and I am asking a lot but if anyone could take a look at this I would very much appreciate it. I've been at this all day, trying to make use of these helper classes I got and can't get it to work. It also doesn't help that I'm not too experienced in this client/server stuff. Any nudges in the right direction or an accepted solution would REALLY mean something to me.
Thank you kindly,
Have a good evening.
Can you post your manifest?
You may need to add the following :
<uses-permission android:name="android.permission.INTERNET"/>
Additionally - I assume you see nothing ever happen on the server side of this connection?
1) Make sure you have the following permission in your Android-Manifest file:
<uses-permission android:name="android.permission.INTERNET/>
w/o this you definitely won't be making any tcp/ip connections.
2) You will want to run the code in debug mode, and place breakpoints where the connection information
is set and also what results are at several points. In other words you need to dig deeper.
If you are somewhat new to coding there is no better investment of time than in running the debugger and stepping line by line through the code. Code only comes to life inside a debugger, where you can see the values of variables and results. So set several breakpoints, step through and you will see more. It is more difficult to debug where there are threads however.
Related
I'm using package com.hierynomus.smbj.share; to connect via smb2 to a network location in order to check it's connectivity however this only runs at the start of my activity (in background).
I've added a listener to return after the task has returned a string value (fail, success) once the the listener in the activity (i called the task from) is called, I then create a new instance of the Connection Status (this loops it)
This is how i check for the connection at onCreate() of an activity
//Global ConnectionStatus connectionStatus;
connectionStatus = new ConnectionStatus();
connectionStatus.setContext(this);
connectionStatus.setListener(this);
connectionStatus.setCon(databaseReadWrite.getMydbc());
connectionStatus.execute("CheckDatabase", "nodelay");
This is how I'm trying to cancel task when another activity is opened
protected void onPause() {
delay.equals("cancel");
super.onPause();
MyApplication.activityPaused();
if (connectionStatus != null) {
connectionStatus.cancel(true);
}
hasRun = false;
}
Then this runs in the same activity after the async task is completed so i've re-run a new instance of connectionStatus
#Override
public void onTaskCompleted(String result) {
ActionBar actionBar = this.getSupportActionBar();
String title = getTitle().toString();
String code = handlingFunctions.getResultCode(result);
if (code.equals("1")) {
Message.message(this, " Database connected to server!");
setTitle(title + result);
} else if (code.equals("2")) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
alertDialog.message(this, result);
} else if (code.equals("0")) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
setTitle(title + " Database connected in offline mode");
alertDialog.message(this, result);
} else if (code.equals("3")) {
//alertDialog.message(this, result);
imageStatus.setText(result);
} else if (code.equals("4")) {
imageStatus.setText(result);
}
connectionStatus = new ConnectionStatus();
connectionStatus.setContext(getApplicationContext());
connectionStatus.setListener(AllParts.this);
connectionStatus.setCon(databaseReadWrite.getMydbc());
connectionStatus.execute("CheckDatabase", "delay");
}
}
public class ConnectionStatus extends AsyncTask<String, Void, String> {
private OnConnectionStatusComplete listener;
private ArrayList<String> imageNames;
private ArrayList<ImageDetails> currentImageDetails;
private SQLiteConnection sqLiteConnection;
private Context context;
public void setListener(OnConnectionStatusComplete listen) {
this.listener = listen;
}
public void setImageNames(ArrayList<String> ImageNames) {
this.imageNames = ImageNames;
}
public void setCurrentDetails(ArrayList<ImageDetails> details) {
this.currentImageDetails = details;
}
#Override
protected void onPostExecute(String s) {
listener.onTaskCompleted(s);
}
public void setContext(Context mContext) {
context = mContext;
}
public void setCon(SQLiteConnection sqlite) {
sqLiteConnection = sqlite;
}
#Override
protected String doInBackground(String... strings) {
if(this.isCancelled()){
return "";
}else{
MyApplication myApplication = (MyApplication) context.getApplicationContext();
String IPAddress = myApplication.getIpaddress();
String domain = myApplication.getDomainname();
String username = myApplication.getUsername();
String password = myApplication.getPassword();
String containingFolder = myApplication.getSharefolder();
String temp = "";
//return null;
if (strings[1].equals("delay")) {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (strings[0].equals("CheckDatabase")) {
temp = checkDatabaseConnect();
} else {
temp = checkImageConnection(IPAddress, domain, username, password, containingFolder);
}
return temp;
}
}
String checkDatabaseConnect() {
String statement = "PRAGMA sync_status";
JSONArray is_ready = new JSONArray();
try {
SQLiteStatement mystatement = null;
try {
mystatement = sqLiteConnection.prepareStatement(statement);
} catch (SQLException ex) {
try {
java.io.File path = new java.io.File("/sdcard/exports/logs");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String currentDateTime = dateFormat.format(new Date()) + " ";
java.io.File myFile = new java.io.File(path, "DBCrashes.txt");
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("\n" +
"\r");
myOutWriter.append(currentDateTime + "Get pragma results: (" + statement + ")" + ex);
myOutWriter.close();
fOut.close();
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}
}
mystatement.step();
int ncols = mystatement.getColumnCount();
if (ncols > 0) {
String result = mystatement.getColumnTextNativeString(0);
JSONObject jObject = new JSONObject(result);
is_ready = jObject.getJSONArray("peers");
if (is_ready.length() > 0) {
return "Success, Database is connected! (1)";
} else {
return "The database is not connected to the server. In offline mode, check network and restart application to connect to server. (0)";
}
}
mystatement.dispose();
} catch (SQLException ex) {
try {
java.io.File path = new java.io.File("/sdcard/exports/logs");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String currentDateTime = dateFormat.format(new Date()) + " ";
java.io.File myFile = new java.io.File(path, "DBCrashes.txt");
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("\n" +
"\r");
myOutWriter.append(currentDateTime + " (" + statement + ")" + ex);
myOutWriter.close();
fOut.close();
return "No connection to a database, please try again (2)";
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}
} catch (JSONException e) {
e.printStackTrace();
}
return "Success (5)";
}
}
The problem I'm having is after I leave the activity, the task is still running and returns this error (I know this because it takes into account the delay)
You do have implemented a handling for isCanceled but this implementation is only at the start.
Your current flow is like this:
task starts, immediately checks if it is cancelled or not (since it is the first line in doInBackground)
onPause is called, cancel of the task is invoked
since the cancel check has already been made your task continues to run freely
How do you solve this?
The easiest way would be to check if it is cancelled before checkDatabaseConnection or checkImageConnection is called. And even inside those methods check if it is cancelled or not.
Even if that is done correctly, your Thread.sleep could cause your AsyncTask being cancelled 6s after onPause is called.
For reasons like this, AsyncTask is not used anymore. There are other options for Threading which are much better.
This or this will give you a starting point.
try checking if the task is cancelled after the Thread.sleep(6000) , so even if the task was in sleep when cancel is called it will return when it is done.
if (strings[1].equals("delay")) {
try {
Thread.sleep(6000);
if(this.isCancelled()) {
return "";
}
} catch (InterruptedException e) {
e.printStackTrace();
}
/*if(this.isCancelled()) {
return "";
}*/
}
I know this kind of questions are maybe too old, but I got stock with this silly thing.
I have an AsyncTask class which is a subclass of an activity class, and right now I want to call it from another class: following codes shows what I mean:
public class STA extends Activity {
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
private static final String TAG = "ListSpdFiles: ";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private String initiator;
private String path;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(String initiator, String path) {
this.initiator = initiator;
this.path = path;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(getApplicationContext(), pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
// tv.setText("task concluded with a null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
//tv.setText("List of files received is:\n" + Arrays.toString(listOfFiles));
}
term();
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
final Global globalVariable = (Global) getApplicationContext();
if (globalVariable.getPasswordButt() == false) {
// Calling Application class (see application tag in AndroidManifest.xml)
// Get name and email from global/application context
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
String username = "/" + getLastAccessedBrowserPage() + ".username" + ".txt";
//String password = "/" + CurrentURL + "password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, username, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setUsername(name);
// getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsUsername(false);
} else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
// globalVariable.setUsernameButt(false);
} else if (globalVariable.getPasswordButt() == true) {
// Calling Application class (see application tag in AndroidManifest.xml)
// final Global globalVariable = (Global) getApplicationContext();
// Get name and email from global/application context
final boolean ispassword = globalVariable.getIsPassword();
if (ispassword == true) {
// String username = "/" + CurrentURL + "username" + ".txt";
String password = "/" + getLastAccessedBrowserPage() + ".password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, password, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setPassword(name);
//getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsPassword(false);
} else if (ispassword == false)
Log.i(TAG, "Wrong Input Type For Password.");
globalVariable.setPasswordButt(false);
// boolpassword=false;
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
Would you please tell me what should I do to fix this code?
Looking over the code I did not see anywhere you referenced anything from the Activity itself besides the application context so you can move the ListSpdFiles class to its own java file and pass it a context into the constructor when you make a new instance of it.
Put this class in a ListSpdFiles.java file so it is no longer an inner class.
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
Context applicationContext;
public ListSpdFiles(Context context, String initiator, String path) {
this.initiator = initiator;
this.path = path;
applicationContext = context.getApplicationContext();
}
// The rest of your code still goes here. Replace other calls to
// getApplicationContext() with the new applicationContext field
}
You can now use this class anywhere a Context is available. You create a new instance by doing:
ListSpdFiles listSpdFilesTask = new ListSpdFiles(context, "someInitiator", "somePath");
listSpdFilesTask.execute();
I wanted to download images via Dropbox API so i followed the sample code # Android Dropbox API file download but i do not understand how to integrate it into my current code. I tried changing api.getFileStream("dropbox", dbPath, null); to dropbox.getFileStream("dropbox", dbPath, null); resulting in the error:
'getFileStream(java.lang.String, java.lang.String)' in 'com.dropbox.client2.DropboxAPI' cannot be applied to '(java.lang.String, java.lang.String, null)'
Updated 1 : Changed to `dropbox.getFileStream(FILE_DIR,null)
Main Code
public class Dropbox extends AppCompatActivity implements View.OnClickListener {
private DropboxAPI<AndroidAuthSession> dropbox;
private final static String FILE_DIR = "/DropboxSample/";
private final static String DROPBOX_NAME = "dropbox_prefs";
private final static String ACCESS_KEY = "Insert Key here";
private final static String ACCESS_SECRET = "Insert Key here";
private boolean isLoggedIn;
private Button logIn;
private Button uploadFile;
private Button downloadFile;
private Button listFiles;
private LinearLayout container;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dropbox);
logIn = (Button) findViewById(R.id.dropbox_login);
logIn.setOnClickListener(this);
uploadFile = (Button) findViewById(R.id.upload_file);
uploadFile.setOnClickListener(this);
downloadFile = (Button) findViewById(download_file);
downloadFile.setOnClickListener(this);
listFiles = (Button) findViewById(R.id.list_files);
listFiles.setOnClickListener(this);
container = (LinearLayout) findViewById(R.id.container_files);
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 ,token);
} else {
session = new AndroidAuthSession(pair );
}
dropbox = new DropboxAPI<>(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);
SharedPreferences.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);
downloadFile.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(Dropbox.this);
tv.setText(fileName);
container.addView(tv);
}
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dropbox_login:
if (isLoggedIn) {
dropbox.getSession().unlink();
loggedIn(false);
} else {
dropbox.getSession().startAuthentication(Dropbox.this);
}
break;
case R.id.list_files:
ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,
handler);
list.execute();
break;
case R.id.upload_file:
UploadFileToDropbox upload = new UploadFileToDropbox(dropbox, FILE_DIR);
upload.execute();
break;
case R.id.download_file:
try {
downloadDropboxFile(FILE_DIR,(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"CapturyGallery")));
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
public class UploadFileToDropbox extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> dropbox;
private String mPath;
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI.UploadRequest mRequest;
private String mErrorMsg;
private File[] listFile;
private int mFilesUploaded;
private int mCurrentFileIndex;;
public UploadFileToDropbox(DropboxAPI<?> dropbox, String path) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
listFile = file.listFiles();
mContext = Dropbox.this;
this.dropbox = dropbox;
this.mPath = path;
mFilesUploaded = 0 ;
mCurrentFileIndex = 0 ;
mDialog = new ProgressDialog(mContext);
mDialog.setMax(100);
mDialog.setMessage("Uploading file 1 /" +listFile.length);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
try {
mRequest.abort();
} catch (Exception e) {
}
}
});
mDialog.show();
mDialog.setCanceledOnTouchOutside(false);
}
#Override
protected Boolean doInBackground(Void... params) {
try {
for (int y = 0; y < listFile.length; y++) {
mCurrentFileIndex = y;
File file = listFile[y];
// 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(file);
String path = mPath + file.getName();
mRequest = dropbox.putFileOverwriteRequest(path, fis, file.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 5;
}
#Override
public void onProgress(long bytes, long total) {
if (isCancelled()) {
mRequest.abort();
} else {
publishProgress(bytes);
}
}
});
mRequest.upload();
if(!isCancelled()){
mFilesUploaded++;
}else{
return false;
}
}
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) {
long totalBytes = 0;
long bytesUploaded = 0;
for (int i = 0; i < listFile.length; i++) {
Long bytes = listFile[i].length();
totalBytes += bytes;
if (i < mCurrentFileIndex) {
bytesUploaded += bytes;
}
bytesUploaded += progress[0];
int percent = 100;
int percent1 = (int) (percent * (bytesUploaded/totalBytes));
mDialog.setMessage("Uploading file " + (mCurrentFileIndex + 1) + " / " + listFile.length);
mDialog.setProgress(percent1);
}
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(Dropbox.this, msg, Toast.LENGTH_LONG);
error.show();
}
}
public class ListDropboxFiles extends AsyncTask<Void, Void, ArrayList<String>> {
private DropboxAPI<?> dropbox;
private String path;
private Handler handler;
public ListDropboxFiles(DropboxAPI<?> dropbox, String path, Handler handler) {
this.dropbox = dropbox;
this.path = path;
this.handler = handler;
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> files = new ArrayList<String>();
try {
DropboxAPI.Entry directory = dropbox.metadata(path, 1000, null, true, null);
for (DropboxAPI.Entry entry : directory.contents) {
files.add(entry.fileName());
}
} catch (DropboxException e) {
e.printStackTrace();
}
return files;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putStringArrayList("data", result);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
Added from Sample code
private boolean downloadDropboxFile(String dbPath, File localFile) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
FileDownload fd = dropbox.getFileStream("dropbox", dbPath, null);
br = new BufferedInputStream(fd.is);
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);
}
} finally {
//in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
}
>
The error message is indicating that the method definition is:
getFileStream(java.lang.String, java.lang.String)
This is also what the documentation for the getFileStream method in the Dropbox Android Core SDK shows.
However, you're attempting to use three parameters:
(java.lang.String, java.lang.String, null)
So, to properly call the method, you should remove that last parameter (null).
Android: FTP client file transfer in passive mode taking time to close connection after 100% upload
While transferring files through FTP client, in passive mode, we are using async task.
Even after the progress update specified 100% of the file has been uploaded, still ftp connection holds async task from coming to on post execute.
The time taken is directly proportional to Internet speed and size of the file uploaded.
Tried with standalone application to upload zip files,
Tried ftp both in active and passive modes.
Still the issue persists.
public class UploadZipFiles extends AsyncTask<Object, Integer, Object> {
ArrayList<String> zipFiles;
String userName, password;
WeakReference<ServiceStatusListener> listenerReference;
private Context mContext;
private long totalFileSize = 0;
protected long totalTransferedBytes = 0;
final NumberFormat nf = NumberFormat.getInstance();
private CustomFtpClient ftpClient = null;
public UploadZipFiles(Context mContext, ServiceStatusListener listener,
ArrayList<String> zipFiles, String userName, String password) {
Log.d("u and p", "" + userName + "=" + password);
this.mContext = mContext;
this.zipFiles = zipFiles;
this.userName = userName;
this.password = password;
this.listenerReference = new WeakReference<ServiceStatusListener>(
listener);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// getting total size of the file
for (String file : zipFiles) {
totalFileSize = totalFileSize + new File(file).length();
}
}
#Override
protected Object doInBackground(Object... arg0) {
ftpClient = new CustomFtpClient();
try {
ftpClient.connect(ftpUrl, 21);
ftpClient.login(userName, password);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
for (String file : zipFiles) {
InputStream in;
in = new FileInputStream(new File(file));
ftpClient.storeFile(new File(file).getName(), in);
in.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return "Success";
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
listenerReference.get().onFailure(
new Exception(result.toString()));
} else {
listenerReference.get().onSuccess("Success");
}
}
#Override
protected void onProgressUpdate(Integer... values) {
int uploadProgress = ((float) values[0] / totalFileSize) * 100);
//Some code to show loader
.......
}
/** Custom client to publish progress **/
public class CustomFtpClient extends FTPClient {
public boolean storeFile(String remote, InputStream local)
throws IOException {
final OutputStream output;
final Socket socket;
if ((socket = _openDataConnection_(FTPCommand.STOR, remote)) == null)
return false;
output = new BufferedOutputStream(socket.getOutputStream(),
getBufferSize());
try {
Util.copyStream(local, output, getBufferSize(),
CopyStreamEvent.UNKNOWN_STREAM_SIZE,
new CopyStreamListener() {
#Override
public void bytesTransferred(
long totalBytesTransferred,
int bytesTransferred, long streamSize) {
totalTransferedBytes = totalTransferedBytes
+ bytesTransferred;
publishProgress((int) totalTransferedBytes);
if (totalTransferedBytes == totalFileSize) {
Log.d(TAG, "upload completed");
}
}
#Override
public void bytesTransferred(
CopyStreamEvent arg0) {
// TODO Auto-generated method stub
}
});
} catch (IOException e) {
try {
socket.close();
} catch (IOException f) {
}
throw e; }
output.close();
socket.close();
return completePendingCommand();
}
}
}
I am trying to upload a file to dropbox via AsyncTask and I am gett the window leaked error:
05-16 16:05:53.523: E/WindowManager(4528): Activity com.example.wecharades.ShowVideo has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#2be59ea8 that was originally added here
I looked here and understand it is because my activity is exited and the progressdialog is still there. I can't understand why my activity gets exited. it is just a screen with a button to press to upload the file. I am using almost an identical code to download a file from dropbox and it works perfect.
Any suggestions?
thanks in advance!
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
protected final ProgressDialog uDialog;
private long dFileLen;
private String SAVE_PATH;
private String mErrorMsg;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dDBApi=mDBApi;
dContext=context;
SAVE_PATH = path;
uDialog = new ProgressDialog(context);
uDialog.setMax(100);
uDialog.setMessage("Uploading Video Charade");
uDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
uDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(ShowVideo.path);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second
return 500;
}
#Override
public void onProgress(long bytes, long total) {
dFileLen = total;
publishProgress(bytes);
}
});
} 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) {
}
catch (Exception e) {
System.out.println("Something went wrong: " + e);
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
Log.d("TAG", "IOException" + e.getMessage());
}
}
Log.d("ErrorMsg", mErrorMsg);
}
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/dFileLen + 0.5);
uDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
uDialog.dismiss();
super.onPostExecute(result);
Log.d("TAG","UDialog Should be dismissed");
}
}
Here is my Activity class from where i call the UploadFile:
The methods buidSession and clearKeys are not yet used.
public class ShowVideo extends Activity implements OnClickListener {
/** Dropbox Key and AccessType Information*/
final static private String APP_KEY = "XXXXXXXXXXXX";
final static private String APP_SECRET = "XXXXXXXXXXXX";
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";
/**--------------------------------------------------------------*/
private DropboxAPI<AndroidAuthSession> mDBApi;
UploadFile upload;
static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
yesButton.setOnClickListener(this);
noButton.setOnClickListener(this);
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
if(!mDBApi.getSession().isLinked())
mDBApi.getSession().startAuthentication(ShowVideo.this);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
//if(upload.getStatus() == upload.){
//Intent intentHome = new Intent(ShowVideo.this, StartScreen.class);
//startActivity(intentHome);
//}
}
if(v.getId() == R.id.NoButton){
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.d("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
#Override
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) {
showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
Log.i("TAG", "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).
*
* #return Array of [access_key, access_secret], or null if none stored
*/
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;
}
}
/**
* 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 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;
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
}
Try this, in your constructor you dont get the context like this:
dContext=context.getApplicationContext();
but try passing the activity from which you start your asynctask
UploadFile upFile = new UploadFile( ActivityName.this, mDBApi, path);
so in your constructor you have now only:
dContext=context;
call super.onPostExexute(result) after uDialog.dismiss();
#Override
protected void onPostExecute(Boolean result) {
uDialog.dismiss();
Log.d("TAG","UDialog Should be dismissed");
super.onPostExecute(result);
}
EDIT:
ok, I think you should call this code
if(v.getId() == R.id.NoButton){
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.d("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
in the onPostExecute trigger, because it's executed without waiting the AsyncTask to finish. This means you will have to pass the value of the v.getId() so you can achive the same functionality.