I want to take picture in an non-activity class. However I get error: Attempt to invoke virtual method on a null object reference. Here is my code:
MainAcvitity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Print myprint = new Print();
myprint.Picture();
}
Print.java
public class Print {
private static final String TAG = "Secret";
Context context;
public void Picture() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
((Activity) this.context).startActivityForResult(intent, 1);
Log.v(TAG, "I took a picture.");
}
}
I don't know what goes wrong. Can you tell me why this happens and how can I fix it? I don't want my Print class to be an Activity class. I know how how to take picture if Print is an Activity class. 0.0
Because your context is null. You haven't init it yet.
If you want to create a class to open your camera, try this:
public class Print{
private static final String TAG = "Secret";
private Context context;
private File photoCaptured;
public Print(Context context) {
this.context = context;
}
public void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = System.currentTimeMillis() + "";
String fileName = "JPEG_" + timeStamp;
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
photoCaptured = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),
fileName + ".jpg");
} else {
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
//create folder
File folder = new File(dir); //folder name
if (!folder.exists()) {
folder.mkdirs();
}
//create file
photoCaptured = new File(dir, fileName + ".jpg");
}
Uri temUri = Uri.fromFile(photoCaptured);
intent.putExtra(MediaStore.EXTRA_OUTPUT, temUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
if (intent.resolveActivity(context.getPackageManager()) != null) {
((AppCompatActivity) context).startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
}
}
Then in your MainActivity, init Print and use it.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Print myprint = new Print(this);
myprint.openCamera();
}
For your question, just init your Print class and it will work. (Just for your case only, but this is not the best approach!!!)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Print myprint = new Print(this);
myprint.Picture()
}
Related
Im working on a augmented reality app which displays 3d models on the users face.I made a class which extends ArFragment in which i set the front camera to be opened once a model is selected.I made a custom button for capturing the image,but i dont know how to implement the capture of the image itself with the 3d model displayed and store it in the phone(preferably without the custom made buttons being shown in the picture).Tried some code found on internet for programatical screenshoting but it screenshots only the buttons(the arrow and the circle).Here is how the activity looks like:
Here is the class that extends ArFragment:
public class CustomArFragment extends ArFragment {
#Override
protected Config getSessionConfiguration(Session session) {
Config config = new Config(session);
config.setAugmentedFaceMode(Config.AugmentedFaceMode.MESH3D);
this.getArSceneView().setupSession(session);
return config;
}
#Override
protected Set<Session.Feature> getSessionFeatures() {
return EnumSet.of(Session.Feature.FRONT_CAMERA);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
FrameLayout frameLayout = (FrameLayout) super.onCreateView(inflater, container, savedInstanceState);
getPlaneDiscoveryController().hide();
getPlaneDiscoveryController().setInstructionView(null);
return frameLayout;
}
}
Here is the activity in which i set the 3d model:
public class ArActivity extends AppCompatActivity {
int pos;
private int[] images = {R.raw.glasses1, R.raw.glasses3, R.raw.glasses4, R.raw.glasses5,
R.raw.glasses6, R.raw.glasses7, R.raw.glasses8, R.raw.glasses9, R.raw.glasses10};
private ModelRenderable modelRenderable;
private boolean isAdded = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
pos = extras.getInt("pos");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ar);
CustomArFragment customArFragment = (CustomArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment);
ModelRenderable
.builder().setSource(this, images[pos])
.build()
.thenAccept(renderable -> {
modelRenderable = renderable;
modelRenderable.setShadowCaster(false);
modelRenderable.setShadowReceiver(false);
});
customArFragment.getArSceneView().setCameraStreamRenderPriority(Renderable.RENDER_PRIORITY_FIRST);
customArFragment.getArSceneView().getScene().addOnUpdateListener(frameTime -> {
if (modelRenderable == null)
return;
Frame frame = customArFragment.getArSceneView().getArFrame();
Collection<AugmentedFace> augmentedFaces = frame.getUpdatedTrackables(AugmentedFace.class);
for (AugmentedFace augmentedFace : augmentedFaces) {
if (isAdded)
return;
AugmentedFaceNode augmentedFaceNode = new AugmentedFaceNode(augmentedFace);
augmentedFaceNode.setParent(customArFragment.getArSceneView().getScene());
augmentedFaceNode.setFaceRegionsRenderable(modelRenderable);
isAdded = true;
}
});
}
}
I had a similar problem before.
Capturing the Camera image with placed 3d models.
i solved it with PixelCopy.
I'm adding my code of that part below.
I'm sorry that it's not going to be the straight-answer to your problem but i hope you get some ideas
ImageButton btn3 = (ImageButton)findViewById(R.id.camera_btn);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
private String generateFilename() {
//현재시간을 기준으로 파일 이름 생성
String date =
new SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.getDefault()).format(new Date());
return Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES) + File.separator + "IM/" + date + "_screenshot.jpg";
}
private void saveBitmapToDisk(Bitmap bitmap, String filename) throws IOException {
//사용자의 갤러리에 IM 디렉토리 생성 및 Bitmap 을 JPEG 형식으로 갤러리에 저장
File out = new File(filename);
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
try (FileOutputStream outputStream = new FileOutputStream(filename);
ByteArrayOutputStream outputData = new ByteArrayOutputStream()) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputData);
outputData.writeTo(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
throw new IOException("Failed to save bitmap to disk", ex);
}
}
private void takePhoto(){
//PixelCopy 를 사용하여 카메라 화면과 object 를 bitmap 으로 생성
final String filename = generateFilename();
ArSceneView view = arFragment.getArSceneView();
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(),
Bitmap.Config.ARGB_8888);
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
PixelCopy.request(view, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap, filename);
//Media Scanning 실시
Uri uri = Uri.parse("file://" + filename);
Intent i = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
i.setData(uri);
sendBroadcast(i);
} catch (IOException e) {
Toast toast = Toast.makeText(AR_Activity.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
"스크린샷이 저장되었습니다.", Snackbar.LENGTH_LONG);
snackbar.setAction("갤러리에서 보기", v -> {
//어플 내에서 저장한 스크린샷을 확인 가능
File photoFile = new File(filename);
Uri photoURI = FileProvider.getUriForFile(AR_Activity.this,
AR_Activity.this.getPackageName() + ".ar.codelab.name.provider",
photoFile);
Intent intent = new Intent(Intent.ACTION_VIEW, photoURI);
intent.setDataAndType(photoURI, "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
});
snackbar.show();
} else {
Toast toast = Toast.makeText(AR_Activity.this,
"스크린샷 저장 실패!: " + copyResult, Toast.LENGTH_LONG);
toast.show();
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}
}
I am working on an app that allows user to select a file from external storage and send it using Android Beam.
Here is the FileBrowser Activity to select a file from a directory and return the file name and directory path back to main activity:
public class FileBrowser extends Activity {
private String root;
private String currentPath;
private ArrayList<String> targets;
private ArrayList<String> paths;
private File targetFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_browser);
getActionBar().setDisplayHomeAsUpEnabled(true);
root = "/";
currentPath = root;
targets = null;
paths = null;
targetFile = null;
showDir(currentPath);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_file_browser, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectDirectory(View view) {
File f = new File(currentPath);
targetFile = f;
//Return target File to activity
returnTarget();
}
public void setCurrentPathText(String message)
{
TextView fileTransferStatusText = (TextView) findViewById(R.id.current_path);
fileTransferStatusText.setText(message);
}
private void showDir(String targetDirectory){
setCurrentPathText("Current Directory: " + currentPath);
targets = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(targetDirectory);
File[] directoryContents = f.listFiles();
if (!targetDirectory.equals(root))
{
targets.add(root);
paths.add(root);
targets.add("../");
paths.add(f.getParent());
}
for(File target: directoryContents)
{
paths.add(target.getPath());
if(target.isDirectory())
{
targets.add(target.getName() + "/");
}
else
{
targets.add(target.getName());
}
}
ListView fileBrowserListView = (ListView) findViewById(R.id.file_browser_listview);
ArrayAdapter<String> directoryData = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, targets);
fileBrowserListView.setAdapter(directoryData);
fileBrowserListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos,long id) {
File f = new File(paths.get(pos));
if(f.isFile())
{
targetFile = f;
returnTarget();
//Return target File to activity
}
else
{
//f must be a dir
if(f.canRead())
{
currentPath = paths.get(pos);
showDir(paths.get(pos));
}
}
}
});
}
public void returnTarget()
{
Intent returnIntent = new Intent();
returnIntent.putExtra("file", targetFile);
returnIntent.putExtra("path", currentPath);
setResult(RESULT_OK, returnIntent);
finish();
}
}
Here is the code for MainActivity where the file returned by FileBrowser Activity is send using android beam:
public class MainActivity extends Activity {
private NfcAdapter nfcAdapter;
public final int fileRequestID = 98;
String name;
String[] extension={".png",".docx",".jpeg",".pdf",".doc"};
ArrayList <String>supportedExtension=new ArrayList<String>(Arrays.asList(extension));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PackageManager pm = this.getPackageManager();
// Check whether NFC is available on device
if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
// NFC is not available on the device.
Toast.makeText(this, "The device does not has NFC hardware.",
Toast.LENGTH_SHORT).show();
}
// Check whether device is running Android 4.1 or higher
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
// Android Beam feature is not supported.
Toast.makeText(this, "Android Beam is not supported.",
Toast.LENGTH_SHORT).show();
}
else {
// NFC and Android Beam file transfer is supported.
Toast.makeText(this, "Android Beam is supported on your device.",
Toast.LENGTH_SHORT).show();
}
}
public void browseForFile(View view) {
Intent clientStartIntent = new Intent(this, FileBrowser.class);
startActivityForResult(clientStartIntent, fileRequestID);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//fileToSend
boolean filePathProvided;
File fileToSend;
if (resultCode == Activity.RESULT_OK && requestCode == fileRequestID) {
//Fetch result
File targetDir = (File) data.getExtras().get("file");
String path = (String)data.getExtras().get("path");
Log.i("Path=",path);
if(targetDir.isFile())
{
if(targetDir.canRead()) {
try{
String ext=targetDir.getName().substring(targetDir.getName().lastIndexOf("."));
if (supportedExtension.contains(ext)) {
fileToSend = targetDir;
filePathProvided = true;
setTargetFileStatus(targetDir.getName() + " selected for file transfer");
Button btn = (Button) findViewById(R.id.send);
btn.setVisibility(View.VISIBLE);
name = targetDir.getName();
}
else{
Toast.makeText(getApplicationContext(), "File with this extension cannot be printed",
Toast.LENGTH_LONG).show();
}
}catch (Exception e){e.printStackTrace();}
}
else
{
filePathProvided = false;
setTargetFileStatus("You do not have permission to read the file " + targetDir.getName());
}
}
else
{
filePathProvided = false;
setTargetFileStatus("You may not transfer a directory, please select a single file");
}
}
}
public void setTargetFileStatus(String message)
{
TextView targetFileStatus = (TextView) findViewById(R.id.selected_filename);
targetFileStatus.setText(message);
}
public void sendFile(View view) {
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// Check whether NFC is enabled on device
if(!nfcAdapter.isEnabled()){
Toast.makeText(this, "Please enable NFC.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
else if(!nfcAdapter.isNdefPushEnabled()) {
Toast.makeText(this, "Please enable Android Beam.",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
}
else {
Uri[] mFileUris = new Uri[1];
String fileName=name;
// Retrieve the path to the user's public pictures directory
File fileDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File fileToTransfer;
fileToTransfer = new File(fileDirectory, fileName);
fileToTransfer.setReadable(true, false);
mFileUris[0] = Uri.fromFile(fileToTransfer);
nfcAdapter.setBeamPushUris(mFileUris, this);
}
}
}
Now, as you can see in my MainActivity, I am setting my directory as Pictures.
File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
My question is How can I dynamically change my directory every time based on the actual directory value obtained from FileBrowser Activity?
I have already went through the android documentation of How to send files using Android Beam, but didn't find it much useful for my problem. I also went through the android documentation of Environment, but couldn't understand much.
Any help regarding this will really be appreciated. Thanks in advance!
You already have the file selected in OnActivityResult method. Just change
mFileUris[0] = Uri.fromFile(fileToTransfer);
to
mFileUris[0] = Uri.fromFile(targetDir);
I'm trying to make an app that will react to screenshots folder and do a toast for beginning,
I'm a new developer and this is my first time using file observer so I can only guess I've made a lot of mistakes.
The problem is there is no toast or log upon taking a screenshot.
Here is the code in my observer class:
public class listeningInit extends FileObserver {
private static final String TAG = "File listener";
public String absolutePath;
public listeningInit(String path) {
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
}
#Override
public void onEvent(int event, String path) {
if ((FileObserver.CREATE & event)!=0) {
Log.v(TAG, absolutePath + "/" + path + " is created\n");
Context context = getContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Folder action!", duration);
toast.show();
}
}
private Context getContext() {
// TODO Auto-generated method stub
return null;
}
and here's the code on activity that does .startWatching
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listeningInit startObs = new listeningInit("/Pictures/Screenshots/");
startObs.startWatching();
//Checking if this is a first run
Boolean firstRun = false;
SharedPreferences run = getSharedPreferences("MYPREFS", 0);
firstRun = run.getBoolean("fr", true);
//if true launch tutorial activity
if(firstRun == true){
Intent k = new Intent(MainActivity.this, Tutorial.class);
startActivity(k);
}
}
There's no errors thrown by the code, it's just not responding and I don't have a slight clue on why that might be.
I have an application that saves data to a file called 'sensorLog.txt'. I am not sure where exactly this is stored but I know this is only accessible by the applicationand it is in the internal memory.
I want to be able to write a copy the current file to an external storage when I click on a button "export". I have pasted a small bit of my program, But i am not sure how to copy sensorLog.txt file to the external storage.
public class MainActivity extends Activity {
private static final String DEBUG_TAG = "MainActivity";
private Button buttonStartService;
private Button buttonStopService;
private Button buttonSettings;
private Button buttonExport;
private TextView textStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
setContentView(R.layout.activity_main);
buttonStartService = (Button) findViewById(R.id.button_start_service);
buttonStopService = (Button) findViewById(R.id.button_stop_service);
buttonSettings = (Button) findViewById(R.id.button_settings);
buttonExport = (Button) findViewById(R.id.button_export);
textStatus = (TextView) findViewById(R.id.text_status);
buttonStartService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startSensorService();
}
});
buttonStopService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopSensorService();
}
});
//export button listener
buttonExport.setOnClickListener(export_handler);
}
public void startSensorService() {
// Schedule
AlarmManager scheduler = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), SensorService.class);
PendingIntent scheduledIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 30 seconds
long interval = 30 * 1000;
scheduler.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, scheduledIntent);
Log.d(DEBUG_TAG, "Service started");
}
public void stopSensorService() {
// Cancel
AlarmManager scheduler = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, SensorService.class);
PendingIntent scheduledIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
scheduler.cancel(scheduledIntent);
Log.d(DEBUG_TAG, "Service stopped");
}
View.OnClickListener export_handler = new View.OnClickListener() {
public void onClick(View v)
{
// Here is the part I am not sure what to do. I want to copy a file sensorLog.txt that has all my sensor information to sd card
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
Log.d(DEBUG_TAG, "SD card detected");
stopSensorService();
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS),"SensorLog.txt");
// delete file from the internal storage once exported
context.deleteFile("SensorLog.txt");
startSensorService();
}
else
{
Log.d(DEBUG_TAG, "No external storage detected(cannot copy file)");
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Part where I create sensorLog.txt***(I dont think it is necessary to read for this question but just in case someone needs it)*:
private class SensorServiceLoggerTask extends AsyncTask<SensorFrame, Void, Void> {
#Override
protected Void doInBackground(SensorFrame... frames) {
SensorFrame frame = frames[0];
BufferedWriter bufWr = null;
try {
File file = new File(getApplicationContext().getFilesDir(), "SensorLog.txt");
if (file.exists()) {
// Write to new file
bufWr = new BufferedWriter(new FileWriter(file, true));
} else {
file.createNewFile();
Log.d(DEBUG_TAG, "New log file created");
// Append to existing file
bufWr = new BufferedWriter(new FileWriter(file, false));
// Write header
bufWr.append(sensorHeader.toString());
}
// Write frame
bufWr.append(sensorFrame.toString());
bufWr.flush();
Log.d(DEBUG_TAG, "Added frame to log");
} catch (IOException ex) {
// TODO: useful error handling
} finally {
// Cleanup
if (bufWr != null) {
try {
bufWr.close();
} catch (IOException ex) {
// TODO: useful error handling
}
}
}
return null;
}
}
I also have 2 more queries:
Lets say I want to append some information at the top of the file just before moving it how can I do that?
My aim is to transfer the sensorLog.txt file from internal to external storage when the export button is pressed. delete or empty the internal sensorLog.txt file and then the same thing happens again if i press export again, then I would have to rename my file when I export it right? would there not be a name clash? How do I handle that? could I give a name dynamically?
Thank you.
EDIT: Some corrections
View.OnClickListener export_handler = new View.OnClickListener() {
public void onClick(View v)
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
Log.d(DEBUG_TAG, "SD card detected");
stopSensorService();
Log.d(DEBUG_TAG, "stopSensorService for file transfer");
//make the timestamp the file name
long TS = System.currentTimeMillis();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(TS);
stringBuilder.append(".txt");
String file_name = stringBuilder.toString();
//file name stored in file_name
File file_ext = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS),file_name);
// attempt to create this new directory
//read from sensorLog.txt file
try
{
file_ext.createNewFile();
File file = getBaseContext().getFileStreamPath("sensorLog.txt");
if(file.exists())
{
FileInputStream read_file = openFileInput("sensorLog.txt");
//read contents of internal file
InputStreamReader inputStreamReader = new InputStreamReader(read_file);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
sb.append("Timestamp of export to SD"+TS+"/n");
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
BufferedWriter bufWr = null;
bufWr = new BufferedWriter(new FileWriter(file_ext, false));
// Write header
bufWr.append(sb.toString());
inputStreamReader.close();
bufWr.close();
read_file.close();
//delete sensor file once exported
getApplicationContext().deleteFile("sensorLog.txt");
}
}
catch(Exception e){}
But for some reason my file is not getting stored in the SD card.
Check out the Android documentation. If you can read your sensorLog.txt file, then you can save it in a String and then save the string to a file in the external storage.
I am downloading a file from ftp server. downloading code worked fine, however after download code screen doesn't show anything ,it gets black. Also download function is not returning true value, even the file is being saved in the specified directory.
public class FTPClass{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_player);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Intent intent = getIntent();
dirname = intent.getStringExtra("currentDirName");
MyFTPClient mftp = new MyFTPClient();
createPath = mftp.getAppRootPath().concat("/"+ dirname);
mftp.setCurrentDir(createPath);
System.out.println(mftp.ftpChangeDirectory(createPath));
FTPFile[] farr = mftp.ftpListAllFiles();
System.out.println(farr.length);
for(int i = 0; i<farr.length;i++){
System.out.println("SRC: "+createPath+"/"+farr[i].getName());
String src = createPath+"/"+farr[i].getName();
System.out.println("DEST: "+"/data/data/com.example.ftpplayer" + "/app_"+dirname);
String dest ="/data/data/com.example.ftpplayer" + "/app_"+dirname+"/"+farr[i].getName();
System.out.println(mftp.downloadFile(src,dest));
}
}
}
public class CallingIntent extends Activity{
System.out.println("In item click ");
Intent intent = new Intent(getApplicationContext(), FTPClass.class);
String dir = ((TextView) view).getText().toString();
intent.putExtra("currentDirName", dir);
startActivity(intent);
}
public class MyFTPClient{
public boolean downloadFile(String srcPath , String destPath){
try {
FileOutputStream fos = new FileOutputStream(destPath);
System.out.println(mftp.retrieveFile(srcPath, fos)); // retrieve file doesn't return true
fos.flush();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return false;
}
}
You need to run your code on the background thread, try using an asyncTask.