Make Toast for display the name of downloaded files - android

i have an FTP connection which is working fine , i can download my files using a fragment which call > an asynctaskt which call > the FTP server
public static void downloadDirectory(FTPClient ftpClient, String parentDir,
String currentDir, String saveDir) throws IOException {
String dirToList = parentDir;
if (!currentDir.equals("")) {
dirToList += "/" + currentDir;
}
FTPFile[] subFiles = ftpClient.listFiles(dirToList);
if (subFiles != null && subFiles.length > 0) {
for (FTPFile aFile : subFiles) {
String currentFileName = aFile.getName();
if (currentFileName.equals(".") || currentFileName.equals("..")) {
// skip parent directory and the directory itself
continue;
}
String filePath = parentDir + "/" + currentDir + "/"
+ currentFileName;
if (currentDir.equals("")) {
filePath = parentDir + "/" + currentFileName;
}
String newDirPath = saveDir + parentDir + File.separator
+ currentDir + File.separator + currentFileName;
if (currentDir.equals("")) {
newDirPath = saveDir + parentDir + File.separator
+ currentFileName;
}
if (aFile.isDirectory()) {
// create the directory in saveDir
File newDir = new File(newDirPath);
boolean created = newDir.mkdirs();
if (created) {
System.out.println("CREATED the directory: "
+ newDirPath);
} else {
System.out.println("COULD NOT create the directory: "
+ newDirPath);
}
// download the sub directory
downloadDirectory(ftpClient, dirToList, currentFileName,
saveDir);
} else {
// download the file
boolean success = downloadSingleFile(ftpClient, filePath,
newDirPath);
if (success) {
System.out.println("DOWNLOADED the file: " + filePath);
} else {
System.out.println("COULD NOT download the file: "
+ filePath);
}
}
}
try {
Log.v("LogoutInformation", "Logout from FTP");
ftpClient.logout();
} catch (Exception e) {
Log.e("LogoutInformation", "Logout Fail");
}
try {
Log.v("DisconnectInformation", "Disconnect from FTP");
ftpClient.disconnect();
} catch (Exception e) {
Log.e("DisconnectInformation", "Disconnect Fail");
}
}
Here my function from FTPserver.
System.out.println("DOWNLOADED the file: " + filePath);
And this is what I want to show on my fragment , i want to make a toast which display the file which is actually in download.
But it's background processing , so i can't display information on my fragment , so i don't know how i can do it.

As from tags, you are using AsyncTask. Modify it's constructor to accept a reference to context.
public class MyAsyncTask extends AsyncTask<..> {
private Context mContext;
public MyAsyncTask(Context c){
this.mContext = c;
}
...
When your task is running in doInBackground, you should publishProgress(String):
doInBackground(String.. params){
for(something){
...
publishProgress(fileName);
}
}
publishProgress(String fName){
Toast.makeText(mContext, name, Toast.Length_long).show();
}

You only need to do this.
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context,"Your text", Toast.LENGTH_LONG).show();
}
});

Are you calling the downloadDirectory in the doInBackground event of the AsyncTask class?
If so, you can make Toast message like so:
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getActivity(),"DOWNLOADED the file: "+filePath,Toast.LENGTH_SHORT).show();
}
Where you make filePath global variable.
Something like that. Hope it helps..

Try to use:
Toast.makeText(getActivity(), "File Downloaded:"+currentFileName, Toast.LENGTH_LONG).show()

Related

OSMdroid : How to render offline map from a local sqlite archive

Programming with Android Studio and the osmdroid library.
I downloaded a portion of a map using the cacheManager.downloadAreaAsync() method. This method stores the map piece in a sqlite file in the data/data/<package>/osmdroid/tiles directory, chosen by me.
Now I want to use this map to load it offline in a mobile application.
I've tried to do it through all kinds of classes (MapTileSqlCacheProvider, XYTileSource, OfflineTileProvider, ...) but I can't get the map to appear.
How should I do it?
To download a portion of the map I do this:
map.setTileSource(TileSourceFactory.OpenTopo);
outputPath = "/data/data/<package>/files" + File.separator + "osmdroid" + File.separator + "tiles" + File.separator;
outputName = outputPath + boxE6.name + ".db";
try {
writer=new SqliteArchiveTileWriter(outputName);
} catch (Exception ex) {
ex.printStackTrace();
}
CacheManager cacheManager = new CacheManager(map,writer);
cacheManager.downloadAreaAsync(this, boxE6, 7, 13, new CacheManager.CacheManagerCallback() {
#Override
public void onTaskComplete() {
Toast.makeText(ctx, "Download complete!", Toast.LENGTH_LONG).show();
if (writer!=null)
writer.onDetach();
} ...
To retrieve the stored map (in this case it is in the usa.db file) I try to do this:
map.setUseDataConnection(false);
map.setTileSource(TileSourceFactory.OpenTopo);
File cache = new File(outputName);
Configuration.getInstance().setOsmdroidTileCache(cache);
mapController.setCenter(new GeoPoint((n+s)/2,(e+w)/2));
I will show how I store and load multiple sqlite Tiles, not just one.
The above answer from José Espejo Roig worked only partly for me. It worked almost fine for caching the tiles, but not for reading them. Writing down cache files though is also not complete. I have created my own code using as example: Make a tile archive from OSMDroid Github.
So to store potentially more than 1 tiles in a specific directory I use a code like below. It creates sequentially my_mapX.sqlite, where X are just stepped consecutive integers. So I get my_map1.sqlite, my_map2.sqlite and so on.
private final String MAP_FILE_NAME = "my_map";
private final String MAP_FILE_EXTENSION = ".sqlite";
// ...
Context ctx = getActivity();
mMapView = new MapView(ctx);
((ConstraintLayout) view.findViewById(R.id.osm_fragment)).addView(mMapView);
mMapView.setTileSource(TileSourceFactory.OpenTopo);
ContextWrapper contextWrapper = new ContextWrapper(ctx);
File root_directory = contextWrapper.getDir(ctx.getFilesDir().getName(), Context.MODE_PRIVATE);
File directory_osm = new File(root_directory, "osmdroid");
directory_osm.mkdir();
File directory = new File(directory_osm, "tiles");
directory.mkdir();
File[] nrFiles = directory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
if (name.endsWith(MAP_FILE_EXTENSION))
return true;
return false;
}
});
String osmdroidTile = directory.getAbsolutePath() + File.separator + MAP_FILE_NAME + (nrFiles.length + 1) + MAP_FILE_EXTENSION;
BoundingBox boxE6 = mMapView.getBoundingBox();
SqliteArchiveTileWriter writer = null;
try {
writer = new SqliteArchiveTileWriter(osmdroidTile);
} catch (Exception ex) {
ex.printStackTrace();
}
CacheManager cacheManager = new CacheManager(mMapView, writer);
SqliteArchiveTileWriter finalWriter = writer;
int currZoom = (int)mMapView.getZoomLevelDouble();
cacheManager.downloadAreaAsync(ctx, boxE6, currZoom, currZoom + 1, new CacheManager.CacheManagerCallback() {
#Override
public void onTaskComplete() {
Toast.makeText(ctx, "Download complete!", Toast.LENGTH_LONG).show();
if (finalWriter != null)
finalWriter.onDetach();
}
#Override
public void updateProgress(int progress, int currentZoomLevel, int zoomMin, int zoomMax) {
}
#Override
public void downloadStarted() {
}
#Override
public void setPossibleTilesInArea(int total) {
}
#Override
public void onTaskFailed(int errors) {
Toast.makeText(getActivity(), "Download complete with " + errors + " errors", Toast.LENGTH_LONG).show();
if (finalWriter != null)
finalWriter.onDetach();
}
});
}
});
This way I can create as many tile files as I want. Important is that they have ".sqlite" extension. ".db" extension didn't work for me.
Now to read these tiles I used again example from OSMDroid Github: Sample SQLITE example. In OSMDroid Github example TileSource is being determined with IArchiveFile. I skipped that, as I assume I know what TileSource I used (in my case it is OpenTopo, as you can see). Then to read multiple offline tiles from the same TileSource (basing on example from OSMDroid) my code looks like this:
//first we'll look at the default location for tiles that we support
Context ctx = getActivity();
mMapView = new MapView(ctx);
((ConstraintLayout) view.findViewById(R.id.osm_fragment)).addView(mMapView);
mMapView.setUseDataConnection(false);
ContextWrapper contextWrapper = new ContextWrapper(ctx);
File root_directory = contextWrapper.getDir(ctx.getFilesDir().getName(), Context.MODE_PRIVATE);
String osmDir = root_directory.getAbsolutePath() + File.separator + "osmdroid" + File.separator + "tiles";
File f = new File(osmDir);
if (f.exists()) {
File[] list = f.listFiles();
ArrayList<File> sqliteArray = new ArrayList<>();
if (list != null) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
continue;
}
String name = list[i].getName().toLowerCase();
if (!name.contains(".")) {
continue; //skip files without an extension
}
name = name.substring(name.lastIndexOf(".") + 1);
if (name.length() == 0) {
continue;
}
//narrow it down to only sqlite tiles
if (ArchiveFileFactory.isFileExtensionRegistered(name) && name.equals("sqlite")) {
sqliteArray.add(list[i]);
}
}
}
OfflineTileProvider tileProvider;
if (sqliteArray.size() > 0) {
try {
tileProvider = new OfflineTileProvider(new SimpleRegisterReceiver(getActivity()), sqliteArray.toArray(new File[0]));
mMapView.setTileProvider(tileProvider);
mMapView.setTileSource(TileSourceFactory.OpenTopo);
mMapView.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(getActivity(), f.getAbsolutePath() + " dir not found!", Toast.LENGTH_SHORT).show();
}

application crash when try to load System.loadLibrary("loader-jni")

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.forsale.forsale-2/base.apk"],nativeLibraryDirectories=[/data/app/com.forsale.forsale-2/lib/arm64, /data/app/com.forsale.forsale-2/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]] couldn't find "libloader-jni.so"
at java.lang.Runtime.loadLibrary0(Runtime.java:972)
at java.lang.System.loadLibrary(System.java:1567)
at com.netcompss.loader.LoadJNI.<clinit>(LoadJNI.java:15)
at com.forsale.app.utils.facades.VideoCompressor$getCompressedVideo$retValue$1.invokeSuspend(VideoCompressor.kt:21)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:236)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
I am getting the crash above when try to run my code
fun getCompressVideo (video: String) {
launch (Dispatchers.Main){
viewModel.mediaViewModel.video = videoCompressor.getCompressedVideo(context, Uri.parse(viewModel.mediaViewModel.video))
}
}
override suspend fun getCompressedVideo(context: Context?, video: Uri): String {
val retValue = withContext(Dispatchers.IO) {
val inputFile = video.path
Log.i("AMIRA3000" , inputFile)
val loadJNI = LoadJNI()
val workFolder: String = context!!.filesDir.absolutePath
val outputFile: String = getFileFullName(
FilesConstants.VIDEO_FOLDER,
String.format(FilesConstants.VIDEO_NAME_FILE_FORMAT, System.currentTimeMillis())
)
val complexCommand = arrayOf(
"ffmpeg", "-y", "-i", inputFile, "-strict", "experimental", "-s", "320x240", "-r", "25", "-aspect", "4:3", "-ab", "48000", "-ac", "2", "-vcodec", "mpeg4", "-movflags", "+faststart", "-ar", "22050", "-b", "2097k", outputFile
)
loadJNI.run(complexCommand, workFolder, context)
}
return retValue.toString()
}
EDIT
public final class LoadJNI {
static {
System.loadLibrary("loader-jni");
}
/**
*
* #param args ffmpeg command
* #param workFolder working directory
* #param ctx Android context
* #param isValidate apply validation to the command
* #throws CommandValidationException
*/
public void run(String[] args, String workFolder, Context ctx, boolean isValidate) throws CommandValidationException {
Log.i(Prefs.TAG, "running ffmpeg4android_lib: " + Prefs.version);
// delete previous log: this is essential for correct progress calculation
String vkLogPath = workFolder + "vk.log";
GeneralUtils.deleteFileUtil(vkLogPath);
GeneralUtils.printCommand(args);
//printInternalDirStructure(ctx);
if (isValidate) {
if (GeneralUtils.isValidCommand(args))
load(args, workFolder, getVideokitLibPath(ctx), true);
else
throw new CommandValidationException();
}
else {
load(args, workFolder, getVideokitLibPath(ctx), true);
}
}
/**
*
* #param args ffmpeg command
* #param videokitSdcardPath working directory
* #param ctx Android context
* #throws CommandValidationException
*/
public void run(String[] args, String workFolder, Context ctx) throws CommandValidationException {
run(args, workFolder, ctx, true);
}
private static void printInternalDirStructure(Context ctx) {
Log.d(Prefs.TAG, "=printInternalDirStructure=");
Log.d(Prefs.TAG, "==============================");
File file = new File(ctx.getFilesDir().getParent());
analyzeDir(file);
Log.d(Prefs.TAG, "==============================");
}
private static void analyzeDir(File path) {
if (path.isDirectory()) {
Log.d(Prefs.TAG,"Scanning dir: " + path.getAbsolutePath());
File[] files1 = path.listFiles();
for (int i = 0; i < files1.length; i++) {
analyzeDir(files1[i]);
}
Log.d(Prefs.TAG, "==========");
}
else {
Log.d(Prefs.TAG, path.getAbsolutePath());
}
}
private static String getVideokitLibPath(Context ctx) {
//File file = new File(ctx.getFilesDir().getParent() + "/lib/");
//analyzeDir(file);
String videokitLibPath = ctx.getFilesDir().getParent() + "/lib/libvideokit.so";
File file = new File(videokitLibPath);
if(file.exists()) {
Log.i(Prefs.TAG, "videokitLibPath exits: " + videokitLibPath);
}
else {
Log.w(Prefs.TAG, "videokitLibPath not exits: " + videokitLibPath);
videokitLibPath = ctx.getFilesDir().getParent() + "/lib/arm64/libvideokit.so";
Log.i(Prefs.TAG, "trying videokitLibPath: " + videokitLibPath);
file = new File(videokitLibPath);
if(file.exists()) {
Log.i(Prefs.TAG, "videokitLibPath exits: " + videokitLibPath);
}
else {
Log.w(Prefs.TAG, "videokitLibPath not exits: " + videokitLibPath);
videokitLibPath = "/data/app/com.examples.ffmpeg4android_demo-1/lib/arm64/libvideokit.so";
Log.i(Prefs.TAG, "trying videokitLibPath: " + videokitLibPath);
file = new File(videokitLibPath);
if(file.exists()) {
Log.i(Prefs.TAG, "videokitLibPath exits: " + videokitLibPath);
}
else {
Log.w(Prefs.TAG, "videokitLibPath not exits: " + videokitLibPath);
videokitLibPath = "/data/app/com.examples.ffmpeg4android_demo-2/lib/arm64/libvideokit.so";
Log.i(Prefs.TAG, "trying videokitLibPath: " + videokitLibPath);
if(file.exists()) {
Log.i(Prefs.TAG, "videokitLibPath exits: " + videokitLibPath);
}
else {
Log.e(Prefs.TAG, "can't find path of lib");
}
}
}
}
//String videokitLibPath = ctx.getFilesDir().getParent() + "/lib/arm64/libvideokit.so";
// only this works on Android M, and the number changes (demo-2, demo-1)
//String videokitLibPath = "/data/app/com.examples.ffmpeg4android_demo-1/lib/arm64/libvideokit.so";
Log.i(Prefs.TAG, "videokitLibPath: " + videokitLibPath);
return videokitLibPath;
}
public void fExit( Context ctx) {
fexit(getVideokitLibPath(ctx));
}
public native String fexit(String videokitLibPath);
public native String unload();
public native String load(String[] args, String videokitSdcardPath, String videokitLibPath, boolean isComplex);
}
the file is found in the library
I know it's late to answer this question but may help someone who is looking for it.
I was also getting the same error and was working on it for couple of days.
i had tried all the possible answers but still was not able to solve them.I was using an old project in which jniLibs was already present but still i was getting the same error. After a lot of research i got my answer and it worked. this is the link which i followed:
http://androidwarzone.blogspot.com/2011/12/ffmpeg4android.html
only three things i had to do:
Add this line to your app gradle.build:
implementation 'com.netcompss:ffmpeg4android_lib:41.08'
Add this to your gradle.properties:
android.useDeprecatedNdk=true
Add this in the application tag in manifest file:
android:extractNativeLibs="true"
I hope it may help someone: Good Luck.

AndroidTv, Adding channels from an XML issue(samleTvApp)

I'm having this issue with Android TV (sampleApp).
I'm inputting streaming channels from a xml file. I'm creating a temp file to be used at the start, and then I have created a button that does all the necessary functions to acquire data from the server and create the NEW xml file from that data. All of this works, but there's one issues:
After pressing the button and file is created, I try to add channels by pressing "add channels" button, but the file that is used is the temp file, not the NEW xml file. So that it uses the NEW xml file, I have to re-run the setup again and then it works flawlesly. It seems like it caches the temp file in memory or something and uses it first when adding channels, because when the app is launched there is no internal storage file (this is where i save my NEW xml file), the file is created only after the button press.
How do I make it so it uses the NEW xml file instead of the temp file(that created during app launch)?, instead of doing a re-setup
This is the method that is used. Basically, on the first launch it creates an xml with no channels or programs(the temp file) and does what it has to. Then using my other class I create a NEW xml file with all the channels and programs. That also works, the file exists and it goes to the else statement after I press the "add Channels" button. But regardless, on the first try after pressing the button it always adds the temp file, rather than the new one. The new one is only runned, if I launch the setup again.
public static XmlTvParser.TvListing getRichTvListings(Context context) {
context1 = context;
FileOutputStream fos;
try {
Boolean exists = context.getFileStreamPath(FILENAME).exists();
if (exists == false){
String string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<!DOCTYPE tv SYSTEM \"xmltv.dtd\">\n" +
"\n" +
"<tv>\n" +
"</tv>";
Log.d(TAG,"Exists: FALSE");
fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
read = "file:" + context.getFilesDir().toString() + "/" + FILENAME ;
Uri catalogUri =Uri.parse(read);
if (sSampleTvListing != null) {
return sSampleTvListing;
}
try (InputStream inputStream = getInputStream(context, catalogUri)) {
sSampleTvListing = XmlTvParser.parse(inputStream);
} catch (IOException e) {
Log.e(TAG, "Error in fetching " + catalogUri, e);
}
}
else{
Log.d(TAG,"Exists: TRUE");
FileInputStream fis = context.openFileInput(FILENAME2);
StringBuilder builder = new StringBuilder();
int inputChar;
while((inputChar = fis.read()) != -1) {
builder.append((char) inputChar);
}
String readFile = builder.toString();
Log.d(TAG, "FileContent: " + readFile);
read = "file:" + context.getFilesDir().toString() + "/" + FILENAME2 ;
Uri catalogUri =Uri.parse(read);
if (sSampleTvListing != null) {
return sSampleTvListing;
}
try (InputStream inputStream = getInputStream(context, catalogUri)) {
sSampleTvListing = XmlTvParser.parse(inputStream);
} catch (IOException e) {
Log.e(TAG, "Error in fetching " + catalogUri, e);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sSampleTvListing;
}
The the button functionalities are in my richSetupFragment class(I wont post all of it, but these are the part that I think are most important in this case):
#Override
protected Boolean doInBackground(Uri... params) {
mTvListing = RichFeedUtil.getRichTvListings(getActivity());
mPoster = fetchPoster();
return true;
}
#Override
public void onActionClicked(Action action) {
if (action.getId() == ACTION_ADD_CHANNELS) {
setupChannels(mInputId);
} else if (action.getId() == ACTION_CANCEL) {
getActivity().finish();
}
else if (action.getId() == RETRIEVE_DATA) {
getChannelsFromServer();
// Log.d(TAG,"List: " + list);
}
private void setupChannels(String inputId) {
inputIdLocal= inputId;
if (mTvListing == null) {
onError(R.string.feed_error_message);
return;
}
TvContractUtils.updateChannels(getActivity(), inputId, mTvListing.channels);
SyncUtils.setUpPeriodicSync(getActivity(), inputId);
SyncUtils.requestSync(inputId, true);
mSyncRequested = true;
// Watch for sync state changes
if (mSyncObserverHandle == null) {
final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask,
mSyncStatusObserver);
}
}

android aws error code bucket already owned by you

I have an android application, which function is to upload image to AWS(Amazon Web Service) S3. When I first time run this app image upload successfully. But when I upload image second time, I am getting following error. How can I fix this error?
Here is the error:
Here is my activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActionBar().setDisplayShowTitleEnabled(false);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
s3Client.setRegion(Region.getRegion(Regions.US_WEST_2));
setContentView(R.layout.submit);
submit = (Button) findViewById(R.id.buttonsubmit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri selectedImage = Uri.parse(Environment
.getExternalStorageDirectory().getPath()
+ File.separator
+ "Pictures"
+ File.separator
+ "Spike" + File.separator + "cubicasa.jpg");
new S3PutObjectTask().execute(selectedImage);
}
});
}
private class S3PutObjectTask extends AsyncTask<Uri, Void, S3TaskResult> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(SubmitActivity.this);
dialog.setMessage(SubmitActivity.this.getString(R.string.uploading));
dialog.setCancelable(false);
dialog.show();
}
protected S3TaskResult doInBackground(Uri... uris) {
if (uris == null || uris.length != 1) {
return null;
}
// The file location of the image selected.
String filepath = Environment.getExternalStorageDirectory()
.toString()
+ File.separator
+ "Pictures"
+ File.separator
+ "Spike" + File.separator + "cubicasa.jpg";
Uri selectedImage = Uri.fromFile(new File(filepath));
// Uri selectedImage =
// Uri.parse("content://media/external/images/media/40894");
String URLLLLLLLLL = selectedImage.toString();
Log.e("uRLLLLLLLLLLLLLL", URLLLLLLLLL);
ContentResolver resolver = getContentResolver();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(resolver.getType(selectedImage));
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
s3Client.createBucket(Constants.getPictureBucket());
PutObjectRequest por = new PutObjectRequest(
Constants.getPictureBucket(), Constants.PICTURE_NAME,
resolver.openInputStream(selectedImage), metadata);
s3Client.putObject(por);
} catch (Exception exception) {
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
dialog.dismiss();
if (result.getErrorMessage() != null) {
displayErrorAlert(
SubmitActivity.this
.getString(R.string.upload_failure_title),
result.getErrorMessage());
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Uploaded Successfully", Toast.LENGTH_SHORT);
toast.show();
}
}
}
Here is my constantclass:
public class Constants {
public static final String ACCESS_KEY_ID = "accesskey";
public static final String SECRET_KEY = "secretkey";
public static final String PICTURE_BUCKET = "picture-bucket5";
public static final String PICTURE_NAME = "NameOfThePicture5";
public static String getPictureBucket() {
return ("bd.dse.test" + ACCESS_KEY_ID + PICTURE_BUCKET).toLowerCase(Locale.US);
}
Any help will be greatly appreciated. Thanks in advance.
From your code : your are creating bucket every time, don't do like that that will cause duplicate of bucket. create bucket once with name (string) like this below code.
s3Client.createBucket("images");
from next time on wards don't call this creating bucket in your code, just put images in that bucket like this following code.
S3.createObjectForBucket("images", Token, _Image);

The method startActivity(Intent) is undefined for the type MyFileObserver

I am trying to start an activity, when a file is inserted into sdcard. For that, I want to start a helloworld.java activity(dummy one). I am getting 'undefined' error at startActivity() method. The Eclipse highlights the error code code with red underline. I have registered both the classes in manifest file. So no problem in manifest file.
public class MyFileObserver extends FileObserver {
public static final String PREFS_NAME = "MyPreferencesFile";
public static String absolutePath;
//final adapter info = new adapter(this);
HashSet<ObserverActivity> registeredObservers;
FileEvent fileevent = new FileEvent();
final filehelper f_help = new filehelper(fileevent);
private Context context;
public MyFileObserver(Context context) {
super(absolutePath);
this.context = context;
}
public MyFileObserver(String path) {
super(path, FileObserver.ALL_EVENTS);
//this.fileevent = fileevent;
absolutePath = path;
registeredObservers = new HashSet<ObserverActivity>();
}
public void registerObserver(ObserverActivity toRegister){
registeredObservers.add(toRegister);
}
public void unregisterObserver(ObserverActivity toUnregister){
registeredObservers.remove(toUnregister);
}
#Override
public void onEvent(int event, String path) {
// try{
if (path == null)
{
return;
}
/*for(ObserverActivity o: registeredObservers){
o.onFileObserved(event, path);
}*/
//a new file or subdirectory was created under the monitored directory
if ((FileObserver.CREATE & event)!=0) {
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + path + " is created\n";
Log.v(path+ " in FileObserver of sample_fileobserver ====>>>> ",path);
// setpath(path);
//fileevent.insert(path);
/*for(ObserverActivity o: registeredObservers){
o.onFileObserved(event, path);
}*///try
// {
FileEvent.path2 = path;
Intent i = new Intent("com.example.sample_fileobserver.hello");
startActivity(i);
// startAct();
// fileevent.insert(path);
// }
//catch(Exception e)
//{
// Log.v("Activity cannot be started ====>>>> ",e.toString());
// }
//Intent i=new Intent("com.example.seperate_fileobserver.FileEvent");
// i.putExtra("path", path);
// startActivity(i);
}
//a file or directory was opened
if ((FileObserver.OPEN & event)!=0) {
FileAccessLogStatic.accessLogMsg += path + " is opened\n";
}
//data was read from a file
if ((FileObserver.ACCESS & event)!=0) {
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + path + " is accessed/read\n";
}
//data was written to a file
if ((FileObserver.MODIFY & event)!=0) {
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + path + " is modified\n";
}
//someone has a file or directory open read-only, and closed it
if ((FileObserver.CLOSE_NOWRITE & event)!=0) {
FileAccessLogStatic.accessLogMsg += path + " is closed\n";
}
//someone has a file or directory open for writing, and closed it
if ((FileObserver.CLOSE_WRITE & event)!=0) {
String filename = "";
int numbers = 0;
f_help.insertpic(filename,numbers);
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + path + " is written and closed\n";
}
//[todo: consider combine this one with one below]
//a file was deleted from the monitored directory
if ((FileObserver.DELETE & event)!=0) {
//for testing copy file
// FileUtils.copyFile(absolutePath + "/" + path);
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + path + " is deleted\n";
Log.v("deleting path",path);
// fileevent.delete(path);
//for(ObserverActivity o: registeredObservers){
// o.onFileObserved(event, path);
// }
try{
fileevent.delete(path);
}
catch(Exception e)
{
Log.v("File cannot be deleted ====>>>> ",e.toString());
}
}
//the monitored file or directory was deleted, monitoring effectively stops
if ((FileObserver.DELETE_SELF & event)!=0) {
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + " is deleted\n";
}
//a file or subdirectory was moved from the monitored directory
if ((FileObserver.MOVED_FROM & event)!=0) {
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + path + " is moved to somewhere " + "\n";
}
//a file or subdirectory was moved to the monitored directory
if ((FileObserver.MOVED_TO & event)!=0) {
FileAccessLogStatic.accessLogMsg += "File is moved to " + absolutePath + "/" + path + "\n";
}
//the monitored file or directory was moved; monitoring continues
if ((FileObserver.MOVE_SELF & event)!=0) {
FileAccessLogStatic.accessLogMsg += path + " is moved\n";
}
//Metadata (permissions, owner, timestamp) was changed explicitly
if ((FileObserver.ATTRIB & event)!=0) {
FileAccessLogStatic.accessLogMsg += absolutePath + "/" + path + " is changed (permissions, owner, timestamp)\n";
}
I am unable to get why it is undefined, and why FileObserver.onEvent() is not supporting startActivity(Intent) method.
Thanks in advance.
Try context.startActivity(i) instead.
startActivity is a method of Context and subclasses of Context, such as Activity and Service. You may be able to use context.startActivity(intent) to get rid of the syntax error, but you may want to consider placing this functionality inside a Service.

Categories

Resources