Hi I have a tricky problem that seems simple but it has been teasing my brain ever since I started it.
My app allows the user to enter a Product Number and an image Number. The app can take more than one image of one product.
When saving the images to gallery I would like to add a sequential file number to it so that I know which images are linked to which product.
Here is the format in which the file will be saved:
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
For example,
Type No = Test1;
ImageNo = 1;
sequentialNumber = 1;
fname = Test1(1)1;
When the user saves this one, they go back to the data entry activity and If they keep the same TypeNo/ProductCode then the sequentialNo should stay the same for the next save.
If the user enters a different TypeNo/ProductNo then the sequentialNo will increment.
Here is the code I have tried so far which doesn't increment correctly when a new TypeNo is entered:
private void saveImageToExternalStorage(Bitmap bitmap_view) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/Digital_Images");
myDir.mkdirs();
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap_view.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = sharedPreferences.edit();
String lastUsedTypeNo = TypeNo;
editor.putString("TypeNo", lastUsedTypeNo);
editor.putInt("sequentialNum", sequentialNumber);
editor.apply();
}
#Override
public void onResume() {
super.onResume();
String TypeNoRetrieved = sharedPreferences.getString("TypeNo", null);
int SQNumRetrieved = sharedPreferences.getInt("sequentialNum", 1);
if (TypeNoRetrieved != null || SQNumRetrieved != 0) {
if (TypeNoRetrieved == lastUsedTypeNo ) {
sequentialNumber = SQNumRetrieved;
} else {
sequentialNumber++;
}
}
}
Anyone able to solve this puzzle for me?
Related
I want to get a file path from my file browser function, but my file browser function has listener, so if i call another function after this file explorer function, it become crash because the path is still empty, here's two function that i want to call :
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
}
});
fileDialog.showDialog();
}
private void generateMFCC(String path) {
// btnBrowse.setText("Done");
Log.d(getClass().getName(), ": Success");
buffer = mRecorder.ReadWave(path);
data = new float[buffer.length];
for (int i = 0; i < buffer.length; i++) {
data[i] = (float) buffer[i];
}
//Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
preProcess = new PreProcess(data, samplePerFreame, sampleRate);
featureExtract = new FeatureExtract(preProcess.framedSignal, sampleRate, samplePerFreame);
featureExtract.makeMfccFeatureVector();
featureVector = featureExtract.getFeatureVector();
double[][] fv = featureVector.getMfccFeature();
for (int i = 0; i < fv.length; i++) {
test = test + "{" + "\n";
for (int j = 0; j < fv[i].length; j++) {
test = test + Double.toString(fv[i][j]) + ", ";
}
test = test + "}" + "\n";
}}
i call the function like this :
openFileExplorer();
generateMFCC(chosenFile);
but it always gives error before the file explorer dialog open
call generateMFCC from openFileExplorer only.
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
generateMFCC(chosenFile);
}
});
fileDialog.showDialog();
}
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
// you should call the function here
generateMFCC(chosenFile);
}
});
fileDialog.showDialog();
}
think that should solve your issue, right now generateMFCC(chosenFile); is called irrespective of file being chosen
*before file is selected
I'm pretty new here, and have been following all I could find on getting my program to append a series of numbers (determined from how often a button was pressed) to a .txt file whenever a timer runs out, but to no avail-I'm not sure what I'm missing...the app starts out by creating a .txt file in the downloads folder with a template in it:
String initialTemplate ="\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\"";
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, filename+".txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(initialTemplate.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And then when a countdowntimer object finishes and restarts/ends, it triggers the class writeresults() to append the values:
if (CountsRemaining < 1){
textViewTime.setText("00:00:00");
cancel();
writeResults();
finishcount();
} else {
//append data
writeResults();
//Clear all variables
clearCounts();
start();
}
And the important part, to actually write the data, which is what isn't working:
public void writeResults(){
String Message = Count1 + ", " + Count2 + ", " + Count3 + ", " + Count4 + ", " + Count5 + ", " +
Count6 + ", " + Count7 + ", " + Count8 + ", " + Count9 + ", " + Count10 + ", " + Count11 + Count12;
FileWriter writer;
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File (path + filename+".txt");
writer = new FileWriter(file, true);
writer.append(Message);
writer.append("this is a writing test message");
writer.close();
Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Any idea what I might be missing? Parameters?
The problem is in this line:
File file = new File (path + filename+".txt");
It should be like this, if you look at your first code, when creating file:
File file = new File (path, filename+".txt");
I working on android csv file reading library. I create a function in library and calling it in other project. The library function reads the csv file ( which is in the assets folder of my project which is extended from library class ) ,store the name and value in strings GotDbname and GotDbValue respectively . But it is not returning anything. Any type help will be appreciated.
public class ReadFile extends Activity {
String GetDbName = "DBName";
String GetDbVersion = "DbVersion";
String GotDbName;
String GotDbVersion;
HashMap<String, String> DatabaseMap = new HashMap<String, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public void hello() {
Log.d("Library Is working ", "Hello ");
}
public HashMap<String, String> read(Context con, String name, String version) {
Log.d("Read File", "Getting Assest Manager");
AssetManager assetManager = con.getAssets();
Log.d("Read File", "Assest Manager Object Created");
if (assetManager == null) {
Log.d("Reading file", "Nothing in assets");
}
else {
InputStream inputStream = null;
Log.d("Read File", "Getting input Stream");
try {
Log.d("Read File", "Getting File");
inputStream = assetManager.open("Db.csv");
Log.d("Read File", "File read");
String text = loadTextFile(inputStream);
String[] text1 = text.split(",");
Log.d("Read File", "LoadTextFile" + text + " " + text1);
String id[] = new String[text1.length];
String value[] = new String[text1.length];
Log.d("Read File", "Getting Strings" + "DbName " + id
+ "DbVersion " + value);
int c = 0;
for (int i = 0; i < text1.length; i += 2)
{
id[c] = text1[i].replace('"', ' ');
Log.d("Read File", "Getting Db name" + " " + id[c]);
c++;
}
int d = 0;
for (int i = 1; i < text1.length; i += 2)
{
value[d] = text1[i].replace('"', ' ');
Log.d("Read File", "Getting getting Version" + " "
+ value[d]);
d++;
}
int indexofid = -1;
for (int i = 0; i < id.length; i++) {
Log.d("Reading CSV", "In for Loop");
if (GetDbName.equals(id[i].trim())) {
indexofid = i;
GotDbName = value[indexofid].toString();
Log.d("Read File final", "Getting Db Name" + " "
+ GotDbName);
break;
}
}
for (int i = 0; i < id.length; i++) {
if (GetDbVersion.equals(id[i].trim())) {
indexofid = i;
GotDbVersion = value[indexofid].toString();
Log.d("Read File final", "Getting Db Version" + " "
+ GotDbVersion);
break;
}
}
} catch (IOException e) {
Log.d("Read File", "No file found");
}
}
DatabaseMap.put(name, GotDbName);
DatabaseMap.put(version, GotDbVersion);
Log.d("Read File", " Database Name =" + GotDbName
+ "Database Version =" + GotDbVersion);
return DatabaseMap;
}
public String loadTextFile(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int len = 0;
while ((len = inputStream.read(bytes)) > 0)
byteStream.write(bytes, 0, len);
return new String(byteStream.toByteArray(), "UTF8");
}
}
And here is the class of other project which is using that library
public class MainClass extends ReadFile {
String DbName;
String DbVersion;
String a, b;
TextView txt_dbName, txt_version;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_dbName = (TextView) findViewById(R.id.txt_dbName);
txt_version = (TextView) findViewById(R.id.txt_version);
HashMap<String, String> map = new HashMap<>();
map = read(this, DbName, DbVersion);
String abc = map.get("name");
Log.d("Main Class", "Map =" + abc);
Log.d("MainClass", "DbName = " + DbName + ": DbVersion = "
+ DbVersion);
txt_dbName.setText(DbName);
txt_version.setText(DbVersion);
}
}
String DbName;
String DbVersion;
...
map = read(this, DbName, DbVersion);
//The DbName and DbVersion is null or empty?
public HashMap<String, String> read(Context con, String name, String version) {
...
DatabaseMap.put(name, GotDbName); // If name is null, how to get?
DatabaseMap.put("name", GotDbName); // Maybe
DatabaseMap.put(version, GotDbVersion);
Log.d("Read File", " Database Name =" + GotDbName
+ "Database Version =" + GotDbVersion);
return DatabaseMap;
}
in my program I would like the user to name their project whatever they would like. So what I need is some way to have the program make a new folder called What ever the user wants. the way I'd like it to happen is by useing a String which I can put in the already existing code to make the new folder.
package com.AlexAdams.SimpleHTML.Program;
import java.io.File;
import com.AlexAdams.SimpleHTML.PopUps.SimpleHTMLDirctoryError;
public class MainFrameCreateMenuCreateNewProject {
public static boolean programDirctory = false;
public MainFrameCreateMenuCreateNewProject() {
/*"SimpleHTML" MAIN FILE DIRCTORY*/
String simpleHTMLpath = System.getProperty("user.home") + File.separator + "Documents";
simpleHTMLpath += File.separator + "SimpleHTML";
File SimpleHTML = new File(simpleHTMLpath);
if (SimpleHTML.exists()) {
System.out.println(SimpleHTML + " Dirctory already exists");
programDirctory = true;
} else if (SimpleHTML.mkdirs()) {
System.out.println(SimpleHTML + " Dirctory was created");
programDirctory = true;
} else {
System.out.println(SimpleHTML + " Dirctory was not created");
programDirctory = false;
new SimpleHTMLDirctoryError();
}
if (programDirctory = true) {
/*"SimpleHTML User Defined Project Name"*/
String simpleHTMLprojectpath = System.getProperty("user.home") + File.separator + "SimpleHTML";
simpleHTMLprojectpath += File.separator + ""; // Put the code for the users name of there project
File /*String of user input from JTextField*/ = new File(simpleHTMLprojectpath);
if (/*Code of user definedprojectname*/.exists()) {
System.out.println(" Project name already exists");
} else if (/*Code of user definedprojectname*/.mkdirs()) {
System.out.println(" New project was created");
} else {
System.out.println(" New project could not be created");
}
} else if (programDirctory = false) {
System.out.println(" Project could not be created. This may be due to the fact that there is a error with the programs main file dirctroy.");
}
}
}
First off, you have a logic error...
if (programDirctory = true) {
Will always be true as you assigning true to programDirctory before the if statement evaluates it.
Better to use
if (programDirctory) {
The same thing goes for else if (programDirctory = false), but considering that the value is either true or false, there are only two states available, so you can shorten this to...
if (programDirctory) {
//...
} else {
//...
}
If you want to supply a variable value, then you need to provide a parameter to your constructor...
For example...
public MainFrameCreateMenuCreateNewProject(String userPath) {
/*"SimpleHTML" MAIN FILE DIRCTORY*/
String simpleHTMLpath = System.getProperty("user.home") + File.separator + "Documents";
simpleHTMLpath += File.separator + "SimpleHTML";
File SimpleHTML = new File(simpleHTMLpath);
if (SimpleHTML.exists()) {
System.out.println(SimpleHTML + " Dirctory already exists");
programDirctory = true;
} else if (SimpleHTML.mkdirs()) {
System.out.println(SimpleHTML + " Dirctory was created");
programDirctory = true;
} else {
System.out.println(SimpleHTML + " Dirctory was not created");
programDirctory = false;
throw new IOException(SimpleHTML + " does not exist and could not be created");
}
if (programDirctory) {
/*"SimpleHTML User Defined Project Name"*/
String simpleHTMLprojectpath = simpleHTMLpath +
File.separator +
userPath; // Put the code for the users name of there project
File userProject = new File(simpleHTMLprojectpath);
if (userProject.exists()) {
System.out.println(" Project name already exists");
} else if (userProject.mkdirs()) {
System.out.println(" New project was created");
} else {
System.out.println(" New project could not be created");
}
}
}
Then you would simply call it using something like...
new MainFrameCreateMenuCreateNewProject("MyProject");
But to me, this seems a bit pointless, as the class doesn't do anything. A better solution might be to make a static method instead...
public class MainFrameCreateMenuCreateNewProject {
public static void createUserFolder(String userPath) {
boolean programDirctory = false;
//...etc...
}
}
Which would allow you to use...
MainFrameCreateMenuCreateNewProject.createUserFolder("MyProject");
The next problem is, what to do if you couldn't create the folder for some reason? You could return a boolean, but that doesn't really mean much, instead, it might be better to throw a IOException, for example...
public static void createNewProjectPath(String userPath) throws IOException {
/*"SimpleHTML" MAIN FILE DIRCTORY*/
String simpleHTMLpath = System.getProperty("user.home") + File.separator + "Documents";
simpleHTMLpath += File.separator + "SimpleHTML";
File SimpleHTML = new File(simpleHTMLpath);
if (SimpleHTML.exists()) {
System.out.println(SimpleHTML + " Dirctory already exists");
programDirctory = true;
} else if (SimpleHTML.mkdirs()) {
System.out.println(SimpleHTML + " Dirctory was created");
programDirctory = true;
} else {
System.out.println(SimpleHTML + " Dirctory was not created");
programDirctory = false;
throw new IOException(SimpleHTML + " does not exist and could not be created");
}
if (programDirctory) {
/*"SimpleHTML User Defined Project Name"*/
String simpleHTMLprojectpath = simpleHTMLpath +
File.separator +
userPath; // Put the code for the users name of there project
File userProject = new File(simpleHTMLprojectpath);
if (userProject.exists()) {
System.out.println(" Project name already exists");
} else if (userProject.mkdirs()) {
System.out.println(" New project was created");
} else {
System.out.println(" New project could not be created");
throw new IOException(userProject + " does not exist and could not be created");
}
}
}
But, to be honest, you could probably simplify the code by doing something like...
public class MainFrameCreateMenuCreateNewProject {
public static void createNewProjectPath(String userPath) throws IOException {
createNewPath("SimpleHTML");
createNewPath(userPath);
}
public static void createNewPath(String path) throws IOException {
String fullPath = System.getProperty("user.home") + File.separator + "Documents";
fullPath += File.separator + path;
File filePath = new File(fullPath);
if (!filePath.exists() && !filePath.mkdirs()) {
throw new IOException(filePath + " does not exist and could not be created");
}
}
}
Simply asking, is this what you want?
public MainFrameCreateMenuCreateNewProject(String ProjectName) {
/*"SimpleHTML" MAIN FILE DIRCTORY*/
String simpleHTMLpath = System.getProperty("user.home") + File.separator + "Documents";
simpleHTMLpath += File.separator + ProjectName;
File SimpleHTML = new File(simpleHTMLpath);
if (SimpleHTML.exists()) {
System.out.println(SimpleHTML + " Dirctory already exists");
programDirctory = true;
} else if (SimpleHTML.mkdirs()) {
System.out.println(SimpleHTML + " Dirctory was created");
programDirctory = true;
} else {
System.out.println(SimpleHTML + " Dirctory was not created");
programDirctory = false;
throw new SimpleHTMLDirctoryException("Error in creating directory");
}
if (programDirctory) {
/*"SimpleHTML User Defined Project Name"*/
String simpleHTMLprojectpath = System.getProperty("user.home") + File.separator + ProjectName;
simpleHTMLprojectpath += File.separator + ProjectName; // Put the code for the users name of there project
File /*String of user input from JTextField*/ file = new File(simpleHTMLprojectpath);
if (file.exists()) {
System.out.println(" Project name already exists");
} else if (file.mkdirs()) {
System.out.println(" New project was created");
} else {
System.out.println("New project could not be created");
}
} else {
System.out.println(" Project could not be created. This may be due to the fact that there is a error with the programs main file dirctroy.");
}
}
If so, can't you just replace the String with a variable, and pass it as the argument in the constructor?
I creating apps with camera function, I call camera with intent snap the shot and saving files in external storage "download" folder, but then I search them they are in another folder "/storage/emulated/0/download/".
Why android needs 2 directors? With same files excep my saved photos.
I'm using Galaxy Nexus phone. For Galaxy tablet everything is allright.
public void openCamera(View view) {
try {
int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1991;
photoName();
String _path = Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE) + "/" + photoFileName;
System.out.println("PATH: "+ _path);
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
}
private String photoName() {
boolean isWhile = true;
int randomId = 0;
int count = 0;
while (isWhile) {
photoFileName = "MobiliSkaita_" + count + ".jpg";
File fileToCheck = new File(Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE) + "/" + photoFileName);
if (fileToCheck.exists()) {
System.out.println("FAILAS YRA: " + randomId);
randomId++;
photoFileName="MobiliSkaita_" + randomId + ".jpg";
} else {
System.out.println("FAILAS NERA: " + randomId);
isWhile = false;
}
count++;
}
return photoFileName;
From http://developer.android.com/guide/topics/data/data-storage.html#filesExternal, some devices use different directories for external storage.
You should try (API >= 8):
Context.getExternalFilesDir();
or (API < 8)
Context.getExternalStorageDirectory();
to get the external storage directory on the current device (assuming it is mounted).