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).
Related
I am facing the problem to create a new user on ejabberd server but sign in is working fine. i used the github repository (https://github.com/dilicode/LetsChat) for register the new user and chat between two and more users. I search on intenet, i found some way to register those are:
1.add
%% In-band registration
{access, register, [{allow, all}]}.
in access rules in ejabberd server and
2. also add
{mod_register, [
{access_from, register},
...
] ...
it in access rules of ejabberd server.
my sign up activity as follows:
public class SignupActivity extends AppCompatActivity implements OnClickListener, Listener<Boolean> {
private static final int REQUEST_CODE_SELECT_PICTURE = 1;
private static final int REQUEST_CODE_CROP_IMAGE = 2;
private static final String RAW_PHOTO_FILE_NAME = "camera.png";
private static final String AVATAR_FILE_NAME = "avatar.png";
private EditText nameText;
private EditText phoneNumberText;
private EditText passwordText;
private Button submitButton;
private ImageButton uploadAvatarButton;
private File rawImageFile;
private File avatarImageFile;
private SignupTask signupTask;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
nameText = (EditText)findViewById(R.id.et_name);
phoneNumberText = (EditText)findViewById(R.id.et_phone_number);
passwordText = (EditText)findViewById(R.id.et_password);
uploadAvatarButton = (ImageButton)findViewById(R.id.btn_upload_avatar);
submitButton = (Button)findViewById(R.id.btn_submit);
submitButton.setOnClickListener(this);
uploadAvatarButton.setOnClickListener(this);
File dir = FileUtils.getDiskCacheDir(this, "temp");
if (!dir.exists()) {
dir.mkdirs();
}
rawImageFile = new File(dir, RAW_PHOTO_FILE_NAME);
avatarImageFile = new File(dir, AVATAR_FILE_NAME);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v == submitButton) {
String phoneNumber = phoneNumberText.getText().toString();
String password = passwordText.getText().toString();
String name = nameText.getText().toString();
if (phoneNumber.trim().length() == 0 || password.trim().length() == 0 ||
name.trim().length() == 0) {
Toast.makeText(this, R.string.incomplete_signup_info, Toast.LENGTH_SHORT).show();
return;
}
signupTask = new SignupTask(this, this, phoneNumber, password, name, getAvatarBytes());
signupTask.execute();
} else if(v == uploadAvatarButton) {
chooseAction();
}
}
private void chooseAction() {
Intent captureImageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rawImageFile));
Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(pickIntent, getString(R.string.profile_photo));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {captureImageIntent});
startActivityForResult(chooserIntent, REQUEST_CODE_SELECT_PICTURE);
}
#Override
public void onResponse(Boolean result) {
if (result) {
Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
setResult(RESULT_OK);
finish();
}
}
#Override
public void onErrorResponse(Exception exception) {
Toast.makeText(this, R.string.create_account_error, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_SELECT_PICTURE:
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
startCropImage(Uri.fromFile(rawImageFile));
} else {
startCropImage(data == null ? null : data.getData());
}
break;
case REQUEST_CODE_CROP_IMAGE:
Bitmap bitmap = BitmapFactory.decodeFile(avatarImageFile.getAbsolutePath());
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
drawable.setCircular(true);
uploadAvatarButton.setImageDrawable(drawable);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startCropImage(Uri source) {
if (source != null) {
int size = getResources().getDimensionPixelSize(R.dimen.default_avatar_size);
CropImageIntentBuilder cropImage = new CropImageIntentBuilder(size, size, Uri.fromFile(avatarImageFile));
cropImage.setSourceImage(source);
startActivityForResult(cropImage.getIntent(this), REQUEST_CODE_CROP_IMAGE);
}
}
private byte[] getAvatarBytes() {
if (!avatarImageFile.exists()) return null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(avatarImageFile);
} catch (FileNotFoundException e) {
AppLog.e("avatar file not found", e);
}
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return output.toByteArray();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (signupTask != null) {
signupTask.dismissDialogAndCancel();
}
}
}
SignupTaskActivity as follows:
public class SignupTask extends BaseAsyncTask<Void, Void, Boolean> {
private String user;
private String name;
private String password;
private byte[] avatar;
private ProgressDialog dialog;
public SignupTask(Listener<Boolean> listener, Context context, String user, String password, String name, byte[] avatar) {
super(listener, context);
this.user = user;
this.name = name;
this.password = password;
this.avatar = avatar;
dialog = ProgressDialog.show(context, null, context.getResources().getString(R.string.signup));
}
#Override
public Response<Boolean> doInBackground(Void... params) {
Context context = getContext();
if (context != null) {
try {
SmackHelper.getInstance(context).signupAndLogin(user, password, name, avatar);
if (avatar != null) {
ImageCache.addAvatarToFile(context, user, BitmapFactory.decodeByteArray(avatar, 0, avatar.length));
}
PreferenceUtils.setLoginUser(context, user, password, name);
return Response.success(true);
} catch(SmackInvocationException e) {
AppLog.e(String.format("sign up error %s", e.toString()), e);
return Response.error(e);
}
}
return null;
}
#Override
protected void onPostExecute(Response<Boolean> response) {
dismissDialog();
super.onPostExecute(response);
}
#Override
protected void onCancelled() {
super.onCancelled();
dismissDialog();
}
public void dismissDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void dismissDialogAndCancel() {
dismissDialog();
cancel(false);
}
}
SmackHelper class as follows:
public class SmackHelper {
private static final String LOG_TAG = "SmackHelper";
private static final int PORT = 5222;
public static final String RESOURCE_PART = "Smack";
private XMPPConnection con;
private ConnectionListener connectionListener;
private Context context;
private State state;
private PacketListener messagePacketListener;
private PacketListener presencePacketListener;
private SmackAndroid smackAndroid;
private static SmackHelper instance;
private SmackContactHelper contactHelper;
private SmackVCardHelper vCardHelper;
private FileTransferManager fileTransferManager;
private PingManager pingManager;
private long lastPing = new Date().getTime();
public static final String ACTION_CONNECTION_CHANGED = "com.mstr.letschat.intent.action.CONNECTION_CHANGED";
public static final String EXTRA_NAME_STATE = "com.mstr.letschat.State";
private SmackHelper(Context context) {
this.context = context;
smackAndroid = SmackAndroid.init(context);
messagePacketListener = new MessagePacketListener(context);
presencePacketListener = new PresencePacketListener(context);
SmackConfiguration.setDefaultPacketReplyTimeout(20 * 1000);
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
ProviderManager.addExtensionProvider(UserLocation.ELEMENT_NAME, UserLocation.NAMESPACE, new LocationMessageProvider());
}
public static synchronized SmackHelper getInstance(Context context) {
if (instance == null) {
instance = new SmackHelper(context.getApplicationContext());
}
return instance;
}
public void setState(State state) {
if (this.state != state) {
Log.d(LOG_TAG, "enter state: " + state.name());
this.state = state;
}
}
public void signupAndLogin(String user, String password, String nickname, byte[] avatar) throws SmackInvocationException {
connect();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("name", nickname);
try {
AccountManager.getInstance(con).createAccount(user, password, attributes);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
login(user, password);
vCardHelper.save(nickname, avatar);
}
public void sendChatMessage(String to, String body, PacketExtension packetExtension) throws SmackInvocationException {
Message message = new Message(to, Message.Type.chat);
message.setBody(body);
if (packetExtension != null) {
message.addExtension(packetExtension);
}
try {
con.sendPacket(message);
} catch (NotConnectedException e) {
throw new SmackInvocationException(e);
}
}
public List<RosterEntry> getRosterEntries() {
List<RosterEntry> result = new ArrayList<RosterEntry>();
Roster roster = con.getRoster();
Collection<RosterGroup> groups = roster.getGroups();
for (RosterGroup group : groups) {
result.addAll(group.getEntries());
}
return result;
}
and finally my menifest file
public UserProfile search(String username) throws SmackInvocationException {
String name = StringUtils.parseName(username);
String jid = null;
if (name == null || name.trim().length() == 0) {
jid = username + "#" + con.getServiceName();
} else {
jid = StringUtils.parseBareAddress(username);
}
if (vCardHelper == null) {
return null;
}
VCard vCard = vCardHelper.loadVCard(jid);
String nickname = vCard.getNickName();
return nickname == null ? null : new UserProfile(jid, vCard);
}
public String getNickname(String jid) throws SmackInvocationException {
VCard vCard = vCardHelper.loadVCard(jid);
return vCard.getNickName();
}
private void connect() throws SmackInvocationException {
if (!isConnected()) {
setState(State.CONNECTING);
if (con == null) {
con = createConnection();
}
try {
con.connect();
}catch (SmackException.NoResponseException er){
Log.e(LOG_TAG,"Norespponse exception");
}
catch(Exception e) {
Log.e(LOG_TAG, String.format("Unhandled exception %s", e.toString()), e);
startReconnectIfNecessary();
throw new SmackInvocationException(e);
}
}
}
#SuppressLint("TrulyRandom")
private XMPPConnection createConnection() {
ConnectionConfiguration config = new ConnectionConfiguration(PreferenceUtils.getServerHost(context), PORT);
SSLContext sc = null;
MemorizingTrustManager mtm = null;
try {
mtm = new MemorizingTrustManager(context);
sc = SSLContext.getInstance("TLS");
sc.init(null, new X509TrustManager[] { mtm }, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (KeyManagementException e) {
throw new IllegalStateException(e);
}
config.setCustomSSLContext(sc);
config.setHostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier()));
config.setSecurityMode(SecurityMode.required);
config.setReconnectionAllowed(false);
config.setSendPresence(false);
config.setSecurityMode(SecurityMode.disabled);
List<HostAddress> list = config.getHostAddresses();
boolean data = config.isSendPresence();
return new XMPPTCPConnection(config);
}
public void cleanupConnection() {
if (con != null) {
con.removePacketListener(messagePacketListener);
con.removePacketListener(presencePacketListener);
if (connectionListener != null) {
con.removeConnectionListener(connectionListener);
}
}
if (isConnected()) {
try {
con.disconnect();
} catch (NotConnectedException e) {}
}
}
private void onConnectionEstablished() {
if (state != State.CONNECTED) {
//processOfflineMessages();
try {
con.sendPacket(new Presence(Presence.Type.available));
} catch (NotConnectedException e) {}
contactHelper = new SmackContactHelper(context, con);
vCardHelper = new SmackVCardHelper(context, con);
fileTransferManager = new FileTransferManager(con);
OutgoingFileTransfer.setResponseTimeout(30000);
addFileTransferListener();
pingManager = PingManager.getInstanceFor(con);
pingManager.registerPingFailedListener(new PingFailedListener() {
#Override
public void pingFailed() {
// Note: remember that maybeStartReconnect is called from a different thread (the PingTask) here, it may causes synchronization problems
long now = new Date().getTime();
if (now - lastPing > 30000) {
Log.e(LOG_TAG, "Ping failure, reconnect");
startReconnectIfNecessary();
lastPing = now;
} else {
Log.e(LOG_TAG, "Ping failure reported too early. Skipping this occurrence.");
}
}
});
con.addPacketListener(messagePacketListener, new MessageTypeFilter(Message.Type.chat));
con.addPacketListener(presencePacketListener, new PacketTypeFilter(Presence.class));
con.addConnectionListener(createConnectionListener());
setState(State.CONNECTED);
broadcastState(State.CONNECTED);
MessageService.reconnectCount = 0;
}
}
private void broadcastState(State state) {
Intent intent = new Intent(ACTION_CONNECTION_CHANGED);
intent.putExtra(EXTRA_NAME_STATE, state.toString());
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
public void login(String username, String password) throws SmackInvocationException {
connect();
try {
if (!con.isAuthenticated()) {
con.login(username, password, RESOURCE_PART);
}
onConnectionEstablished();
} catch(Exception e) {
SmackInvocationException exception = new SmackInvocationException(e);
// this is caused by wrong username/password, do not reconnect
if (exception.isCausedBySASLError()) {
cleanupConnection();
} else {
startReconnectIfNecessary();
}
throw exception;
}
}
public String getLoginUserNickname() throws SmackInvocationException {
try {
return AccountManager.getInstance(con).getAccountAttribute("name");
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
private void processOfflineMessages() {
Log.i(LOG_TAG, "Begin retrieval of offline messages from server");
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
try {
if (!offlineMessageManager.supportsFlexibleRetrieval()) {
Log.d(LOG_TAG, "Offline messages not supported");
return;
}
List<Message> msgs = offlineMessageManager.getMessages();
for (Message msg : msgs) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());
context.startService(intent);
}
offlineMessageManager.deleteMessages();
} catch (Exception e) {
Log.e(LOG_TAG, "handle offline messages error ", e);
}
Log.i(LOG_TAG, "End of retrieval of offline messages from server");
}
private ConnectionListener createConnectionListener() {
connectionListener = new ConnectionListener() {
#Override
public void authenticated(XMPPConnection arg0) {}
#Override
public void connected(XMPPConnection arg0) {}
#Override
public void connectionClosed() {
Log.e(LOG_TAG, "connection closed");
}
#Override
public void connectionClosedOnError(Exception arg0) {
// it may be due to network is not available or server is down, update state to WAITING_TO_CONNECT
// and schedule an automatic reconnect
Log.e(LOG_TAG, "connection closed due to error ", arg0);
startReconnectIfNecessary();
}
#Override
public void reconnectingIn(int arg0) {}
#Override
public void reconnectionFailed(Exception arg0) {}
#Override
public void reconnectionSuccessful() {}
};
return connectionListener;
}
private void startReconnectIfNecessary() {
cleanupConnection();
setState(State.WAITING_TO_CONNECT);
if (NetworkUtils.isNetworkConnected(context)) {
context.startService(new Intent(MessageService.ACTION_RECONNECT, null, context, MessageService.class));
}
}
private boolean isConnected() {
return con != null && con.isConnected();
}
public void onNetworkDisconnected() {
setState(State.WAITING_FOR_NETWORK);
}
public void requestSubscription(String to, String nickname) throws SmackInvocationException {
contactHelper.requestSubscription(to, nickname);
}
public void approveSubscription(String to, String nickname, boolean shouldRequest) throws SmackInvocationException {
contactHelper.approveSubscription(to);
if (shouldRequest) {
requestSubscription(to, nickname);
}
}
public void delete(String jid) throws SmackInvocationException {
contactHelper.delete(jid);
}
public String loadStatus() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadStatus();
}
public VCard loadVCard(String jid) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard(jid);
}
public VCard loadVCard() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard();
}
public void saveStatus(String status) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
vCardHelper.saveStatus(status);
contactHelper.broadcastStatus(status);
}
public SubscribeInfo processSubscribe(String from) throws SmackInvocationException {
SubscribeInfo result = new SubscribeInfo();
RosterEntry rosterEntry = contactHelper.getRosterEntry(from);
ItemType rosterType = rosterEntry != null ? rosterEntry.getType() : null;
if (rosterEntry == null || rosterType == ItemType.none) {
result.setType(SubscribeInfo.TYPE_WAIT_FOR_APPROVAL);
result.setNickname(getNickname(from));
} else if (rosterType == ItemType.to) {
result.setType(SubscribeInfo.TYPE_APPROVED);
result.setNickname(rosterEntry.getName());
approveSubscription(from, null, false);
}
result.setFrom(from);
return result;
}
public void sendImage(File file, String to) throws SmackInvocationException {
if (fileTransferManager == null || !isConnected()) {
throw new SmackInvocationException("server not connected");
}
String fullJid = to + "/" + RESOURCE_PART;
OutgoingFileTransfer transfer = fileTransferManager.createOutgoingFileTransfer(fullJid);
try {
transfer.sendFile(file, file.getName());
} catch (SmackException e) {
Log.e(LOG_TAG, "send file error");
throw new SmackInvocationException(e);
}
while(!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
Log.d(LOG_TAG, "send file status: " + transfer.getStatus());
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
private void addFileTransferListener() {
fileTransferManager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
new Thread() {
#Override
public void run() {
IncomingFileTransfer transfer = request.accept();
String fileName = String.valueOf(System.currentTimeMillis());
File file = new File(FileUtils.getReceivedImagesDir(context), fileName + FileUtils.IMAGE_EXTENSION);
try {
transfer.recieveFile(file);
} catch (SmackException e) {
Log.e(LOG_TAG, "receive file error", e);
return;
}
while (!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
Log.e(LOG_TAG, "receive file error, " + transfer.getError());
return;
}
}
// start service to save the image to sqlite
if (transfer.getStatus().equals(Status.complete)) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(request.getRequestor()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, context.getString(R.string.image_message_body));
intent.putExtra(MessageService.EXTRA_DATA_NAME_FILE_PATH, file.getAbsolutePath());
intent.putExtra(MessageService.EXTRA_DATA_NAME_TYPE, ChatMessageTableHelper.TYPE_INCOMING_IMAGE);
context.startService(intent);
}
}
}.start();
}
});
}
public void onDestroy() {
cleanupConnection();
smackAndroid.onDestroy();
}
public static enum State {
CONNECTING,
CONNECTED,
DISCONNECTED,
// this is a state that client is trying to reconnect to server
WAITING_TO_CONNECT,
WAITING_FOR_NETWORK;
}
}
but i could not found any progress.please help me out. thanks in advance.
After struggle i found solution of this kind of problem. we need to do server side changes like:
step1:
step2:
step3:
after doing all these steps we will able to register new user on ejabberd server.
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
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(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, 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) {
CurrentURL = getLastAccessedBrowserPage();
// 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");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#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
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
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]);
}
//}
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 = spdappliationcontext.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;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}
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();
In my android application, there is a app file at the sd card, and the same in our server, but the data in the server may be updated.
So I make an activity to check if latest data is avaiable.
This is an example, there is only one button "Check", when user hit this button, I will get the information of the local data, and then reqest to the server to check if it can be udpated.(THis is done by the CheckTask and a progress dialog will show up during the checking).
Then if a update is requred, I will provide a Dialog to tell the user, they can choose "Download Now" or "Download Later", if they choose "Download Now", a DownLoadTask will be executed,and a new ProgressDialog will be created to show the progress of the download.
Now I meet a problem:
Everything works well unless user click the "Download Now" and then cancel the download.
Then when user click the "Check" button, the CheckTask will not work normally.
This is the codes:
public class MyActivity extends Activity {
private DecimalFormat format = new DecimalFormat("0.#");
private final int Dialog_Offline_Check_HaveUpdate = 13;
private final int Dialog_Offline_Download = 14;
private CheckTask mCheckTask;
private ProgressDialog mCheckProgressDialog;
private DownloadTask mDownloadTask;
private ProgressDialog mDownloadProgressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setupView();
}
private void setupView() {
mCheckProgressDialog = new ProgressDialog(this);
mCheckProgressDialog.setCanceledOnTouchOutside(false);
findViewById(R.id.check).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startCheckTask();
}
});
}
private void startCheckTask() {
if (mDownloadTask != null && !mDownloadTask.isCancelled()) {
showDialog(Dialog_Offline_Download);
} else {
//for debug
String data = String.format("{\"name\":\"%s\",\"size\":123455,\"lastModifiedTime\":\"2014-1-1\",\"hasUpdate\":false}", "Old Data");
AppData appData = null;
try {
appData = buildMapData(data);
} catch (JSONException e) {
e.printStackTrace();
}
if (mCheckTask != null) mCheckTask.cancel(true);
mCheckTask = new CheckTask();
mCheckTask.execute(String.format("http://xxxx?t=%s", appData.lastModifiedTime));
}
}
private void startDownLoadTask() {
if (mDownloadTask != null) {
mDownloadTask.cancel(true);
}
mDownloadTask = new DownloadTask();
mDownloadTask.execute("https://dl.google.com/android/adt/adt-bundle-windows-x86-20131030.zip"); //for debug
showDialog(Dialog_Offline_Download);
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) {
case Dialog_Offline_Check_HaveUpdate:
builder.setTitle("Check Update").setPositiveButton("Download Now", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
startDownLoadTask();
}
}).setNegativeButton("Download Later", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}).setMessage("Latest Data avaiable!");
return builder.create();
case Dialog_Offline_Download:
mDownloadProgressDialog = new ProgressDialog(this);
mDownloadProgressDialog.setTitle("Download Latest Data");
mDownloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDownloadProgressDialog.setMax(100);
mDownloadProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Do it in Background", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
mDownloadProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (mDownloadTask != null)
mDownloadTask.cancel(true);
}
});
mDownloadProgressDialog.setMessage("");
return mDownloadProgressDialog;
}
return null;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
switch (id) {
case Dialog_Offline_Check_HaveUpdate:
String msgg;
AppData appData1 = (AppData) args.getSerializable("data");
if (appData1 != null) {
msgg = String.format("%s\n%s: %s \n%s: %s\n%s: %s", "New Data Avaiable",
"Name", appData1.name,
"Size", makeFileSizeReadable(appData1.size),
"Last Update Time", appData1.lastModifiedTime);
} else {
msgg = "";
}
((AlertDialog) dialog).setMessage(msgg);
break;
}
}
private String makeFileSizeReadable(long size) {
double value;
String unit;
if (size < 1024) {
// < 1k
value = size;
unit = "Byte";
} else if (size < 1024 * 1024) {
// 1k,1M
value = size / 1024d;
unit = "Kb";
} else {
value = size / 1024d / 1024d;
unit = "Mb";
}
return String.format("%s %s", format.format(value), unit);
}
class CheckTask extends AsyncTask<String, Void, AppData> {
private String errorMsg;
private boolean cancel = false;
#Override
protected AppData doInBackground(String... urls) {
String url = urls[0];
//for debug
String response = String.format("{\"name\":\"%s\",\"size\":222222,\"lastModifiedTime\":\"2014-1-5\",\"hasUpdate\":true}", "New Data");
Log.d("map.setting", String.format("start parse result: [%s]", response));
AppData md = null;
try {
md = buildMapData(response);
} catch (JSONException e) {
e.printStackTrace();
Log.e("map.setting", "error when parse:" + e.getMessage());
}
Log.d("map.setting", "get md:" + md);
return md;
}
#Override
protected void onPreExecute() {
mCheckProgressDialog.setMessage("Checking...");
mCheckProgressDialog.show();
}
#Override
protected void onPostExecute(AppData appData) {
mCheckProgressDialog.dismiss();
if (appData == null) {
return;
}
if (appData.hasUpdate) {
Bundle bd = new Bundle();
bd.putSerializable("data", appData);
showDialog(Dialog_Offline_Check_HaveUpdate, bd);
} else {
Toast.makeText(MyActivity.this, "Your data is the latest!", Toast.LENGTH_SHORT).show();
}
}
}
private AppData buildMapData(String response) throws JSONException {
JSONObject root = new JSONObject(response);
String name = root.getString("name");
long size = root.getLong("size");
String lastModifiedTime = root.getString("lastModifiedTime");
boolean hasUpdate = root.getBoolean("hasUpdate");
AppData md = new AppData();
md.name = name;
md.lastModifiedTime = lastModifiedTime;
md.size = size;
md.hasUpdate = hasUpdate;
return md;
}
class DownloadTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/tmp.data", false);
byte data[] = new byte[4096];
int total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0)
publishProgress(total * 100 / fileLength, total, fileLength);
output.write(data, 0, count);
}
} catch (Exception e) {
return null;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
} finally {
// wl.release();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
//progress current total
if (mDownloadProgressDialog != null) {
mDownloadProgressDialog.setProgress(values[0]);
String msg = String.format("Progress:%s/%s", makeFileSizeReadable(values[1]), makeFileSizeReadable(values[2]));
mDownloadProgressDialog.setMessage(msg);
}
}
#Override
protected void onPostExecute(String res) {
//map file downloaded replace the old file
}
#Override
protected void onCancelled() {
super.onCancelled();
}
}
}
class AppData implements Serializable {
public String name;
public String lastModifiedTime;
public long size;
public boolean hasUpdate;
}
Anyone can find what is the problem?
Is that you encounter AsynTask's bug after HONEYCOMB?
Order of execution
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
In our project we use AsynTask like this:
public void executeParallelly(Params... params) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
task.execute(params);
} else {
task.executeOnExecutor(AsynTask.THREAD_POOL_EXECUTOR, params);
}
}
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.