I have json response in string datatype. I want to save this text to sharedpreferences but it neither gives me error nor save it to sharedpreferences.
but when I try to retrieve it gives me empty value and null pointer exception if I fetch its length. MY JSON REPONE is at
http://www.professionalhub.pk/recipe/webServices/recipe1.php
Use this class for your purpose with files ! Hope it will help you !
public class MyJSON {
static String fileName = "myBlog.json";
public static void saveData(Context context, String mJsonResponse) {
try {
FileWriter file = new FileWriter(context.getFilesDir().getPath() + "/" + fileName);
file.write(mJsonResponse);
file.flush();
file.close();
} catch (IOException e) {
Log.e("TAG", "Error in Writing: " + e.getLocalizedMessage());
}
}
public static String getData(Context context) {
try {
File f = new File(context.getFilesDir().getPath() + "/" + fileName);
//check whether file exists
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
return null;
}
}
}
Related
I am using this piece of code to create a zip file:
String filename = Helper.Timestamp() + ".zip";
ZipOutputStream out = Helper.CreateZipOutputStream(filename);
Helper.AddZipFolder(out, Helper.ImageFolder);
Helper.AddZipFile(out, new File(Settings.FILENAME));
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Helper functions:
public static String Timestamp() { return new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); }
public static ZipOutputStream CreateZipOutputStream(String filename){
FileOutputStream dest = null;
try {
dest = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new ZipOutputStream(new BufferedOutputStream(dest));
}
public static void AddZipFolder(ZipOutputStream out, File folder){
for (File file: folder.listFiles()){
Helper.AddZipFile(out, file, folder.getName() + File.separator + file.getName());
}
}
public static void AddZipFile(ZipOutputStream out, File file){
AddZipFile(out, file, file.getName());
}
public static void AddZipFile(ZipOutputStream out, File file, String path){
byte[] data = new byte[1024];
FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
return;
}
try {
out.putNextEntry(new ZipEntry(path));
int len;
while ((len = in.read(data)) > 0)
out.write(data, 0, len);
out.closeEntry();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
However there seems to be something wrong with the out.write(data, 0, len); because there is a NullPointerException inside this function call. I believe this is due to the fact that my CreateZipOutputStream throws a FileNotFoundException.
So how should I properly create a zip file?
Because you forget to append base path on your filename. your filename must be like:
String filename = Environment.getExternalStorageDirectory().getPath() + "/" + Helper.Timestamp() + ".zip";
when I upload my captured webveiw(bitmap image), I use this :
public static void saveBitmaptoPng(Bitmap bitmap, String folder, String name) {
String ex_storage = Environment.getExternalStorageDirectory().getAbsolutePath();
// Get Absolute Path in External Sdcard
String foler_name = "/" + folder + "/";
String file_name = name + ".png";
String string_path = ex_storage + foler_name;
File file_path;
try {
file_path = new File(string_path);
if (!file_path.isDirectory()) {
file_path.mkdirs();
}
FileOutputStream out = new FileOutputStream(string_path + file_name);
**bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);**
out.close();
} catch (FileNotFoundException exception) {
Log.e("FileNotFoundException", exception.getMessage());
} catch (IOException exception) {
Log.e("IOException", exception.getMessage());
}
}
It is working well. but when I change 90 to 100 of Bitmap.CompressFormat,
I got an error whe getresponseCode
int serverResponseCode = connection.getResponseCode();
if (serverResponseCode == HttpURLConnection.HTTP_OK) {
is = new BufferedInputStream(connection.getInputStream());
} else {
is = new BufferedInputStream(connection.getErrorStream());
return null;
}
when changing from 90 to 100, process flow errorStream.... but I don't know any reasons.... even 95 is also not working well..
How to receive original content and file name from server side code.
Client Code
public void send1(Socket socket)
{
try
{
dataOutputStream = new DataOutputStream(socket.getOutputStream());
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "temp.txt");
FileInputStream fis = new FileInputStream(file);
//write file length
dataOutputStream.writeLong(file.length());
Log.i("File Size", "" + file.length());
//write file names
dataOutputStream.writeUTF(file.getName());
Log.i("File Name", "" + file.getName());
//write file to dos
byte[] buf = new byte[4092];
int n = 0;
while((n = fis.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
dataOutputStream.write(buf, 0, n);
}
dataOutputStream.flush();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
File Name as temp.txt and Content as Hello
Server Code
public void receive1(Socket socket)
{
try
{
inputStream = socket.getInputStream();
dataInputStream = new DataInputStream(inputStream);
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "test.txt");
FileOutputStream fos = new FileOutputStream(file);
int n = 0;
byte[] buf = new byte[4092];
//read file name
/*String fileName = "";
try
{
fileName = dataInputStream.readUTF();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Name", "" + fileName);*/
//read file size
long fileSize = 0;
try
{
fileSize = dataInputStream.readLong();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Size", "" + fileSize);
//read file
while((n = dataInputStream.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
fos.write(buf, 0, n);
}
fos.flush();
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
File Name as test.txt and Content as temp.txtHello.
In this test.txt file, contains temp.txt. I am not getting file name from dataInputStream.readUTF().
Where I mistaken code...
If I called readUTF() method, then I am getting the Exception
Exception as
java.io.EOFException
at libcore.io.Streams.readFully(Streams.java:83)
at java.io.DataInputStream.readFully(DataInputStream.java:99)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:178)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:173)
at java.io.DataInputStream.readUTF(DataInputStream.java:169)
You wrote the Long before the String in the inputStream of the send method. What you did in the server code is that you are expecting to recieve String before the Long which in reserved on what you did in your send method.
solution:
switch reading long first then string
sample:
//read file size
long fileSize = 0;
try
{
fileSize = dataInputStream.readLong();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Size", "" + fileSize);
//read file name
String fileName = "";
try
{
fileName = dataInputStream.readUTF();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Name", "" + fileName);
i m writing .json file and i want to read that file,
but the problem is, when i try to read whole file as string it adds the space before and after every character and just because of extra chars it couldn't read json.
the Json format is
[{"description1":"The ThinkerA bronze sculpture by Auguste Rodin. It depicts a man in sober\nmeditation battling with a powerful internal struggle.","description2":"Steve JobsFounder of Apple, he is widely recognized as a charismatic pioneer of\nthe personal computer revolution.","description3":"Justin BieberBorn in 1994, the latest sensation in music industry with numerous\nawards in recent years."}]
but it gives weired response like:
[ { " d e s c r i p t i o n 1 " : " T h e .....
to trim extra spaces i refered to this, but stil didnt work:
Java how to replace 2 or more spaces with single space in string and delete leading spaces only
i m using this code
File folderPath = Environment.getExternalStorageDirectory();
File mypath=new File(folderPath, "description.json");
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(mypath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
String response = fileData.toString();
the "response" string contains weird response
so can anyone help me ?
for writing into file ,i m using :
FileOutputStream fos = new FileOutputStream(mypath);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeChars(response);
Write below method for Write Json File, Here params is a File Name and mJsonResponse is a Server Response.
For Create Files into Internal Memory of Application
public void mCreateAndSaveFile(String params, String mJsonResponse) {
try {
FileWriter file = new FileWriter("/data/data/" + getApplicationContext().getPackageName() + "/" + params);
file.write(mJsonResponse);
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
For Read Data From Json File, Here params is File Name.
public void mReadJsonData(String params) {
try {
File f = new File("/data/data/" + getPackageName() + "/" + params);
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String mResponse = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I like above answer and edited: I just love to share so i have shared that may be useful to others.
Copy and Paste following class in your package and use like:
Save: MyJSON.saveData(context, jsonData);
Read: String json = MyJSON.getData(context);
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
/**
* Created by Pratik.
*/
public class MyJSON {
static String fileName = "myBlog.json";
public static void saveData(Context context, String mJsonResponse) {
try {
FileWriter file = new FileWriter(context.getFilesDir().getPath() + "/" + fileName);
file.write(mJsonResponse);
file.flush();
file.close();
} catch (IOException e) {
Log.e("TAG", "Error in Writing: " + e.getLocalizedMessage());
}
}
public static String getData(Context context) {
try {
File f = new File(context.getFilesDir().getPath() + "/" + fileName);
//check whether file exists
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
return null;
}
}
}
writeChars writes each character as two bytes.
http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChars(java.lang.String)
http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChar(int)
Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2.
Your writing code is the problem. Just use
FileWriter fos = new FileWriter(mypath);
fos.write(response);
I need to copy a PNG file form res.raw my App's private internal memory. This is code I am using. The resulting file appears to be corrupt in that BitmapFactory.decodeFile() returns null. The same file, if placed on the SD Card decodes just fine. Here is the code that I am using.
private void loadGraphics(){
InputStream inputStream = BasicContext.getResources().openRawResource(R.raw.galaxy);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader, 8192);
int Byte = 0;
FileWriter writer = null;
String PathA = "/sdcard/rfo-basic/data/Galaxy1.png";
try {
writer = new FileWriter(PathA);
do {
Byte = buffreader.read();
{writer.write(Byte);}
} while (Byte != -1);
} catch (IOException e) {
Log.v(Basic.LOGTAG, " " + Basic.CLASSTAG + " I/O Exception 2 ");
}
finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
Log.v(Basic.LOGTAG, " " + Basic.CLASSTAG + " I/O Exception 4 ");
}
}
}
}