How to open a file in android app? - android

I am trying to make an app that can open a file from the phone's directory. I will be opening .ddd files but would like to be able to open any file type. I know intents can be used. I have tried this but at the moment it just opens goes into the file selection but doesn't open the file.
import java.io.File;
import java.io.Serializable;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import ar.com.daidalos.afiledialog.*;
public class AFileDialogTestingActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Assign behaviors to the buttons.
Button buttonActivity1 = (Button)this.findViewById(R.id.activity_simple_open);
buttonActivity1.setOnClickListener(btnActivitySimpleOpen);
Button buttonActivity2 = (Button)this.findViewById(R.id.activity_open_downloads);
buttonActivity2.setOnClickListener(btnActivityOpenDownloads);
Button buttonActivity3 = (Button)this.findViewById(R.id.activity_select_folders);
buttonActivity3.setOnClickListener(btnActivitySelectFolders);
Button buttonActivity4 = (Button)this.findViewById(R.id.activity_create_files);
buttonActivity4.setOnClickListener(btnActivityCreateFiles);
Button buttonActivity5 = (Button)this.findViewById(R.id.activity_select_images);
buttonActivity5.setOnClickListener(btnActivitySelectImages);
Button buttonActivity6 = (Button)this.findViewById(R.id.activity_ask_confirmation);
buttonActivity6.setOnClickListener(btnActivityAskConfirmation);
Button buttonActivity7 = (Button)this.findViewById(R.id.activity_custom_labels);
buttonActivity7.setOnClickListener(btnActivityCustomLabels);
Button buttonDialog1 = (Button)this.findViewById(R.id.dialog_simple_open);
buttonDialog1.setOnClickListener(btnDialogSimpleOpen);
Button buttonDialog2 = (Button)this.findViewById(R.id.dialog_open_downloads);
buttonDialog2.setOnClickListener(btnDialogOpenDownloads);
Button buttonDialog3 = (Button)this.findViewById(R.id.dialog_select_folders);
buttonDialog3.setOnClickListener(btnDialogSelectFolders);
Button buttonDialog4 = (Button)this.findViewById(R.id.dialog_create_files);
buttonDialog4.setOnClickListener(btnDialogCreateFiles);
Button buttonDialog5 = (Button)this.findViewById(R.id.dialog_select_images);
buttonDialog5.setOnClickListener(btnDialogSelectImages);
Button buttonDialog6 = (Button)this.findViewById(R.id.dialog_ask_confirmation);
buttonDialog6.setOnClickListener(btnDialogAskConfirmation);
Button buttonDialog7 = (Button)this.findViewById(R.id.dialog_custom_labels);
buttonDialog7.setOnClickListener(btnDialogCustomLabels);
}
// ----- Buttons for open a dialog ----- //
private OnClickListener btnDialogSimpleOpen = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogOpenDownloads = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Define start folder.
dialog.loadFolder(Environment.getExternalStorageDirectory() + "/Download/");
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogSelectFolders = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the folder mode.
dialog.setFolderMode(true);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogCreateFiles = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the button for create files.
dialog.setCanCreateFiles(true);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogSelectImages = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Define the filter for select images.
dialog.setFilter(".*jpg|.*png|.*gif|.*JPG|.*PNG|.*GIF");
dialog.setShowOnlySelectable(false);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogAskConfirmation = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the button for create files.
dialog.setCanCreateFiles(true);
// Activate the confirmation dialogs.
dialog.setShowConfirmation(true, true);
// Show the dialog.
dialog.show();
}
};
private OnClickListener btnDialogCustomLabels = new OnClickListener() {
public void onClick(View v) {
// Create the dialog.
FileChooserDialog dialog = new FileChooserDialog(AFileDialogTestingActivity.this);
// Assign listener for the select event.
dialog.addListener(AFileDialogTestingActivity.this.onFileSelectedListener);
// Activate the folder mode.
dialog.setFolderMode(true);
// Activate the button for create files.
dialog.setCanCreateFiles(true);
// Activate the confirmation dialogs.
dialog.setShowConfirmation(true, true);
// Define the labels.
FileChooserLabels labels = new FileChooserLabels();
labels.createFileDialogAcceptButton = "AcceptButton";
labels.createFileDialogCancelButton = "CancelButton";
labels.createFileDialogMessage = "DialogMessage";
labels.createFileDialogTitle = "DialogTitle";
labels.labelAddButton = "AddButton";
labels.labelSelectButton = "SelectButton";
labels.messageConfirmCreation = "messageConfirmCreation";
labels.messageConfirmSelection = "messageConfirmSelection";
labels.labelConfirmYesButton = "yesButton";
labels.labelConfirmNoButton = "noButton";
dialog.setLabels(labels);
// Show the dialog.
dialog.show();
}
};
// ---- Buttons for open an activity ----- //
private OnClickListener btnActivitySimpleOpen = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityOpenDownloads = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Define start folder.
intent.putExtra(FileChooserActivity.INPUT_START_FOLDER, Environment.getExternalStorageDirectory() + "/Download/");
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivitySelectFolders = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the folder mode.
intent.putExtra(FileChooserActivity.INPUT_FOLDER_MODE, true);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityCreateFiles = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the button for create files.
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivitySelectImages = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Define the filter for select images.
intent.putExtra(FileChooserActivity.INPUT_REGEX_FILTER, ".*jpg|.*png|.*gif|.*JPG|.*PNG|.*GIF");
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityAskConfirmation = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the button for create files.
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
// Activate the confirmation dialogs.
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_CREATE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_SELECT, true);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener btnActivityCustomLabels = new OnClickListener() {
public void onClick(View v) {
// Create the intent for call the activity.
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
// Activate the folder mode.
intent.putExtra(FileChooserActivity.INPUT_FOLDER_MODE, true);
// Activate the button for create files.
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
// Activate the confirmation dialogs.
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_CREATE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_SELECT, true);
// Define the labels.
FileChooserLabels labels = new FileChooserLabels();
labels.createFileDialogAcceptButton = "AcceptButton";
labels.createFileDialogCancelButton = "CancelButton";
labels.createFileDialogMessage = "DialogMessage";
labels.createFileDialogTitle = "DialogTitle";
labels.labelAddButton = "AddButton";
labels.labelSelectButton = "SelectButton";
labels.messageConfirmCreation = "messageConfirmCreation";
labels.messageConfirmSelection = "messageConfirmSelection";
labels.labelConfirmYesButton = "yesButton";
labels.labelConfirmNoButton = "noButton";
intent.putExtra(FileChooserActivity.INPUT_LABELS, (Serializable) labels);
// Call the activity
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
private OnClickListener clickButtonOpenActivity = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AFileDialogTestingActivity.this, FileChooserActivity.class);
intent.putExtra(FileChooserActivity.INPUT_REGEX_FILTER, ".*pdf|.*jpg|.*png|.*mp3|.*mp4|.*avi");
intent.putExtra(FileChooserActivity.INPUT_SHOW_ONLY_SELECTABLE, true);
intent.putExtra(FileChooserActivity.INPUT_CAN_CREATE_FILES, true);
intent.putExtra(FileChooserActivity.INPUT_FOLDER_MODE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_CREATE, true);
intent.putExtra(FileChooserActivity.INPUT_SHOW_CONFIRMATION_ON_SELECT, true);
// Define labels.
FileChooserLabels labels = new FileChooserLabels();
labels.createFileDialogAcceptButton = "AcceptButton";
labels.createFileDialogCancelButton = "CancelButton";
labels.createFileDialogMessage = "DialogMessage";
labels.createFileDialogTitle = "DialogTitle";
labels.labelAddButton = "AddButton";
labels.labelSelectButton = "SelectButton";
labels.messageConfirmCreation = "messageConfirmCreation";
labels.messageConfirmSelection = "messageConfirmSelection";
labels.labelConfirmYesButton = "yesButton";
labels.labelConfirmNoButton = "noButton";
intent.putExtra(FileChooserActivity.INPUT_LABELS, (Serializable) labels);
AFileDialogTestingActivity.this.startActivityForResult(intent, 0);
}
};
// ---- Methods for display the results ----- //
private FileChooserDialog.OnFileSelectedListener onFileSelectedListener = new FileChooserDialog.OnFileSelectedListener() {
public void onFileSelected(Dialog source, File file) {
source.hide();
Toast toast = Toast.makeText(AFileDialogTestingActivity.this, "File selected: " + file.getName(), Toast.LENGTH_LONG);
toast.show();
}
public void onFileSelected(Dialog source, File folder, String name) {
source.hide();
Toast toast = Toast.makeText(AFileDialogTestingActivity.this, "File created: " + folder.getName() + "/" + name, Toast.LENGTH_LONG);
toast.show();
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
boolean fileCreated = false;
String filePath = "";
Bundle bundle = data.getExtras();
if(bundle != null)
{
if(bundle.containsKey(FileChooserActivity.OUTPUT_NEW_FILE_NAME)) {
fileCreated = true;
File folder = (File) bundle.get(FileChooserActivity.OUTPUT_FILE_OBJECT);
String name = bundle.getString(FileChooserActivity.OUTPUT_NEW_FILE_NAME);
filePath = folder.getAbsolutePath() + "/" + name;
} else {
fileCreated = false;
File file = (File) bundle.get(FileChooserActivity.OUTPUT_FILE_OBJECT);
filePath = file.getAbsolutePath();
}
}
String message = fileCreated? "File created" : "File opened";
message += ": " + filePath;
Toast toast = Toast.makeText(AFileDialogTestingActivity.this, message, Toast.LENGTH_LONG);
toast.show();
}
}
}

This is how I would do it. You also should be sure to include <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in the AndroidManifest
xml file
Button
android:id="#+id/FileButtonOrWhatever"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="GetFiles"
java file
public void GetFiles(View view) {
// get the files directory
File lister = this.getFilesDir();
FileInputStream inputStream = null;
byte[] bytes = new byte[500];
int fileIdx = -1;
for (String list : lister.list()){
fileIdx++;
if(list.endsWith("ddd")){
File file = lister.listFiles()[fileIdx];
try {
inputStream = new FileInputStream(file);
bytes = new byte[inputStream.available()];
inputStream.read(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();}
finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}

Related

directly start Activity if user has already registered

I am new in android development. i want my application to directly launch MainActivity if the User has already registered. how can i do this.
this is my MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
Button btnTip, btnApp, btndos, btnAbout, btnServices;
ConnectionDetector cd;
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
public static String contact;
public static String imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Dental Application");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnTip = (Button) findViewById(R.id.tips);
btndos = (Button) findViewById(R.id.dos);
btnApp = (Button) findViewById(R.id.appointments);
btnAbout = (Button) findViewById(R.id.about);
btnServices = (Button) findViewById(R.id.services);
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please check your Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
contact = i.getStringExtra("contact");
imei = i.getStringExtra("imei");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
//lblMessage = (TextView) findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId, contact, imei);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
btnTip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TipsActivity.class);
startActivity(intent);
}
});
btndos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DosActivity.class);
startActivity(intent);
}
});
btnApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BookAppointmennts.class);
startActivity(intent);
}
});
btnAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AboutUsActivity.class);
startActivity(intent);
}
});
btnServices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ServicesActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
//lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver", "> " + e.getMessage());
}
super.onDestroy();
}
}
and the RegisterActivity
public class RegisterActivity extends Activity {
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
// UI elements
EditText txtName;
EditText txtEmail;
EditText txtContact;
// Register button
Button btnRegister;
String imei;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if GCM configuration is set
if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
|| SENDER_ID.length() == 0) {
// GCM sernder id / server url is missing
alert.showAlertDialog(RegisterActivity.this, "Configuration Error!",
"Please set your Server URL and GCM Sender ID", false);
// stop executing code by return
return;
}
txtName = (EditText) findViewById(R.id.txtName);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtContact = (EditText) findViewById(R.id.contact);
btnRegister = (Button) findViewById(R.id.btnRegister);
TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = mngr.getDeviceId();
/*
* Click event on Register button
* */
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Read EditText dat
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
String contact = txtContact.getText().toString();
// Check if user filled the form
if (name.trim().length() > 0 && email.trim().length() > 0 && contact.trim().length()>0) {
// Launch Main Activity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Registering user on our server
// Sending registraiton details to MainActivity
i.putExtra("name", name);
i.putExtra("email", email);
i.putExtra("contact", contact);
i.putExtra("imei", imei);
startActivity(i);
finish();
} else {
// user doen't filled that data
// ask him to fill the form
alert.showAlertDialog(RegisterActivity.this, "Registration Error!", "Please enter your details", false);
}
}
});
}
}
i am using GCM. the user is first registered and MainActivity is Displayed. Next time when the user opens the application i want directly MainActivity to be displayed. how can i do this. Can anyone please help me.
You will have to make LauncherActivity like SplashScreen in which check from shared prefrences or sqlite data that user is already registered or not
then by checking this transfer to corresponding activity.
If the user is not registered then show Registration Screen and when user register then save info in Sqlite or sharedpreferences or any other way.
If the user is already registered the show HomeScreen
First of all just post only the code that needs modification, you've posted all of the code in that Java file of yours. We could be more helpful if your code isn't cluttered.

How to set directory for sending files using Android Beam

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);

Dont open second activity if android back button is pressed

i am trying to implement below code every thing works fine how ever
here is the situation i am facing
mainactivity just has a button to open splashactivity
splash activity does the parsing part then opens the listactvity
my workflow is if user has clicked on the button in main activity
it opens the splash activity and redirects to listactivty the
problem occurs when on the splash activity if a user clicks the
andorid back button it does go back to the mainactivity however the
parsing in splashactivity continues and user is redirected to
listactivty this thing should not happen, when user on splash
activity has clicked backbutton it should go back to mainactivity
and stay there itself
how can this be done
package com.site.name;
public class SplashActivity extends Activity {
RSSFeed feed;
String fileName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
// //public String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity!",
Toast.LENGTH_LONG);
toast.show();
//feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//feed = myParser.parseXml(RSSFEEDURL);
//feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss");
feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
//Include the code here
return;
}
}
You can cancel parsing the feed in MainActivity's onRestart() as this is one method of MainActivity that will be called when you press back from your Parsing Activity.
You can read more about Activity Life Cycle here.
For detecting the Back button press event use the following method
#Override
public void onBackPressed() {
// do something on back.
// Change your activity by calling intent
return;
}
If you want to do anything with your back button then you have to override it manually.
#Override
Public void onBackPressed() {
//do whatever you want to do as your question is quite confusing.
return;
}

restoring the edittext field on clicking back button

public class MainActivity extends Activity implements SurfaceHolder.Callback {
EditText , PatientInfo,PatientAge,PatientId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
Button buttonCapturePreview = (Button) findViewById(R.id.Capturecamerapreview);
rgGender = (RadioGroup) findViewById(R.id.rgGender);
rdbMale = (RadioButton) findViewById(R.id.rdbMale);
rdbFemale = (RadioButton) findViewById(R.id.rdbFemale);
PatientInfo = (EditText) findViewById(R.id.PatientName);
PatientInfo.setHint("enter patient name");
PatientAge = (EditText) findViewById(R.id.Age);
PatientAge.setHint("Age");
PatientId = (EditText) findViewById(R.id.PatientId);
PatientId.setHint("PatientId");
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this)
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
loadInput();
int imageNum = 0;
String Name = PatientInfo.getText().toString();
String Age = PatientAge.getText().toString();
String Id = PatientId.getText().toString();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
Rname = s.toString() +".jpg";
File imagesFolders = new File(Environment.getExternalStorageDirectory().toString() + "/" + Name + Age + gender + Id);
imagesFolders.mkdirs();
File output = new File(imagesFolders, Rname);
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(MainActivity.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
{
........
}
buttonCapturePreview.setOnClickListener(new OnClickListener()
{...}
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
......}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.rdbMale:
if (checked)
gender= "M";
gender1="M";
rdbFemale.setChecked(false);
break;
case R.id.rdbFemale:
if (checked)
gender = "F";
gender1="F";
rdbMale.setChecked(false);
break;
}
}
Button backButton = (Button) findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
saveInput();
startActivity(intent);
}
});
}
protected void saveInput()
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().putString("Name",PatientInfo.getText().toString()).commit();
preferences.edit().putString("Age", PatientAge.getText().toString()).commit();
preferences.edit().putString("Id",PatientId.getText().toString()).commit();
}
private void loadInput(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedTextN = preferences.getString("Name", null);
String savedTextA = preferences.getString("Age", null);
String savedTextI = preferences.getString("Id", null);
PatientInfo.setText(savedTextN);
PatientAge.setText(savedTextA);
PatientId.setText(savedTextI);
System.out.println(savedTextN);
System.out.println(savedTextA);
System.out.println(savedTextI);
}
i am trying to load the same data that i entered in my first activity. On button click the data is lodt. So i used shared preferences. But am using it first time so there is something wrong in my code. I just tried to load one of the edittext. Anyone can point out whats the mistake
You are doing it wrong. the wrong things are
to just restoring a data you are trying to restart the whole activity.
you are calling the onResume method by yourself..
Dont do these . you can do it easily by following.
create a method which will do the initial data setting tasks for your.
in onResume of you method (or in oncreate ) call that method
whenever you want to reset data (i.e after back button pressed) call that method.
You are wrongly getting the data from your preferences with the Wrong key.
As you are storing the value in preferences with the key Name in your onResume method and in your loadInput method you are trying to fetch it with the PatientInfo key which is not available in your preferences.
Change your loadInput method as below:
private void loadInput(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedText = preferences.getString("Name");
PatientInfo.setText(savedText);
}
As the onResume method always gets called before the onCreate so you need to initialize your PatientInfo view in your onResume method and then try to store its value into the Preferences.

Image is not displayed in the imageview on giving the path of that image

I am trying to display image on ImageView. I have the image in /storage/sdcard/DCIM/Camera/SAMPLE IMAGES/xxx.png I have used the following code to display image on the ImageView.
public class MainActivity extends Activity
{ Button button,hi,addpic;
final adapter info = new adapter(this);
Runnable m_handlertask = null ;
String path,birth;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
hi = (Button) findViewById(R.id.button3);
final adapter info = new adapter(this);
/* for(int i =1;i<=info.getrowcount();i++)
{
java.lang.String[] images_paths = {};
images_paths[i-1]=info.fetchsingles(i);
Toast.makeText(getApplicationContext(), images_paths[i-1], Toast.LENGTH_LONG).show();
}*/
hi.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,newlist.class);
startActivity(i);
}
});
addpic = (Button) findViewById(R.id.button2);
addpic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,adpic.class);
startActivity(i);
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,padd.class);
startActivity(i);
}
});
Date date = new Date(0);
java.text.DateFormat dateFormat =
android.text.format.DateFormat.getDateFormat(getApplicationContext());
dateFormat.format(date);
final ImageView jpgView;
jpgView = (ImageView) findViewById(R.id.imageView1);
//adapter mDbAdapter;
// path = info.getpath(y);
path = info.getPath();
final Handler mHandler = new Handler();
m_handlertask = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
mHandler.postDelayed(m_handlertask,3000);
condition();
}
int i=3;
private void condition() {
// TODO Auto-generated method stub
if((i % 3 )== 0) //running 1 time
{
birthday();
i++;
}
else //running 2 times
{
images();
i++;
}
}
private void birthday() {
// TODO Auto-generated method stub
try
{
birth = info.getBirth();
Toast.makeText(getApplicationContext(), "This is b'day pic : "+birth, Toast.LENGTH_LONG).show();
//Drawable d = Drawable.createFromPath(birth);
//jpgView.setImageDrawable(d);
File sdCardPath = Environment.getExternalStorageDirectory();
Bitmap bitmap = BitmapFactory.decodeFile(sdCardPath+"/DCIM/Camera/SAMPLE IMAGES/"+path);
jpgView.setImageBitmap(bitmap);
// Bitmap bitmap = BitmapFactory.decodeFile(birth);
// jpgView.setImageBitmap(bitmap);
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
private void images() {
// TODO Auto-generated method stub
try
{
path = info.getPath();
Toast.makeText(getApplicationContext(), "This is reg pic : "+path, Toast.LENGTH_LONG).show();
// Drawable d = Drawable.createFromPath(path);
// jpgView.setImageDrawable(d);
File sdCardPath = Environment.getExternalStorageDirectory();
Bitmap bitmap = BitmapFactory.decodeFile(sdCardPath+"/DCIM/Camera/SAMPLE IMAGES/"+path);
jpgView.setImageBitmap(bitmap);
// Bitmap bitmap = BitmapFactory.decodeFile(path);
// jpgView.setImageBitmap(bitmap);
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
};
m_handlertask.run();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }
I have read other questions and tutorials, but I found same method of displaying, as I did in the code above. No image is displayed here. I did not find any error message in logcat. Please suggest me, any improvements in the code.
Thanks in advance.
You have a space between "/storage/ sdcard/". You should print the stacktrace to see the Exception using er.printStackTrace(). Also, you shouldn't hardcode the string path; use the Environment Class to reference file locations in a consistent way.
1) Make sure you have given permission to read external storage in your android manifest file.
2)
instead of hard coding the path to external storage use this.
File sdCardPath = Environment.getExternalStorageDirectory();
then add your folder and file name..
Bitmap bitmap = BitmapFactory.decodeFile(sdCardPath+"/DCIM/Camera/img_folder/xxx.png");
jpgView.setImageBitmap(bitmap);

Categories

Resources