Error For Below code - android

Getting Error for the below package:
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Cell;
can any help me for the below code to resolve the error.
public class AndroidReadExcelActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View writeButton = findViewById(R.id.write);
writeButton.setOnClickListener(this);
View readButton = findViewById(R.id.read);
readButton.setOnClickListener(this);
View writeExcelButton = findViewById(R.id.writeExcel);
writeExcelButton.setOnClickListener(this);
View readExcelButton = findViewById(R.id.readExcel);
readExcelButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.write:
saveFile(this,"myFile.txt");
break;
case R.id.read:
readFile(this,"myFile.txt");
break;
case R.id.writeExcel:
saveExcelFile(this,"myExcel.xls");
break;
case R.id.readExcel:
readExcelFile(this,"myExcel.xls");
break;
}
}
private static boolean saveFile(Context context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.w("FileUtils", "Storage not available or read only");
return false;
}
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
PrintStream p = null; // declare a print stream object
boolean success = false;
try {
OutputStream os = new FileOutputStream(file);
// Connect print stream to the output stream
p = new PrintStream(os);
p.println("This is a TEST");
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != p)
p.close();
} catch (Exception ex) {
}
}
return success;
}
private static void readFile(Context context, String filename) {
if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
{
Log.w("FileUtils", "Storage not available or read only");
return;
}
FileInputStream fis = null;
try
{
File file = new File(context.getExternalFilesDir(null), filename);
fis = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Log.w("FileUtils", "File data: " + strLine);
Toast.makeText(context, "File Data: " + strLine , Toast.LENGTH_SHORT).show();
}
in.close();
}
catch (Exception ex) {
Log.e("FileUtils", "failed to load file", ex);
}
finally {
try {if (null != fis) fis.close();} catch (IOException ex) {}
}
return;
}
private static boolean saveExcelFile(Context context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.w("FileUtils", "Storage not available or read only");
return false;
}
boolean success = false;
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c = null;
//Cell style for header row
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("myOrder");
// Generate column headings
Row row = sheet1.createRow(0);
c = row.createCell(0);
c.setCellValue("Item Number");
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue("Quantity");
c.setCellStyle(cs);
c = row.createCell(2);
c.setCellValue("Price");
c.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
sheet1.setColumnWidth(2, (15 * 500));
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
private static void readExcelFile(Context context, String filename) {
if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
{
Log.w("FileUtils", "Storage not available or read only");
return;
}
try{
// Creating Input Stream
File file = new File(context.getExternalFilesDir(null), filename);
FileInputStream myInput = new FileInputStream(file);
// Create a POIFSFileSystem object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator<Row> rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
Log.w("FileUtils", "Cell Value: " + myCell.toString());
Toast.makeText(context, "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT).show();
}
}
}catch (Exception e){e.printStackTrace(); }
return;
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}

You need to Import Apache POI library
Tutorial using this library can be found here
Go through the official website for latest library release and go through this answer as well.
Jar Download URL click on any mirror link under HTTP.

public class AndroidReadExcelActivity
reemplaced for name your archive JAVA for example mainActivity

Related

com.googlecode.mp4parser fails for mp3 audio file?

I am using the com.googlecode.mp4parser library to merge audio files. I have an external audio mp3 file which I store in raw resources. This file fails to merge due to following exception, Below is my code :
Reading a file from raw folder :
InputStream is = context.getResources().openRawResource(R.raw.my_mp3_file);
OutputStream output = null;
try {
File file = new File(context.getFilesDir(), "silence.mp3");
if(!file.exists()) {
file.createNewFile();
}
output = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = is.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
output.close();
fileReference= file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace(); // handle exception, define IOException and others
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Code that reads movie ( Which is failing ) :
if(fileReference.exists()) {
Movie m = new MovieCreator().build(fileReference.getAbsolutePath());
}
While getting this Movie m my code fails throwing the exception :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.coremedia.iso.boxes.MovieBox.getBoxes(java.lang.Class)' on a null object reference
It works for some mp3 files fails for raw resource files ? What's wrong here ?
Here are my conclusion and solution after a lot of research
MP4Parser for merging audio and video only use .m4a extension
String root = Environment.getExternalStorageDirectory().toString();
String audio = root + "/" + "tests.m4a";
String video = root + "/" + "output.mp4";
String output = root + "/" + "aud_vid.mp4";
mux(video, audio, output);
and here is the method
public boolean mux(String videoFile, String audioFile, String outputFile) {
Movie video;
try {
video = new MovieCreator().build(videoFile);
} catch (RuntimeException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Movie audio;
try {
audio = new MovieCreator().build(audioFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Track audioTrack = audio.getTracks().get(0);
video.addTrack(audioTrack);
Container out = new DefaultMp4Builder().build(video);
FileOutputStream fos;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
try {
out.writeContainer(byteBufferByteChannel);
byteBufferByteChannel.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private static class BufferedWritableFileByteChannel implements WritableByteChannel {
private static final int BUFFER_CAPACITY = 1000000;
private boolean isOpen = true;
private final OutputStream outputStream;
private final ByteBuffer byteBuffer;
private final byte[] rawBuffer = new byte[BUFFER_CAPACITY];
private BufferedWritableFileByteChannel(OutputStream outputStream) {
this.outputStream = outputStream;
this.byteBuffer = ByteBuffer.wrap(rawBuffer);
}
#Override
public int write(ByteBuffer inputBuffer) throws IOException {
int inputBytes = inputBuffer.remaining();
if (inputBytes > byteBuffer.remaining()) {
dumpToFile();
byteBuffer.clear();
if (inputBytes > byteBuffer.remaining()) {
throw new BufferOverflowException();
}
}
byteBuffer.put(inputBuffer);
return inputBytes;
}
#Override
public boolean isOpen() {
return isOpen;
}
#Override
public void close() throws IOException {
dumpToFile();
isOpen = false;
}
private void dumpToFile() {
try {
outputStream.write(rawBuffer, 0, byteBuffer.position());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Seem like this issue happens because Google devs have forgotten to handle that NullPointerException case. After several hours diving into the code base, I finally found the solution and It works very fine, you can try this:
Movie movie;
try{
movie = MovieCreator.build(videoPath);
}catch(NullPointerException e){
Log.d("AsyncTask", "Catch null getMovieBoxes");
FileDataSourceImpl fileDataSource = new FileDataSourceImpl(new File(videoPath));
IsoFile isoFile = new IsoFile(fileDataSource);
List<TrackBox> trackBoxes = isoFile.getBoxes(TrackBox.class);
for (TrackBox trackBox : trackBoxes) {
SchemeTypeBox schm = Path.getPath(trackBox, "mdia[0]/minf[0]/stbl[0]/stsd[0]/enc.[0]/sinf[0]/schm[0]");
if (schm != null && (schm.getSchemeType().equals("cenc") || schm.getSchemeType().equals("cbc1"))) {
movie.addTrack(new CencMp4TrackImplImpl(fileDataSource.toString() + "[" + trackBox.getTrackHeaderBox().getTrackId() + "]", trackBox));
} else {
movie.addTrack(new Mp4TrackImpl(fileDataSource.toString() + "[" + trackBox.getTrackHeaderBox().getTrackId() + "]" , trackBox));
}
}
}

Retrofit 2 download image and save to folder

I need to download image from server and save it to folder, so I am using Retrofit 2.
Problem is that saved images is empty when I look for it in folder and I tried to debug and saw that Bitmap is null.
I do not get why, here is my code:
#GET("images/{userId}/{imageName}")
#Streaming
Call<ResponseBody> downloadImage(#Path("userId") String userId, #Path("imageName") String imageName);
Download image code:
private void downloadImage(final int position) {
String url = "htttp://myserver.com/";
retrofitImage = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
imageApi = retrofitImage.create(BlastApiService.class);
String userId = feedList.get(position).getUserId();
String fileName = feedList.get(position).getFile();
Call<ResponseBody> imageCall = imageApi.downloadImage(userId, fileName );
imageCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccess()){
String fileName = feedList.get(position).getFile();
InputStream is = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
saveImage1(bitmap, fileName);
} else{
try {
Log.d("TAG", "response error: "+response.errorBody().string().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "Image download error: " + t.getLocalizedMessage());
}
});
}
Here is method to save image.
private void saveImage1(Bitmap imageToSave, String fileName) {
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/FOLDER_NAME/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
counter++;
// if (counter < feedList.size()) {
//downloadImage(counter);
//} else {
setImage();
//}
} catch (Exception e) {
e.printStackTrace();
}
}
This worked for me:
public static boolean writeResponseBody(ResponseBody body, String path) {
try {
File file = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
//long fileSize = body.contentLength();
//long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(file);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
//fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
after call this method you can get image from path:
boolean result = writeResponseBody(body, path);
if(result) {
Bitmap bitmap = BitmapFactory.decodeFile(path)
}
private boolean writeResponseBodyToDisk(ResponseBody body, String name) {
try {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/MyApp";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File futureStudioIconFile = new File(path, name + ".pdf");//am saving pdf file
if (futureStudioIconFile.exists())
futureStudioIconFile.delete();
futureStudioIconFile.createNewFile();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

Realm file created with Android in a project is not valid in Another

The realm version is the latest jar I compiled from source (github).
I am using an Android project to create a realm file from a json file.
In this project all seems well and the realm is fine. Here is the code:
public class MainActivity extends Activity {
private static final String REALM_DB_FILE = "categories.realm";
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(REALM_DB_FILE)
.setModules(new CurrencyModule())
.build();
Realm realm = Realm.getInstance(realmConfiguration);
RealmResults<RLMCategory> r = realm.where(RLMCategory.class).findAll();
if(r != null && r.size()> 0){
Log.d(TAG, "items : "+r.size());
realm.beginTransaction();
r.clear();
realm.commitTransaction();
Log.d(TAG, "items : " + r.size());
}
String json = getJsonStringFromRawFile(this, R.raw.categories);
try {
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("results");
for(int i = 0; i<arr.length(); i++){
realm.beginTransaction();
RLMCategory category = createFromJson((JSONObject) arr.get(i), i);
RLMCategory categoryRLM = realm.copyToRealm(category);
realm.commitTransaction();
}
} catch (JSONException e) {
Log.e(TAG, "onCreate");
}
String path = realm.getPath();
Log.d(TAG, "insert finished : path "+path);
r = realm.where(RLMCategory.class).findAll();
Log.d(TAG, "items : "+r.size());
for (RLMCategory category : r){
Log.d(TAG, toString(category));
}
realm.close();
sendDatabaseByEmail();
}
public void sendDatabaseByEmail() {
// init realm
// Realm realm = Realm.getInstance(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(REALM_DB_FILE)
.setModules(new CurrencyModule())
.build();
Realm realm = Realm.getInstance(realmConfiguration);
File exportRealmFile = null;
try {
// get or create an "export.realm" file
exportRealmFile = new File(getExternalCacheDir(), REALM_DB_FILE);
// if "export.realm" already exists, delete
exportRealmFile.delete();
// copy current realm to "export.realm"
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
realm.close();
// init email intent and add export.realm as attachment
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, "valeria#letgo.com");
intent.putExtra(Intent.EXTRA_SUBJECT, REALM_DB_FILE +" database");
intent.putExtra(Intent.EXTRA_TEXT, "datatabse");
Uri u = Uri.fromFile(exportRealmFile);
intent.putExtra(Intent.EXTRA_STREAM, u);
// start email intent
startActivity(Intent.createChooser(intent, "Send database"));
}
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public String toString(RLMCategory rlmCategory) {
return "RLMCategory{" +
"id=" + rlmCategory.getId() +
", name='" + rlmCategory.getName() + '\'' +
", description='" + rlmCategory.getDescription() + '\'' +
", image_src='" + rlmCategory.getImage_src() + '\'' +
", category_id=" + rlmCategory.getCategory_id() +
", name_dirify='" + rlmCategory.getName_dirify() + '\'' +
", objectId='" + rlmCategory.getObjectId() + '\'' +
'}';
}
#Nullable
public static String getJsonStringFromRawFile(Context context, int resId) {
InputStream is = context.getResources().openRawResource(resId);
return getJsonStringFromIS(is);
}
private static String getJsonStringFromIS(InputStream inputStream){
String jsonStr = null;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
if (inputStream == null) {
// Nothing to do.
jsonStr = null;
} else {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
jsonStr = null;
} else {
jsonStr = buffer.toString();
}
} catch (IOException e) {
Log.e(TAG, "getJsonStringFromIS", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}
return jsonStr;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static RLMCategory createFromJson(JSONObject obj, int id){
RLMCategory category = null;
try {
category = new RLMCategory();
category.setName(obj.getString("name"));
category.setId(id);
category.setCategory_id(obj.getInt("category_id"));
category.setDescription(obj.getString("description"));
category.setName_dirify(obj.getString("name_dirify"));
category.setImage_src(obj.getString("image"));
category.setObjectId(obj.getString("description"));
} catch (JSONException e) {
Log.e(TAG, "createFromJson : " +obj, e );
}
return category;
}
#RealmModule(classes = {RLMCategory.class})
public class CurrencyModule {
}
}
On my other project I am adding the categories.realm to raw folder and then I am copying it to a normal folder:
Utils.copyRealmDb(context, REALM_DB_FILE, CATEGORIES_RES);
RealmConfiguration realmConfiguration2 = new RealmConfiguration.Builder(context)
.name(REALM_DB_FILE)
.setModules(new CategoryModule())
.build();
this.realm = Realm.getInstance(realmConfiguration2); //crash here
}
public static void copyRealmDb(Context context, String realmDbFile, #RawRes int rarResFile) {
File f = context.getFilesDir();
File targetFile = new File(f, realmDbFile);
if(targetFile.exists()){
targetFile.delete();
}
if(!targetFile.exists()){
InputStream is = context.getResources().openRawResource(rarResFile);
FileOutputStream os = null;
try {
os = new FileOutputStream(targetFile);
copyStream(is, os);
} catch (FileNotFoundException e) {
Timber.e(e, "Unable to copy database from raw");
} finally {
try {
if(is != null){
is.close();
}
} catch (IOException e) {
Timber.e(e, "Unable to close inputStream");
}
try {
if(os != null){
os.close();
}
} catch (IOException e) {
Timber.e(e, "Unable to close outputStream");
}
}
}
}
I get a crash on trying to get the instance of the database and the error I get is:
Caused by: java.lang.IllegalArgumentException: Illegal Argument: Invalid format of Realm file.
at io.realm.internal.SharedGroup.createNativeWithImplicitTransactions(Native Method)
at io.realm.internal.SharedGroup.<init>(SharedGroup.java:60)
at io.realm.Realm.<init>(Realm.java:189)
at io.realm.Realm.createAndValidate(Realm.java:557)
at io.realm.Realm.create(Realm.java:525)
at io.realm.Realm.getInstance(Realm.java:498)
I have no idea how to fix it. Any ideas? Thks
EDIT: I am able to open the created realm file with a Mac and it seems fine.
EDIT 2: Here is the missing method:
public static void copyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}

java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)

File albumF = getVideoAlbumDir();
String path = albumF.getAbsolutePath();
// path =/storage/emulated/0/Pictures/.MyImages (Hidden folder)
// fileSelected.fileName()=IMG_20140417_113847.jpg
File localFile = new File(path + "/" + fileSelected.fileName());
Log.v("", "file exist===" + localFile.exists());
if (!localFile.exists()) {
Log.v("", "inside if===");
Log.v("", "Parent Filet===" + localFile.getParentFile());
localFile.getParentFile().mkdirs();
// localFile.createNewFile();
copy(fileSelected, localFile);
} else {
Log.v("", "inside else===");
mCurrentPhotoPath = localFile.getAbsolutePath();
uploadMediaFile();
}
This copy method copies data from dropbox file to my local storage.
private void copy(final Entry fileSelected, final File localFile) {
final ProgressDialog pd = ProgressDialog.show(ChatActivity.this,
"Downloading...", "Please wait...");
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
DropboxInputStream fd;
try {
fd = mDBApi.getFileStream(fileSelected.path,
localFile.getAbsolutePath());
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(
localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
pd.dismiss();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
android.os.Message msg = new android.os.Message();
msg.arg1 = 100;
if (msg.arg1 >= 100) {
progressHandler.sendMessage(msg);
mCurrentPhotoPath = localFile.getAbsolutePath();
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
I am creating file in a folder using localFile.getParentFile().mkdirs();
I got above error when I upload this file to server.
how to fix this?
If you've tried all other options - and problem still persists - then maybe you have a case when the file you want to create matches name of already existing directory.(which might be earlier created my some call to mkdirs() maybe accidentally).
Example:
You want to save file Test\test.pdf but you already have folder Test\Test.pdf\

Reading Arabic from UTF-8 encoded Text file in android?

I am working on an application in which I have a some text in English and Arabic. For the sake of example I can say it as a words meaning application. The word is in English and user will get it's meaning in Arabic.
For Example:
Test اختبار // Test is the word and then there is it's meaning in Arabic
But when I read this local file I don't get Arabic as intended. Instead I get some strange characters. I am making sure that file is UTF-8 encoded and when I read the file I again pass encoding scheme to be UTF-8..but it does not wwork. Code snippet is as follows:
InputStream inputStream = resources.openRawResource(R.raw.textfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
try {
String line;
while((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, " ");
if (strings.length < 2) continue;
addWord(strings[0].trim(), strings[1].trim());
}
} finally {
reader.close();
}
Any help is appreciated..Thanks..!!!
I actually built an helper class that handles FileIO (and is completely compatible with Hebrew) so I guess Arabic will be no problem:
/***
*
* #author Android Joker ©
* Do NOT copy without confirmation!
* Thanks!
*
*/
public class FileMethods {
private Boolean isOk;
private Context mContext;
private String fileName;
public FileMethods(Context c, String FILENAME) {
this.isOk = true;
this.mContext = c;
this.fileName = FILENAME;
}
public void reWrite(Object DATA) {
//For deleting the content of the file and then writing
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write(DATA.toString().getBytes());
fos.close();
Log.i("File Writing ("+this.fileName+")", "Success!");
isOk = true;
}
catch (IOException e) {
e.printStackTrace();
Log.e("File Writing ("+this.fileName+")", "Failed!");
isOk = false;
}
}
public void Write(Object DATA) {
//For keeping the previous contents and continue writing
String data = Read("") + DATA.toString() + "\n";
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
Log.i("File Writing ("+this.fileName+")", "Success!");
isOk = true;
}
catch (IOException e) {
e.printStackTrace();
Log.e("File Writing ("+this.fileName+")", "Failed!");
isOk = false;
}
}
public void Clear() {
//For deleting all the file contents
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write("".getBytes());
fos.close();
Log.i("Cleared"+"("+this.fileName+")", "Success!");
isOk = true;
}
catch (IOException e) {
e.printStackTrace();
Log.e("Cleared"+"("+this.fileName+")", "Failed!");
isOk = false;
}
}
public String Read(String inCaseOfFailure) {
//For reading (If reading failed for any reason, inCaseOfFailure will be written)
String info = "";
try {
FileInputStream fis = mContext.openFileInput(this.fileName);
byte[] dataArray = new byte[fis.available()];
if (dataArray.length>0) {
while(fis.read(dataArray)!=-1)
{
info = new String(dataArray);
}
fis.close();
Log.i("File Reading ("+this.fileName+")","Success!");
isOk = true;
}
else {
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write(inCaseOfFailure.getBytes());
fos.close();
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Success!");
isOk = true;
}
catch (Exception e) {
e.printStackTrace();
isOk = false;
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Failed!");
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "MOVING ON");
}
}
}
catch (FileNotFoundException e) {
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
if (inCaseOfFailure != null) {
fos.write(inCaseOfFailure.getBytes());
fos.close();
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Success!");
isOk = true;
}
else {
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Failed!");
isOk = false;
}
}
catch (IOException e1) {
e.printStackTrace();
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Failed!");
isOk = false;
}
}
catch (IOException e) {
e.printStackTrace();
Log.e("File Reading ("+this.fileName+")", "Failed!");
isOk = false;
}
return info;
}
public Boolean GetIsOK() {
//Method that checks whether the FileIO was successfully running or not
Boolean temp = isOk;
isOk = true;
return temp;
}
}
Each instance of the class handles another file (FILENAME).
Hope this helps!

Categories

Resources