Create file from drawable to send with sendbird - android

I want use sendFileMessage in sendbird api. It need file value and I want use this file from drawable (or assets). sendBird API
this is snipped code from sendbird
Hashtable<String, Object> info = Helper.getFileInfo(getActivity(), uri);
final String path = (String) info.get("path");
File file = new File(path);
String name = file.getName();
String mime = (String) info.get("mime");
int size = (Integer) info.get("size");
sendFileMessage(file, name, mime, size, "", new BaseChannel.SendFileMessageHandler() {
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
return;
}
mAdapter.appendMessage(fileMessage);
mAdapter.notifyDataSetChanged();
}
});
This code working well which I got uri from open image intent. but I want to use to other purpose and I want to replace this code
File file = new File(path);
become something like
File file = new File(<path or uri from drawable or assets>);
I have tried with uri
Uri uri = Uri.parse("android.resource://com.package.name/raw/filenameWithoutExtension");
File file = new File(uri.getPath());
with inputStream
try {
File f=new File("file name");
InputStream inputStream = getResources().openRawResource(R.raw.myrawfile);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
always failed in getting file and return error code ERR_REQUEST_FAILED 800220

Have you tried like below?
String fileName = FILE_NAME;
File cachedFile = new File(this.getActivity().getCacheDir(), fileName);
try {
InputStream is = getResources().openRawResource(R.raw.sendbird_ic_launcher);
FileOutputStream fos = new FileOutputStream(cachedFile);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
fos.write(buf, 0, len);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
groupChannel.sendFileMessage(cachedFile, fileName, "image/jpg", (int) cachedFile.length(), "", new BaseChannel.SendFileMessageHandler() {
#Override
public void onSent(FileMessage fileMessage, SendBirdException e) {
}
});
This works for me.

Related

Read,Write,Delete Specific text from json file

I am currently developing an application that reads,writes,updates,deletes json file.i have 4 json files namely data.json(to store name,address,area,pin),image.json(to store image name),location.json(to store latitute,longitude) and final.json that merges the above json files.final.json will combine all data from 3 files to make a single record.In a activity I need to read the name,date,time of all records stored in final.json in different radio buttons. I am unable to read only the name,date,time from a record stored in temp.json as temp.json contains latitute,longitude,image name,name,address,pin,area,date,time.Please help me do the following.Also I need to delete only specific record from temp.json file.
This is the code I used to read the text from temp.json.How to read only name,date,time from the file.I am able to read all the parameters
My temp.json looks like
{Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22"]} {Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22" ]}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File file = new File(myDir, FILENAME);//making a new file in the folder
if(file.exists()) // check if file exist
{
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
String x=text.toString();
String z=x.replace("{","").replace("date:","").replace("time:","").replace("Record:","").replace("[","").replace("latitude:","").replace("longitude:","").replace("name:","").replace("address:","").replace("pin:","").replace("area:","").replace("image:","").replace("\"","").replace("]","").replace("}","");
String[] y=z.split(",");
//rb1.setText(y[3].toString()+","+y[7].toString()+","+y[8].toString()+""+"");
// rb2.setText(y[11].toString()+","+y[15].toString()+","+y[16].toString());
//rb3.setText(y[19].toString()+","+y[23].toString()+","+y[24].toString());
//rb4.setText(y[27].toString()+","+y[31].toString()+","+y[32].toString());
}
else
{
rb1.setText("Sorry file doesn't exist!!");
}
///////merge code////
static class CopyFileContent {
public static void main(String[] args) {
JSONObject jsonObj2 = new JSONObject();
try {
// Here we convert Object to JSON
jsonObj2.put("date",a.toString());jsonObj2.put("time",c.toString());// Set the first name/pair
} catch (JSONException ex) {
ex.printStackTrace();
}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File destFile = new File(myDir, FILENAME11);//making a new file in the folder
/* Source file, from which content will be copied */
File sourceFile1 = new File(myDir,FILENAME12);
File sourceFile2 = new File(myDir,FILENAME13);
File sourceFile3 = new File(myDir,FILENAME14);
/* destination file, where the content to be pasted */
// File destFile = new File(FILENAME);
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;
OutputStream output = null;
InputStream input4=null;
try {
/* FileInputStream to read streams */
input1 = new FileInputStream(sourceFile1);
input2 = new FileInputStream(sourceFile2);
input3 = new FileInputStream(sourceFile3);
/* FileOutputStream to write streams */
output = new FileOutputStream(destFile,true);
byte[] buf = new byte[1024];
int bytesRead;
output.write("{Record:[".getBytes());
while ((bytesRead = input1.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input2.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input3.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
output.write(jsonObj2.toString().getBytes());
output.write("]}".getBytes());
output.write("\r\n".getBytes());
output.write("\r\n".getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (null != input1) {
input1.close();
}
if (null != input2) {
input2.close();
}
if (null != input3) {
input3.close();
}
if (null != output) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Android created Zip does not hold contained file sizes

I have put in place the ability to archive user data for my application by creating a compressed file.
I create the compressed file like this :
try
{
int iBufferSize = 2048;
int iByteCount = 0;
byte btData[] = new byte[iBufferSize];
File fZipFile = new File(ARCHIVE_FILE);
FileOutputStream fos = new FileOutputStream(fZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
BufferedInputStream bis = null;
FileInputStream fIn = null;
ZipEntry ze = null;
File[] fPartitions = new File(FILES_PATH).listFiles();
for(File fPartition : fPartitions)
{
lFileSize = fPartition.length();
fIn = new FileInputStream(fPartition);
bis = new BufferedInputStream(fIn, iBufferSize);
ze = new ZipEntry(fPartition.getName());
ze.setSize(lFileSize);
zos.putNextEntry(ze);
while((iByteCount = bis.read(btData, 0, iBufferSize)) != -1)
{
zos.write(btData, 0, iByteCount);
}
bis.close();
zos.closeEntry();
}
zos.close();
bis.close();
fIn.close();
bOk = true;
}
catch(Exception e)
{
e.printStackTrace();
}
Now, when I try to restore the contents, I am not able to get the original file size. Here is how I am doing the expansion :
try
{
// open the archive
FileInputStream fis = new FileInputStream(fArchive);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
bBuffer = new byte[2048];
// iterate through all files, putting them back into the same place
ze = zis.getNextEntry();
while(ze != null)
{
strFileName = ze.getName();
strFileName = FILE_PATH + "/" + strFileName;
fCheck = new File(strFileName);
lZipFileSize = ze.getSize(); // <--- returns -1 systematically
lTargetFileSize = fCheck.length();
fCheck = null;
FileOutputStream fos = new FileOutputStream(strFileName);
// read the data
while((iCount = zis.read(bBuffer)) != -1)
{
fos.write(bBuffer, 0, iCount);
}
fos.close();
ze = zis.getNextEntry();
}
zis.close();
fis.close();
bOk = true;
}
catch(Exception e)
{
e.printStackTrace();
}
I have noted that ze.getSize() is returning -1 systematically.
How can I store and get the individual file sizes ?
Ok, so if you come across this problem, here is how I worked around it.
Use the ZipFile class for reading the zip file.
Inspired from ZipInputStream: getting file size of -1 when reading and The ZipFileTest.java Android example source code

How to copy a file to another directory programmatically?

There is an image file inside a directory. How to copy this image file into another directory that was just created ? The two directories are on the same internal storage of the device :)
You can use these functions. The first one will copy whole directory with all children or a single file if you pass in a file. The second one is only usefull for files and is called for each file in the first one.
Also note you need to have permissions to do that
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Functions:
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
If you want to copy image programtically then use following code.
File sourceLocation= new File (sourcepath);
File targetLocation= new File (targetpath);
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
** Use FileUtils This Is Simple Fast And Best method and Download Jar file from here**
public void MoveFiles(String sourcepath) {
File source_f = new File(sourcepath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsappStatus/yourfilename.mp4";
File destination = new File(destinationPath);
try
{
FileUtils.copyFile(source_f , destination);
}
catch (IOException e)
{
e.printStackTrace();
}
}
Go To Link For FileUtils Jar

File writing in external storage device is not working

I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}

Extrakting Zip to SD-Card is very slow. How can i optimize performance?

my app downloads a zip with about 350 files. A mix of JPG and HTML files. The function i wrote to do it works just fine but the unzipping takes for ever.
At first i thought the reason might be that writing to the sd-card is slow. but when i unzip the same zip with an other app on my phone it works much faster. is there anything that i could do to optimize it?
here is the code:
private void extract() {
try {
FileInputStream inStream = new FileInputStream(targetFilePath);
ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(inStream));
ZipEntry entry;
ZipFile zip = new ZipFile(targetFilePath);
//i know the contents for the zip so i create the dirs i need in advance
new File(targetFolder).mkdirs();
new File(targetFolder + "META-INF").mkdir();
new File(targetFolder + "content").mkdir();
int extracted = 0;
while((entry = zipStream.getNextEntry()) != null) {
if (entry.isDirectory()) {
new File(targetFolder + entry.getName()).mkdirs();
} else {
FileOutputStream outStream = new FileOutputStream(targetFolder + entry.getName());
for (int c = zipStream.read(); c != -1; c = zipStream.read()) {
outStream.write(c);
}
zipStream.closeEntry();
outStream.close();
extracted ++;
}
publishProgress(""+(int)extracted*100/zip.size());
}
zipStream.close();
inStream.close();
//
new File(targetFilePath).delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
thanks to CommonsWare i modified my code like this:
int size;
byte[] buffer = new byte[2048];
FileOutputStream outStream = new FileOutputStream(targetFolder + entry.getName());
BufferedOutputStream bufferOut = new BufferedOutputStream(outStream, buffer.length);
while((size = zipStream.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, size);
}
bufferOut.flush();
bufferOut.close();
big performance difference.
Thanks a lot.
You are reading and writing a byte at a time. Consider reading and writing a larger block at a time.
Just use this method once and believe me its a super fast process.. It will unzip all the files without skipping any file with in 1 second.
public boolean rajDhaniSuperFastUnzip(String inputZipFile, String destinationDirectory)
{
try {
int BUFFER = 2048;
List<String> zipFiles = new ArrayList<String>();
File sourceZipFile = new File(inputZipFile);
File unzipDestinationDirectory = new File(destinationDirectory);
unzipDestinationDirectory.mkdir();
ZipFile zipFile;
zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
Enumeration<?> zipFileEntries = zipFile.entries();
while (zipFileEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(unzipDestinationDirectory, currentEntry);
if (currentEntry.endsWith(".zip")) {
zipFiles.add(destFile.getAbsolutePath());
}
File destinationParent = destFile.getParentFile();
destinationParent.mkdirs();
try {
if (!entry.isDirectory()) {
BufferedInputStream is =
new BufferedInputStream(zipFile.getInputStream(entry));
int currentByte;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest =
new BufferedOutputStream(fos, BUFFER);
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
zipFile.close();
for (Iterator<String> iter = zipFiles.iterator(); iter.hasNext();) {
String zipName = (String)iter.next();
doUnzip(
zipName,
destinationDirectory +
File.separatorChar +
zipName.substring(0,zipName.lastIndexOf(".zip"))
);
}
} catch (IOException e) {
e.printStackTrace();
return false ;
}
return true;
}
Hope this will help you.. Happy Coding :)

Categories

Resources