I have a simple SQLite database on my PC containing one table. I have the same SQLite database in my Android app. The data changes on the PC version of the database from time to time. How do I go about syncing the data from the SQLite database on the PC to the SQLite database on the Android device?
This is a simple solution with sockets:
Server side :
ServerSocket servsock = new ServerSocket(2004);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
BufferedReader input = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
String serverResponse = input.readLine();
// sendfile
File myFile = new File("C://XXXX/XXXX/XXXXX.db");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
Client side :
private String serverIpAddress = "xxx.xxx.xxx.xxx";
private static final int REDIRECTED_SERVERPORT = 2004;
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
int filesize = 6022386;
int bytesRead;
int current = 0;
byte[] mybytearray = new byte[filesize];
InputStream is = socket.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
FileOutputStream fos = new FileOutputStream(
"/data/data/XXXXX/databases/XXXXX.db");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current,
(mybytearray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
bos.close();
socket.close();
This will take quite some work to get it running without problems. Here is how I'd go:
Use a receiver on the Android to detect when USB is plugged. When this is detected, copy your database file over to the SD Card in a folder of your choice (say /data/com.example.package/sync/db.sqlite).
From your PC, detect mass storage devices. Scan the SD Card to check if you find the file at the path above. If not, there is nothing to sync. If yes, then you'll need to perform some DB comparison (google for algorithms and depending on your data you have different possibilities here)
Now you should be having a 3rd database file (the result of the sync between PC and Android databases). This file can be copied to the mass storage (your SD card) at the same place as it was taken.
Use a receiver on the Android to detect when the SDCard is mounted. When this is detected, simply copy the database file from /data/com.example.package/sync/db.sqlite to your application package directory.
We did that for a music application. This is not a trivial task but we managed to get it working quite nicely.
Related
I'm facing an issue writing PDF file to BluetoothSocket OutputStream in my android project. Text file write(print) is working fine but when I'm writing PDF file, it prints out some gibberish text not the data inside the PDF file. Here is my code snippet:
File file = new File("/storage/emulated/0/Download/sample.pdf");
inputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
int nextByte;
while ((nextByte = inputStream.read(bytes, 0, bytes.length)) != -1) {
outputStream.write(bytes, 0, nextByte);
outputStream.flush();
}
inputStream.close();
outputStream.close();
Here outputStream is BluetoothSocket OutputStream.(ex: bluetoothSocket.getOutputStream())
I am making an android music player. One of the features of the app is that it can connect to another device via sockets and then stream files over that connection. Right now, I have the app connecting to my computer with a ServerSocket. What I want is to load an mp3 on my laptop, get all the bytes from the file and send them over the socket. Then The android app should play the bytes as they are received. I was able to write all the bytes to an mp3 file on my phone, but I am wondering if there is a way to play the bytes as they come in without having to download it. I'm using a MediaPlayer for playback.
Here is my code on the android app for receiving data.
Socket socket = new Socket("ip", port);
out = new DataOutputStream(socket.getOutputStream());
out.write("0\r\n".getBytes());
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream inS = socket.getInputStream();
String line;
FileOutputStream newFile = new FileOutputStream(path+"test.mp3");
byte[] by = new byte[BUFFER_SIZE];
int read;
do{
read = inS.read(by,0,BUFFER_SIZE);
newFile.write(by,0,read);
}while(read>0);
And here is my code on the laptop (which is the server side).
Path path = "path to mp3";
byte[] b = Files.readAllBytes(path);
int portNum = 5000;
ServerSocket ss = new ServerSocket(portNum);
while(true)
{
System.out.println("waiting for connection:");
Socket clientSocket = ss.accept();
System.out.println("Got client");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line = in.readLine();
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
System.out.println(line);
byte[] by = new byte[BUFFER_SIZE];
FileInputStream s = new FileInputStream(path.toString());
int rc = s.read(by);
while(rc>0)
{
System.out.println(rc);
out.write(by,0,rc);
rc = s.read(by,0,BUFFER_SIZE);
}
s.close();
Is there a way I can create a MediaPlayer and make it's data source the byte array being read in and have it play simultaneously?
I am trying to read InputStream after writing output stream to sdcard. I have downloaded file from HttpURLConnection. File is successfuly written to sdcard. But I am trying to read inputstream from same file but contents are not being read properly. On emulator some contents are shown but on actual device contents are not shown. Can you please help what can be the issue? I am posting downloading, writing and reading code.
fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
InputStream is = connection.getInputStream();
/**
* Create file with input stream
*/
File downloadFile = new File("/sdcard/", "myFile3.pdf");
downloadFile.createNewFile();
final FileOutputStream outputStream = new FileOutputStream(downloadFile);
int availbleLength = is.available();
byte[] bytes = new byte[availbleLength];
int len1 = 0;
while ((len1 = is.read(bytes)) > 0) {
outputStream.write(bytes, 0, len1);
}
outputStream.flush();
outputStream.close();
File myFile = new File("/sdcard/myFile3.pdf");
InputStream inputStream = new FileInputStream(myFile);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
System.out.println("Byte Lenght: " + buffer.length);
inputStream.available() is only an estimate not actual length of the complete input data.
FileInputStream.available()
I need to develop an application to transfer image continuously from android to android which should be received as an video on the client side..and i have two applications which one (server) will send the file through socket connected by wifi and other should the client side should recive the image which is sent...currently am just saving it in one location in the client side...am able to receive the file correctly...but the problem is am not able to send all files correctly all the time...
Means some time the image file will be transfered and some time i ll not be able to receive and when i ll not be able to receive i am getting an exception as
: java.io.UTFDataFormatException: ...and the file is not written and saved on the receiving side...
If am not able to receive images continuously...i can think there is some problem in the code..but am able to transfer it some times..and some time not able to transfer...am not able to figure what the issue is...plz any guidance
the error is:
11-18 10:38:17.351: W/System.err(1001): java.io.UTFDataFormatException: bad second or third byte at 2
11-18 10:38:17.359: W/System.err(1001): at java.nio.charset.ModifiedUtf8.decode(ModifiedUtf8.java:53)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.decodeUTF(DataInputStream.java:444)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.decodeUTF(DataInputStream.java:438)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.readUTF(DataInputStream.java:433)
and the file is not saved when i get this exception..
Many scenarios i have tested by capturing image and saving and sending...and also compressing the image and sending...in these scenarios some very rarely it is going....am not able to figure out it...
Sender code:
File myFile = new File(sdCard+"/image/image.jpg");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//bis.read(mybytearray, 0, mybytearray.length);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
tv.setText("Send file name size to server");
//Sending file name,file size and to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
socket.close();
tv.setText("Socket Close");
tv.setText("Sent");
Receiver Code:
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
String fileName = clientData.readUTF();
File file = new File(dir,fileName);
OutputStream output = new FileOutputStream(file);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
output.write(buffer, 0, bytesRead);
size -= bytesRead;
System.out.println("Writing");
}
// status.setText("Received");
// Closing the FileOutputStream handle
output.close();
s.close();
Thanks and Regards,
Divya.K
I was stuck on this thing i combined few days of my search and reached to this... Try it and see if works for you..
Bitmap myBitmap = null;
try {
File imgFile = new File(imgPath);
if (imgFile.exists()) {
File image = new File(imgPath, "imagename.jpg");
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
//myBitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true); //uncomment this if you want to scale the image
//imageView.setImageBitmap(bitmap);//to set bitmap to image view
}
Socket sock = new Socket("192.168.1.1", 80);//ip adress and port number
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (myBitmap != null) {
myBitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
}
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
BufferedInputStream bis = new BufferedInputStream(bs);
bis.read(bitmapdata, 0, bitmapdata.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(bitmapdata, 0, bitmapdata.length);
os.flush();
sock.close();
} catch (Exception e) {
e.printStackTrace();
}
i am trying to download files using getFileStream() in dropbox api but it returns file
information only,please help me to download file data.
here is code..
FileDownload fd = api.getFileStream("dropbox","/public/myfilename.rtf", null);
BufferedReader br = new BufferedReader(new InputStreamReader(fd.is));
BufferedWriter bw = new BufferedWriter(new FileWriter(newfile));
char[] buffer = new char[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break
}
bw.write(buffer, 0, read);
}
FileDownload fd = api.getFileStream("dropbox",path, null);
File f=new File("/sdcard/test.pdf");
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=fd.is.read(buf))>0)
out.write(buf,0,len);
out.close();
fd.is.close();
and mention your path like "/public/myfilename"
Here in my code i want to save it as a PDF so
i am creating one pdf and writing data to that.