How to save an application's data? - android

I have written a Web View app, which logs you into 12 different sites (sign in) which works pretty fine. However, i am trying to figure out a way to backup my web view's data (so that all the login credentials are saved) to SD card. the only way i have found is to copy the root/data/data/com.example/your app folder.
How do i copy this folder somewhere to my SD card using root command on the click of a button?
this is how i access and delete the data folder
private void clear() {
String cmd = "pm clear com.wagtailapp";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true)
.command("su");
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
StreamReader stdoutReader = new StreamReader(p.getInputStream(),
CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
try {
out.write((cmd + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
String result = stdoutReader.getResult();
}
}
streamreader.java
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
#Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}

Related

I can only send files with wifi direct the first time after connection

I'm trying to exchange files between two devices using android wifi direct. Any of the device can send and receive files. After discovering and connecting the two devices,I can only successfully send and receive a file/files upon the first time calling send. I'm unable to send any file afterwards. In addition,transfer speed is very slow(it takes about three minutes to transfer a 10mb file)
void startServer(){
String intRoot = new FilesDisplayFragment().internalDirRoot;
ExecutorService serverExecutor = newSingleThreadExecutor();
serverExecutor.submit(new Runnable() {
#Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(bis);
int filesCount = 0;
try {
filesCount = dis.readInt();
} catch (IOException e) {
e.printStackTrace();
}
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = 0;
try {
fileLength = dis.readLong();
} catch (IOException e) {
e.printStackTrace();
}
String fileType = null;
try {
fileType = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = null;
try {
fileName = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
if (fileType == "apk"){
File dirs = new File(intRoot + "RemoteView/" + "app");
if(!dirs.exists()) dirs.mkdirs();
files[i] = new File(dirs.toString() + "/" + fileName);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(files[i]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++) {
try {
bos.write(bis.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
void startClient(Intent intent){
socket = new Socket();
String intRoot = new FilesDisplayFragment().internalDirRoot;
Parcelable parcelable = intent.getParcelableExtra("hostAdd");
Parceler parceler = Parcels.unwrap(parcelable);
String hostAdd = parceler.getGroupOwnerAddress().getHostAddress();
ExecutorService clientExecutor = newSingleThreadExecutor();
clientExecutor.submit(new Runnable() {
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd, 8888), 5000);
} catch (IOException e) {
e.printStackTrace();
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(bis);
int filesCount = 0;
try {
filesCount = dis.readInt();
} catch (IOException e) {
e.printStackTrace();
}
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = 0;
try {
fileLength = dis.readLong();
} catch (IOException e) {
e.printStackTrace();
}
String fileType = null;
try {
fileType = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = null;
try {
fileName = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
if (fileType == "apk"){
File dirs = new File(intRoot + "RemoteView/" + "app");
if(!dirs.exists()) dirs.mkdirs();
files[i] = new File(dirs.toString() + "/" + fileName);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(files[i]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++) {
try {
bos.write(bis.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
void send(Intent intent){
Parcelable parcelable = intent.getParcelableExtra("selected_wifi_files");
Parceler parceler = Parcels.unwrap(parcelable);
File[] files = parceler.getSelectedFilesWifi();
ExecutorService sendExecutor = newSingleThreadExecutor();
sendExecutor.submit(new Runnable() {
#Override
public void run() {
If(bos == null){
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream dos = new DataOutputStream(bos);
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream dos = new DataOutputStream(bos);
}
try {
dos.writeInt(files.length);
} catch (IOException e) {
e.printStackTrace();
}
for(File file : files)
{
long length = file.length();
try {
dos.writeLong(length);
} catch (IOException e) {
e.printStackTrace();
}
String fileType = FilenameUtils.getExtension(String.valueOf(file));
try {
dos.writeUTF(fileType);
} catch (IOException e) {
e.printStackTrace();
}
String name = file.getName();
try {
dos.writeUTF(name);
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while(true) {
try {
if (!((theByte = bis.read()) != -1)) break;
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.write(theByte);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}

Can not resolve getAssets() method from inside a java file: Android

I have created a file
inside assests folder and now I want to read the file from a java class and pass it to another function in the same class but for some reason i am unable to use getAssest() method. Please help!
public void configuration()
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(Context context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
You should try
getResources().getAssets().open("config.txt")
instead of
context.getAssets().open("config.txt");
Change your Method with Single Parameter Context ....
Pass Context from where you Call this Method..
public void configuration(Context context)
{
String text = "";
try {
InputStream is = context.getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
Yes now as per i think you are not aware from java structure...
Suppose you have this YOUR_CLASS_NAME.java
public void YOUR_CLASS_NAME{
Context context;
YOUR_CLASS_NAME(Context context){
this.context=context;
}
public void configuration(Context context)
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
}
Use this Code
BufferedReader reader = null;
try {
StringBuilder returnString = new StringBuilder();
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
returnString.append(mLine );
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

How can i save data from multipart/form-data in servlet and save this data to db?

public void saveData(HttpServletRequest request,HttpServletResponse response) throws IOException {
try {
boolean checkMultiPart = ServletFileUpload.isMultipartContent(request);
System.out.println(checkMultiPart);
//fin = request.getInputStream();
Part part = request.getPart("pic");
fin = part.getInputStream();
System.out.println(fin);
writer = response.getWriter();
if(fin != null){
fin.read();
System.out.println("Inside Function");
query = "INSERT INTO SAVEPIC(picID,PIC) VALUES (picIncVal.nextval,?)";
Class.forName(DB_DRIVER);
connection = DriverManager.getConnection(DB_URL, DB_USER,DB_PASSWORD);
connection.setAutoCommit(false);
insertStatement = connection.prepareStatement(query);
insertStatement.setBinaryStream(1, fin, fin.available());
row = insertStatement.executeUpdate();
connection.commit();
System.out.println("Save To Data Base");
}
if (row > 0)
writer.print("SUCCESS");
else
writer.print("FAILED");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (NullPointerException e) {
writer.print("Pic Value is Null");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fin != null)
fin.close();
if(writer != null)
writer.close();
if (connection != null) {
insertStatement.close();
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
I want to store image which i am sending from android in multipart/form-data. Can any one give me suggestions how can i do it.
By this code only some bits are storing into the db, Not whole image.
Thanks in advance.

read/write an object to file

here is the code :
my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array.
public void setup()
{
byte[] data = SerializationUtils.serialize(f);
WriteByteToFile(data,filename);
}
Person p =null ;
public void draw()
{
File te = new File(filename);
FileInputStream fin = null;
try {
fin=new FileInputStream(te);
byte filecon[]=new byte[(int)te.length()];
fin.read(filecon);
String s = new String(filecon);
System.out.println("File content: " + s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text(p.a,150,150);
}
and my function :
public void WriteByteToFile(byte[] mybytes, String filename){
try {
FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
it is returning a filenotfoundexception .
(i am new at this, so please be patient and understanding)
EDIT ::this is how i am (trying to ) read, (for cerntainly)
ObjectInputStream input = null;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Person myPersonObject = (Person) input.readObject();
text(myPersonObject.a,150,150);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and for reading :::
if(mousePressed)
{
Person myPersonObject = new Person();
myPersonObject.a=432;
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.writeObject(myPersonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You don't need to use the 'byte array' approach. There is an easy way to (de)serialize objects.
EDIT: here's the long version of code
Read:
public void read(){
ObjectInputStream input;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
Person myPersonObject = (Person) input.readObject();
Log.v("serialization","Person a="+myPersonObject.getA());
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Write:
public void write(){
Person myPersonObject = new Person();
myPersonObject.setA(432);
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
out.writeObject(myPersonObject);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Person class:
public class Person implements Serializable {
private static final long serialVersionUID = -29238982928391L;
int a;
public int getA(){
return a;
}
public void setA(int newA){
a = newA;
}
}
FileNotFoundException when creating a new FileOutputStream means that one of the intermediate directories didn't exist. Try
file.getParentFile().mkdirs();
before creating the FileOutputStream.
Add this code to manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Go to phone setting/applications/your_app/permissions/ allow files and media permission. You can ask permission via by code and when user enter app program will ask permission. If you want I can give you code.
All writen and readen objects must be serializable.(Must implements Serializable interface) If A class extends B class, to set B class serializable is enough.
And add this code to writen and readen class:
private static final long serialVersionUID = 1L;
Write to external memory:
public static void writeToExternal(Serializable object, String filename) {
try {
//File root = new File(Environment.getExternalStorageDirectory(), "MyApp");
//or
File root = new File("/storage/emulated/0/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write to internal memory(This memory is not visible and doesn't need permission. This is your app stored in. For this, you can use getFilesDir() instead of getExternalStorageDirectory(). More about https://developer.android.com/reference/android/content/ContextWrapper#getFilesDir%28%29
https://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29
https://gist.github.com/granoeste/5574148
https://source.android.com/docs/core/storage
public static void writeToInternal(Context context, Serializable object, String filename){
try {
//File root1 = new File(context.getFilesDir(), "MyApp");
//or
File root = new File("/data/user/0/com.example.myapplication/files/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Read an object:
public static Object read(String filename) {
try {
File file = new File("/storage/emulated/0/MyApp/" + filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fis);
Object data = (Object) input.readObject();
input.close();
return data;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
When you call read method you must cast to your readen and writen class.(For example Person p = (Person)read("file.txt");
Import all classes and run.

Read from internal storage file (Android)

How to read the particular data from the internal storage file.
For eg., I have stored
1. Device 2. Time(epoch format) 3. button text
CharSequence cs =((Button) v).getText();
t = System.currentTimeMillis()/1000;
s = cs.toString();
buf = (t+"\n").getBytes();
buf1 = (s+"\n").getBytes();
try {
FileOutputStream fos = openFileOutput(Filename, Context.MODE_APPEND);
fos.write("DVD".getBytes());
fos.write(tab.getBytes());
fos.write(buf);
fos.write(tab.getBytes());
fos.write(buf1);
//fos.write(tab.getBytes());
//fos.write((R.id.bSix+"\n").getBytes());
fos.write(newline.getBytes());
//fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then while reading, how can we read only price from the file? (using fos.read())
Thanks
I would suggest writing the file in a more structured way, like this:
long t = System.currentTimeMillis()/1000;
String s = ((Button) v).getText();
DataOutputStream dos = null;
try {
dos = new DataOutputStream(openFileOutput(Filename, Context.MODE_APPEND));
dos.writeUTF("DVD");
dos.writeLong(t); // Write time
dos.writeUTF(s); // Write button text
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
// Ignore
}
}
}
To read it back, something like this:
DataInputStream dis = null;
try {
dis = new DataInputStream(openFileInput(Filename));
String dvd = dis.readUTF();
long time = dis.readLong();
String buttonText = dis.readUTF();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
// Ignore
}
}
}

Categories

Resources