I got in the data and converted them into what object I want and added them to the ArrayList which is ToDoItems(I've checked what I said above by Toast). Now I notified the adapter to fresh the screen. But error occurs. There's only one adapter and I created this method in the activity where this adapter is.
public void getImport(){
Gson gson = new Gson();
FileInputStream inStream = null;
File file = new File(getCacheDir(),"list1.txt");
try {strong text
String data = null;
inStream = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
inStream.read(fileContent);
data = new String(fileContent);
if(data == null){
Toast.makeText(this, "No data to import", Toast.LENGTH_LONG).show();
}
else{
todoItems.clear();
String[] token = data.split("$$");
for(int i = 0;i<token.length;i++){
todoItems.add(i, gson.fromJson(token[i], ToDoItem.class));
}
aa.notifyDataSetChanged();
}
inStream.close();
Toast.makeText(this, "Import Successfully", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "FileNotFoundException", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_LONG).show();
}
}
Related
This question already has answers here:
Android permission doesn't work even if I have declared it
(11 answers)
Closed 4 years ago.
I want to store Bitmap image in external storage but I am getting an error creating the file directory.
This is my code.
private void saveImage(Bitmap bitmap){
String root = Environment.getExternalStorageDirectory().toString();
File directory = new File(root + "/Wallpapers");
boolean wasSuccessful = directory.mkdirs();
if(!wasSuccessful){
Toast.makeText(context, "Error Creating directory", Toast.LENGTH_SHORT).show();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt();
String fname = "Wallpaper-"+n+".png";
File file = new File(directory, fname);
if (file.exists()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(context, "Wallpaper Saved Successfully", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Error Saving Wallpaper", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
I already write the permission in android manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I've already tried out many solutions but it cannot resolved my issue.
Writing simple example to store bitmapImage Image given as follows. please try it out ...
//Get file name and bitmapImage and call the method ()
//Bitmap bitmapImage = ImageUtil.getInstance().changeImageRotated(cameraUri, bitmapImage, ImageUtil.TypeMode.CAMERA);
//String fileName = String.valueOf(getCurrentTimeStamp());
//ImageUtil.getInstance().saveImage(bitmapImage, fileName);
//Here is function to save bitmap image to internal storage
public Boolean saveImage(Bitmap imageData, String fileName) {
String savePath = getFilePath(AppConst.getInstance().IMAGE_DIR_APPLY);
isPathMade(savePath);
File file = new File(savePath, fileName);
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
boolean keep = true;
try {
fileOutputStream = new FileOutputStream(file);
imageData.compress(Bitmap.CompressFormat.PNG, AppConst.getInstance().PARKING_APPLY_IMAGE_COMPRESS_QUALITY, fileOutputStream);
} catch (Exception e) {
keep = false;
} finally {
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (fileOutputStream != null){
fileOutputStream.close();
}
if (!keep) {
file.delete();
}
return true;
} catch (Exception e) {
Logger.e(TAG, "saveImageToCache Exception is " + e.toString());
}
}
return false;
}
I have an app that has to take a string, encode it into JSONObject format and write it into a JSON file in the SD. It all seems to be working fine apart from writing part. I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />command in my MANIFEST and that's my code
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String lines[] = importantemail.split("\\r?\\n");
// String firstLine = (lines[0]);
//String secondLine = (lines[1]);
// Toast.makeText(SignificantEmailActivity.this,firstLine + secondLine,Toast.LENGTH_SHORT).show();;
JSONObject jsonObject = makeJsonObject();
try{
Writer output = null;
File file = new File(Environment.getExternalStorageDirectory()+ "importantemail.json");
if (!file.exists()) {
file.mkdirs();
}
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
}
public JSONObject makeJsonObject()
{
JSONObject object = new JSONObject();
try {
object.put("Message ID", id);
object.put("Sender",accountStr);
object.put("Subject",subj);
object.put("E-mail:",importantemail);
}catch (JSONException e)
{
e.printStackTrace();
}
return object;
}
When I press the button I get this message from the Toast
"storage/emulated/0importantemail.json
Permission denied"
No idea why is that though
Tested, Hi replace few lines and this will fix your issue.
JSONObject jsonObject = makeJsonObject();
try{
Writer output = null;
File file = new File(Environment.getExternalStorageDirectory(), "importantemail.json");
if(file.isDirectory()){
file.delete();
}
if(!file.exists()){
file.createNewFile();
}
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
public JSONObject makeJsonObject()
{
JSONObject object = new JSONObject();
try {
object.put("Message ID", 5);
object.put("Sender","test");
object.put("Subject","test");
object.put("E-mail:","test");
}catch (JSONException e)
{
e.printStackTrace();
}
return object;
}
in 6.0 or later versions of android, you must give runtime permission. check this.
I get a warning stating that the result of cachePath.createNewFile(); is ignored. Otherwise the following code does not save an image to my phone. What can I do?
holder.messageImage.setOnLongClickListener(v -> {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Bitmap bitmap = ((BitmapDrawable) holder.messageImage.getDrawable()).getBitmap();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try {
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
Toast.makeText(mContext, "Image saved successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Log.w(getClass().toString(), e);
Toast.makeText(mContext, "Failed saving image", Toast.LENGTH_SHORT).show();
}
return false;
});
I download the image from my back end this way:
private void downloadMessageImage(ViewHolder holder, int position) {
ParseQuery<ParseObject> query = new ParseQuery<>(ParseConstants.CLASS_YEET);
query.whereEqualTo(ParseConstants.KEY_OBJECT_ID, mYeets.get(position).getObjectId());
query.findInBackground((user, e) -> {
if (e == null) for (ParseObject userObject : user) {
if (userObject.getParseFile("image") != null) {
String imageURL = userObject.getParseFile("image").getUrl();
/*Log.w(getClass().toString(), imageURL);*/
if (imageURL != null) {
holder.messageImage.setVisibility(View.VISIBLE);
Picasso.with(mContext)
.load(imageURL)
.placeholder(R.color.placeholderblue)
.into(holder.messageImage);
} else {
holder.messageImage.setVisibility(View.GONE);
}
}
}
});
}
The bitmap certainly does not exist: android.graphics.Bitmap#12d9cc4
to save an image I use the following code:
try {
signature.setDrawingCacheEnabled(true);
Bitmap bm = Bitmap.createBitmap(signature.getDrawingCache());
// Define params for save
File f = new File(Environment.getExternalStorageDirectory() + "/Cassiopea/momomorez/" + File.separator + "signature.png");
f.createNewFile();
FileOutputStream os = new FileOutputStream(f);
os = new FileOutputStream(f);
//compress to specified format (PNG), quality - which is ignored for PNG, and out stream
bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Toast.makeText(mContext, "Saving image OK", Toast.LENGTH_SHORT).show();
os.close();
}
catch (Exception e) {
Log.v("Gestures", e.getMessage());
e.printStackTrace();
}
Use this code to save a pattern in an image within an established folder.
I'm downloading a file that is stored on a remote server, I try to decrypt it using JNCryptor, and all goes well except that the file I have downloaded and store in the phone external storage is corrupted and I cannot open it. Can anyone tell me where im going wrong?
Im trying to get the InputStream from the file, decrypt it, and save the file on external storage.
Thanks
Here is my code:
private void downloadFile() {
final String FILE_URL = "https://www.google.com";
final String PASS = "password";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
Log.d(TAG, "starting");
JNCryptor cryptor = new AES256JNCryptor();
int count;
try {
URL url = new URL(FILE_URL);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
//decrypt istream
byte[] b = null;
byte[] data = null;
try {
b = new byte[input.available()];
input.read(b);
} catch (IOException e) {
Log.i("decrypt error", e.toString());
}
AES256JNCryptorOutputStream cryptorStream = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
cryptorStream = new AES256JNCryptorOutputStream(byteStream,
PASS.toCharArray());
} catch (CryptorException e) {
e.printStackTrace();
}
try {
cryptorStream.write(b);
cryptorStream.flush();
cryptorStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] encrypted = byteStream.toByteArray();
try {
data = cryptor.decryptData(encrypted, PASS.toCharArray());
Log.d(TAG, "decrypted");
} catch (InvalidHMACException e) {
e.printStackTrace();
} catch (CryptorException e) {
e.printStackTrace();
}
if (data != null) {
Log.d(TAG, "data is ok");
}
//end decryption
// Output stream
//test
FileOutputStream fos = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/temp.zip");
fos.write(data);
fos.close();
Log.d(TAG, "file saved ");
input.close();
Log.d(TAG, "done");
} catch (Exception e) {
Log.d(TAG, "Error: " + e.getMessage());
}
return null;
}
}.execute();
}
P.S. Im not getting any error or warning in logCat.
I have made an EditText and a Button. The click of the button should save the text from the EditTextinto the ArrayList. The ArrayList is then persisted to a file. Further clicks append the text from the EditText to the ArrayList and then the file. However, after saving the file, I can only retrieve the first item entered from the file. I want to retrieve the whole list in a comma-separated format.
Button Click code:
String filename =“abc.text”;
List arrlist = new ArrayList();
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String listtext = a1.getText().toString();
// a1 is edittext
if (listtext.equals("")) {
Toast.makeText(getApplicationContext(), "Enter product", Toast.LENGTH_SHORT).show();
} else {
arrlist.add(listtext);
a1.setText("");
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrlist);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
Retrieval of ArrayList from file:
List newarrList = new ArrayList();
FileInputStream fis = openFileInput(filename);
ObjectInputStream restore = new ObjectInputStream(fis);
newarrList= (ArrayList)restore.readObject();
restore.close();
String joined = TextUtils.join(", ", newarrList);
Toast.makeText(getApplicationContext(),joined,Toast.LENGTH_LONG).show();
// only the first item is displayed, not sure why
You keep adding ArrayList objects to the file using the ObjectInputStream. But you only read a single one out. I think you want to keep around a single ArrayList that you add the data to and then save that single ArrayList to the file whenever a click occurs instead of appending multiple ArrayLists for each entry.
List arrist = new ArrayList();
arrlist.add(listtext);
a1.setText("");
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
appending an ArrayList object with only one entry each time an onclick occurs
oos.writeObject(arrlist);
oos.close();
fos.close();
}...
If you want to keep your original code and the state is only held for a single Activity and no persistence between Activity changes/App restarts etc.. then this should work.
final String filename = "abc.text";
File file = new File(filename);
// moved out of onClickListener
final List arrlist = new ArrayList();
try {
// load the previous contents if it exists
FileInputStream fis = openFileInput(filename);
ObjectInputStream restore = new ObjectInputStream(fis);
ArrayList newArrList = (ArrayList) restore.readObject();
arrlist.addAll(newArrList);
restore.close();
fis.close();
} catch (FileNotFoundException e) {
// ignore, maybe log
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e)
e.printStackTrace()
}
b2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v
) {
String listtext = a1.getText().toString(); //a1 is edittext
if (listtext.equals("")) {
Toast.makeText(getApplicationContext(), "Enter product", Toast.LENGTH_SHORT).show();
} else {
arrlist.add(listtext);
a1.setText("");
try {
Change Context.MODE_APPEND to Context.MODE_PRIVATE otherwise we keep inflating the file with junk
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrlist);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
);
The other alternative is to not use the ObjectInputStream but just a straight FileOutputStream and append the String contents on each click.
You store(write) string into file, end the string with comma, and After reading__(read) split the result with "," which returns a String array. Make sure you are appending the string into file. ArrayList variable as global variable.
//global variable
List arrlist = new ArrayList();
......
//write to file
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String listtext = a1.getText().toString();
.....
arrlist.add(listtext);
.....
listtext = listtext + ",";
FileOutputStream fOut = openFileOutput("file name here", Context.MODE_APPEND);
fOut.write(listtext .getBytes());
fOut.close();
....
}
//reading from file
String fileContent = readFile();
String[] items = TextUtils.split(fileContent, ",");