I am trying to write an android application that streams images taken from a first device, through the camera, to a second device with WiFi Direct.
I am trying to use this GitHub project, WiFiDIrectDemo, I managed to connect the devices and to send just one file.
When I try to send a second file I don't get any error and, from the logs, everything seems to work, but the second device doesn't get any file.
Is this a known issue? I have tried to look on the internet but I could not find anything that could help me.
I am attaching my File Transfer Service class:
public class FileTransferService extends IntentService {
Handler mHandler;
public static final int SOCKET_TIMEOUT = 50000; //ms
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public static int PORT = 8888;
public static final String inetaddress = "inetaddress";
public static final int ByteSize = 512;
public static final String Extension = "extension";
public static final String Filelength = "filelength";
public FileTransferService(String name) {
super(name);
}
public FileTransferService() {
super("FileTransferService");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
InputStream is = null;
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
String extension = intent.getExtras().getString(Extension);
String filelength = intent.getExtras().getString(Filelength);
try {
if(!socket.isConnected())
{
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.setReuseAddress(true);
socket.connect((new InetSocketAddress(host, port)),5000); // ..,socket_timeout)
Log.e("File Transfer Service"," socket connect");
}
Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
Log.e("file transfer" +
" service", "get output stream");
ContentResolver cr = context.getContentResolver();
Long FileLength = Long.parseLong(filelength);
WiFiTransferModal transObj = null;
ObjectOutputStream oos = new ObjectOutputStream(stream);
if(transObj == null) transObj = new WiFiTransferModal();
transObj = new WiFiTransferModal(extension,FileLength);
oos.writeObject(transObj);
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
}
DeviceDetailFragment.copyFile(is, stream);
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
oos.flush();
oos.close(); //close the ObjectOutputStream after sending data.
} catch (IOException e) {
Log.e("file transfer service","unable to connect: " + e.toString() );
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (Exception e) {
// Give up
e.printStackTrace();
Log.e("File transfer service","exception socket.close: " + e.toString());
}
}
}
else Log.e("file transfer service","socket is already null");
}
}
}
}
EDIT
Receiving code:
public class FileServerAsyncTask extends AsyncTask<String, String, String> {
// private TextView statusText;
private Context mFilecontext;
private String Extension, Key;
private File EncryptedFile;
private long ReceivedFileLength;
private int PORT;
public FileServerAsyncTask(Context context, int port) {
this.mFilecontext = context;
handler = new Handler();
this.PORT = port;
}
#Override
protected String doInBackground(String... params) {
try {
Log.e("device detail fragment", "File Async task port-> " + PORT);
ServerSocket serverSocket = new ServerSocket();
Log.e("device detail fragment"," new server");
serverSocket.setReuseAddress(true);
Log.e("device detail fragment","set reuse address");
serverSocket.bind(new InetSocketAddress(PORT));
Log.e("device detail fragment","socket bind");
Socket client = serverSocket.accept();
Log.e("device detail fragment "," socket client accept");
Log.e("Device detail fragment ", "client inet address" + client.getInetAddress());
WiFiClientIp = client.getInetAddress().getHostAddress();
Log.e("device detail fragment"," get client ip: " + WiFiClientIp);
ObjectInputStream ois = new ObjectInputStream(
client.getInputStream());
Log.e("device detail fragment","object input stream + " + ois.toString());
WiFiTransferModal obj = null;
String InetAddress;
try {
obj = (WiFiTransferModal) ois.readObject();
Log.e("device detail fragment"," read object");
if (obj != null) {
Log.e("device detail fragment"," obj != null ");
InetAddress = obj.getInetAddress();
Log.e("device detail fragment"," get inet address: " +
InetAddress);
if (InetAddress != null
&& InetAddress
.equalsIgnoreCase(FileTransferService.inetaddress)) {
SharedPreferencesHandler.setStringValues(mFilecontext,
mFilecontext.getString(R.string.pref_WiFiClientIp), WiFiClientIp);
//set boolean true which identify that this device will act as server.
SharedPreferencesHandler.setStringValues(mFilecontext,
mFilecontext.getString(R.string.pref_ServerBoolean), "true");
ois.close(); // close the ObjectOutputStream object
Log.e("device detail fragment"," output stream close");
// after saving
serverSocket.close();
Log.e("device detail fragment","close");
return "Demo";
}
Log.e("device detail fragment","FileName got from socket on other side->>> "+
obj.getFileName());
}
final File f = new File(
Environment.getExternalStorageDirectory() + "/"
+ FolderName + "/"
+ obj.getFileName());
Log.e("background"," new file f from inputstream");
File dirs = new File(f.getParent());
Log.e("device detail fragment"," f get parent()");
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.e("device detail fragment","create new file");
/**
* Receive file length and copy after it
*/
this.ReceivedFileLength = obj.getFileLength();
InputStream inputstream = client.getInputStream();
Log.e("device detail fragment","input stream client get input");
Message msg = Message.obtain();
msg.what = 1;
try
{
// send the images to the image view through handler
Bitmap bitmap = BitmapFactory.decodeStream(inputstream);
Log.e("device detail fragment", "decode stream");
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
Log.e("device detail fragment","message: " + msg.toString());
messageHandler.sendMessage(msg);
}
catch (Exception e)
{
Log.e("device detail fragment","stream not decoded into bitmap with" +
"exception: " + e.toString());
}
copyRecievedFile(inputstream, new FileOutputStream(f),
ReceivedFileLength);
Log.e("device detail fragment","copy input stream into file");
ois.close(); // close the ObjectOutputStream object after saving
// file to storage.
Log.e("device detail fragment","ois close");
/**
* Set file related data and decrypt file in postExecute.
* */
this.Extension = obj.getFileName();
this.EncryptedFile = f;
final Uri uri = Uri.fromFile(f);
return f.getAbsolutePath();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
Log.e("device detail fragment", e.getMessage());
}
return "";
} catch (IOException e) {
Log.e("device detail fragment", e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
if (!result.equalsIgnoreCase("Demo")) {
Log.e("On Post Execute","result +" + result);
} else if (!TextUtils.isEmpty(result)) {
/**
* To initiate socket again we are initiating async task
* in this condition.
*/
FileServerAsyncTask FileServerobj = new
FileServerAsyncTask(mFilecontext, FileTransferService.PORT);
if (FileServerobj != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
FileServerobj.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
Log.e("Post Execute", "FileServerobj.execute on executor");
} else
{
FileServerobj.execute();
Log.e("Post Execute", "FileServerobj.execute");
}
}
}
}
}
#Override
protected void onPreExecute() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(mFilecontext);
}
if(imageView == null){
imageView = new ImageView(mFilecontext);
}
}
}
The server will receive a file and then opens it by letting the user choose an app to display the file. The server asynctask then has finished. So no new file can be received. So i do not believe you if you say that the logs tell that all is normal. Your client socket can not connect to begin with. All is intented behaviour.
* To initiate socket again we are initiating async task * in this condition..
Your code is not coming there.
You have to start an asynctask again to receive the next file.
Related
I am composing a WiFi Direct android app following guide of Google Developer's guide. I am just beginning to learn. I am stuck in sending an image from Client to Server. The following is Client and Server coding taken from Demo:
This is a code to call Client Intent (MainActivity):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode ==SELECT_IMAGE) {
Log.d(MainActivity.TAG, "onActivityResult Start");
Log.d(MainActivity.TAG, "requestCode "+requestCode);
Uri uri = data.getData();
Intent serviceIntent = new Intent(this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
Log.d(MainActivity.TAG, "file path " + uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_ADDRESS, IP_SERVER);
serviceIntent.putExtra(FileTransferService.EXTRAS_PORT, PORT);
this.startService(serviceIntent);
} else {
Log.d(MainActivity.TAG, "Service transfer failed");
}
}
This is code for Client (I used IntentService in a separate class):
public class FileTransferService extends IntentService {
public static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.moon.android.wifidirectproject_moon.action.SEND_FILE";
public static final String EXTRAS_ADDRESS = "go_host";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_PORT = "go_port";
Socket socket = new Socket();
public FileTransferService() {
super("FileTransferService");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_PORT);
try {
Log.d(MainActivity.TAG, "Opening client socket - ");
Log.d(MainActivity.TAG, "fileUri" + fileUri);
Log.d(MainActivity.TAG, "host" + host);
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(MainActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
Log.d(MainActivity.TAG, "is - " + is);
} catch (FileNotFoundException e) {
Log.d(MainActivity.TAG, e.toString());
}
copyFile(is, stream);
Log.d(MainActivity.TAG, "Client: Data written");
} catch (IOException e) {
Log.e(MainActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(MainActivity.TAG, e.toString());
return false;
}
return true;
}
}
This is a call to Server Intent
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
if (info.groupFormed && info.isGroupOwner) {
InetAddress groupOwnerAddress = info.groupOwnerAddress;
ownerIP = groupOwnerAddress.getHostAddress();
Log.d(MainActivity.TAG, "Owner connected" + ownerIP);
Intent serverIntent = new Intent(mActivity, ServerService.class);
serverIntent.putExtra("port",MainActivity.PORT);
mActivity.startService(serverIntent);
.....
The following is Server Intent Service:
public class ServerService extends IntentService {
public static String mClientIP;
public ServerService() {
super("ServerService");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
Integer port = intent.getExtras().getInt("port");
try {
ServerSocket serverSocket = new ServerSocket(port);
Socket client = serverSocket.accept();
Log.d(MainActivity.TAG, "Server: Socket opened");
Log.d(MainActivity.TAG, "clientIP" + client.getInetAddress().toString());
mClientIP = client.getInetAddress().toString();
Log.d(MainActivity.TAG, "Server: connection done");
/*
*************I am stuck here******************************
*/
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(MainActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
} catch (IOException e) {
Log.e(MainActivity.TAG, e.getMessage());
} finally {
stopSelf();
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(MainActivity.TAG, e.toString());
return false;
}
return true;
}
}
Lastly, the following is my LogCat. I put asterisk marks where no further progress is made in Server.
1) Server device (Initial State)
: search start
: WiFi_enabled
: Owner connected192.168.49.1
2) Client Device(sending image):
...............................
Opening client socket -
: fileUricontent://media/external/images/media/16871
: host192.168.49.1
: Client socket - true
: WiFi_enabled
: is - android.os.ParcelFileDescriptor$AutoCloseInputStream#3c520d34
3) Again Server Device
: Server: Socket opened
: clientIP/192.168.49.133
: Server: connection done
: open failed: ENOENT (No such file or directory)
I must confess that I don't fully understand the server/client. I just have rough knowledge. However, if you give me any hint on what I am wrong with, I will try to learn more for myself. I've spent several days working on it but couldn't work it out. Thanks for reading this post.
I have an android app that I would like to make it be able compare data via wi-fi p2p.
I understand the connection method (1. Set up app. permissions; set up broadcast reciever and P2P manager; initiate peer descovery; connect to peer)
But I have a problem when it comes to data transfer. My app's interface has some drop-down menus
with several options to select from. I was wondering, how can I make the selected options (once the app users connect to each other)
be able to compare data and notify the app users if they have mutual selections.
Will this code work?
//SERVER
public static class FileServerAsyncTask extends AsyncTask {
private Context context;
private TextView statusText;
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
/**
* Create a server socket and wait for client connections. This
* call blocks until a connection is accepted from a client
*/
ServerSocket serverSocket = new ServerSocket(8888);
Socket client = serverSocket.accept();
/**
* If this code is reached, a client has connected and transferred data
*/
var pGender:String
var pDesire:String
var pAge:String
var pRace:String
var pWeight:String
var pHeight:String
var dGender:String = dGender.getValue(dGender.selectedItem.data);
var pDesire:String = pDesire.getValue(pDesire.selectedItem.data);
var dRace:String = dRace.getValue(dRace.selectedItem.data);
var dAge:String = dAge.getValue(dAge.selectedItem.data);
var dHeight:String = dHeight.getValue(dHeight.selectedItem.data);
var dWeight:String = dWeight.getValue(dWeight.selectedItem.data);
if (pGender == dGender.selectedItem.data && pDesire == pDesire.selectedItem.data && pRace == dRace.selectedItem.data && pWeight == dWeight.selectedItem.data && pHeight == dHeight.selectedItem.data)
{
trace (jump to frame 110 + vibrate);
}
else
{
trace (jump to frame 138 + vibrate + jump to frame 10) ;
}
return results;
}
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/**
* Start activity that can handle the JPEG image
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
}
Then the on the client I have this:
//CLIENT
Context context = this.getApplicationContext();
String host;
int port;
int len;
Socket socket = new Socket();
byte buf[] = new byte[1024];
...
try {
/**
* Create a client socket with the host,
* port, and timeout information.
*/
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), 500);
/**
* Create a byte stream from a JPEG file and pipe it to the output stream
* of the socket. This data will be retrieved by the server device.
*/
OutputStream outputStream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream inputStream = null;
/*varibles declaration
*/
pGender.getValue(pGender.selectedItem.data);
pDesire.getValue(pDesire.selectedItem.data);
pRace.getValue(pRace.selectedItem.data);
pAge.getValue(pAge.selectedItem.data);
pHeight.getValue(pHeight.selectedItem.data);
pWeight.getValue(pWeight.selectedItem.data);
inputStream = cr.openInputStream(Uri.parse(DataProvider.getItemAt(pGender:String, pDesire:String, pRace:String, pAge:String, pHeight:String, pWeight:String):Object));
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
//catch logic
} catch (IOException e) {
//catch logic
}
/**
* Clean up any open sockets when done
* transferring or if an exception occurred.
*/
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
//catch logic
}
}
}
}
I am having a bluetooth device . Basically i want my app to connect to the device and receive the data it sends.However so far i am able to connect to the bluetooth device,but i am not able to receive any inputs from it .
here is my problem:
i) DataInputStream.available() always return 0.
ii) If i use any breakpoint on line
bytes = input.read(buffer); // This will freeze doesn't show anything.
and line below it never executes
public class ConnectThread extends Thread{
final String TAG="ConnectThread";
private ReadThread mReadThread = null;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean isDeviceConnected;
public final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket mmSocket = null;
Handler mHandler;
BluetoothDevice bTdevice;
private DataInputStream mReadData = null;
public ConnectThread(BluetoothDevice bTdevice, Handler mHandler) {
super();
this.bTdevice = bTdevice;
this.mHandler = mHandler;
InputStream tmpIn = null;
OutputStream tmpOut = null;
BluetoothSocket socket;
try {
socket = bTdevice.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("**** Socket created using standard way******");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
mmSocket = socket;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
#Override
public synchronized void run() {
// TODO Auto-generated method stub
super.run();
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.cancelDiscovery();
Log.i("***Bluetooth Adapter**", "Bluetooth Discovery Canceled");
}
if (mmSocket != null) {
mmSocket.connect();
Log.i("***Socket Connection Successful**", "Socket Connection Successful");
isDeviceConnected = true;
mReadData = new DataInputStream(mmSocket.getInputStream());
Log.i("***Read data**", "" + mReadData);
if (mReadThread == null) {
mReadThread=new ReadThread(mReadData,mmSocket);
mReadThread.start();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("***Error**", "Socket Connection failed");
e.printStackTrace();
try {
mmSocket.close();
isDeviceConnected = false;
} catch (IOException closeException) {
e.printStackTrace();
}
}
// mHandler.obtainMessage(DisplayBtdataActivity.SUCCESS_CONNECT,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
// Read the data from device
private class ReadThread extends Thread {
/** The input. */
private DataInputStream input;
/**
* Constructor for ReadThread.
*
* #param input
* DataInputStream
*/
private BluetoothSocket mSocket;
public ReadThread(DataInputStream input, BluetoothSocket socket) {
this.input = input;
this.mSocket = socket;
}
/**
* Method run.
*
* #see java.lang.Runnable#run()
*/
public synchronized void run() {
try {
Log.d(TAG, "ReadThread run");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
bytes = input.available(); // always return 0
// bytes = mReadData.readInt();
Log.i("***Bytes data**", "" + bytes);// print 0
Log.i("***Data input stream**", "" + input); // Here input is not null
if (input != null) {
Log.i("***hello world**", "...");
while (isDeviceConnected) {
try {
bytes = input.read(buffer); // this code never executes
Log.i("**bytes data**", " " + bytes);
if (input != null) {
int len = input.readInt();
Log.i(TAG, "Response Length: " + len);
if (len > 65452) {// Short.MAX_VALUE*2
Log.i(TAG, "Error: Accesory and app are not in sync.");
continue;
}
Log.d(TAG, "Response Length: " + len);
Log.d(TAG, "Reading start time:" + System.currentTimeMillis());
byte[] buf = new byte[len];
Log.d(
TAG, "input.available() " + input.available());
if (input.available() > 0) {
input.readFully(buf);
System.out.println("Output:=");
}
Log.d(TAG, "Reading end time:" + System.currentTimeMillis());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
isDeviceConnected = false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
isDeviceConnected = false;
Log.e(TAG, "catch block 3 " + e.toString());
}
}
}
}
In ReadThread.Run() - you have to move the code
bytes = input.available (); // Always return 0
into while loop
1, you use input before checking for null if (input! = null)
2, Data is sent continuously and is a high probability that when running thread do not come any data, so therefore you have to give input.available bytes = (); into a while loop.
3, You can try to modify data processing. In principle, quickly read the data in the temporary buffer, and then move to MainBuffer and then manipulated with it. An example is in c # .net Xamarin, but just for an example :
private const int BTLPacketSize = 1024;
private const int BTLdataSize = 65536;
private System.Object InternaldataReadLock = new System.Object();
private System.Object dataReadLock = new System.Object();
private byte[] InternaldataRead = new byte[BTLPacketSize];//posila 64Byte pakety (resp. 62, protoze 2 jsou status bytes)
private byte[] TempdataRead = new byte[BTLPacketSize];
private byte[] dataRead = new byte[BTLdataSize];//Tyto pameti pouzivaji cursorc -> musim ohlidat preteceni pameti//Max. prenos rychlost je 115200 b/s.
private bool continueRead = true;
public override void Run()
{
while (continueRead)
{
try
{
int readBytes = 0;
lock (InternaldataReadLock)
{//Quick reads data into bigger InternaldataRead buffer and next move only "received bytes" readBytes into TempdataRead buffer
readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
Array.Copy(InternaldataRead, TempdataRead, readBytes);
}
if (readBytes > 0)
{//If something reads move it from TempdataRead into main dataRead buffer a send it into MainThread for processing.
lock (dataReadLock)
{
dataRead = new byte[readBytes];
for (int i = 0; i < readBytes; i++)
{
dataRead[i] = TempdataRead[i];
}
}
Bundle dataBundle = new Bundle();
dataBundle.PutByteArray("Data", dataRead);
Message message = btlManager.sourceHandler.ObtainMessage();
message.What = 1;
message.Data = dataBundle;
btlManager.sourceHandler.SendMessage(message);
}
}
catch (System.Exception e)
{
if (e is Java.IO.IOException)
{
//.....
}
}
}
}
This is the error caused after runnung the code
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.lang.Thread.run(Thread.java:841)
03-13 16:43:00.901: E/AndroidRuntime(18994): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 56: http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.net.URI.create(URI.java:727)
03-13 16:43:00.901: E/AndroidRuntime(18994): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
03-13 16:43:00.901: E/AndroidRuntime(18994): at com.example.mobilehealthcare.Temperature$DownloadWebPageTask.doInBackground(Temperature.java:271)
java file
package com.example.mobilehealthcare;
public class Temperature extends Activity {
private static final String TAG = "bluetooth2";
Button btnOn, btnOff;
TextView txtArduino;
Handler h;
private GraphView mGraph;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
// private static String address = "00:12:09:29:42:57";
// private static String address = "00:15:83:15:A3:10";
// private static String address = "20:13:07:12:04:17";
String sdop = "";
String pd = "";
String s1,sa,s1nom,sakom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temperature);
SharedPreferences pre = getSharedPreferences("pref", 0);
s1 = pre.getString("savedDatasd", "10");
s1nom = pre.getString("savedDatad", "10");
mGraph = (GraphView)findViewById(R.id.grap);
txtArduino = (TextView)findViewById(R.id.texView1);
mGraph.setMaxValue(1024);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
// int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
int endOfLineIndex = sb.indexOf("/");
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
Toast.makeText(getApplicationContext(), "received message"+"----"+sbprint, 30).show();
sb.delete(0, sb.length()); // and clear
txtArduino.setText(sbprint); // update TextView
// final int s = Integer.parseInt(sbprint);
// mGraph.addDataPoint(s);
sdop+= txtArduino.getText().toString()+",";
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
public void tyre(View v)
{
mConnectedThread.write("t");
Toast.makeText(this, "waid for values to be received", Toast.LENGTH_SHORT).show();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(s1);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
//"savedData" is the key that we will use in onCreate to get the saved data
//mDataString is the string we want to save
// editor.putString("savedDatasd", sa);
// editor.putString("savedDatad", sakom);
// commit the edits
editor.commit();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
public void bus(View v)
{
Intent jkl = new Intent(this,Select.class);
startActivity(jkl);
finish();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Toast.makeText(getApplicationContext(), "Values are isent to Doctor", 30).show();
}else{Toast.makeText(getApplicationContext(), "Values are not sent to Doctor", 30).show();}
}
}
public void sav(View v)
{
String e = "t";
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/temp.php?name="+s1nom+"&temper="+sdop+"w="+e });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.temperature, menu);
return true;
}
}
Is it due to the php code?
or is the error in this java file.?
Which charater should be changed?
The error is in download web page task.
Edit:
This is the other code with same concept:
this works without error
public class Register extends Activity {
EditText a,b,c,d,e,f,g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
a = (EditText) findViewById(R.id.editname1);
b = (EditText) findViewById(R.id.editpas1);
c = (EditText) findViewById(R.id.age);
d = (EditText) findViewById(R.id.editph1);
e = (EditText) findViewById(R.id.editadd1);
f = (EditText) findViewById(R.id.editem1);
g = (EditText) findViewById(R.id.dph);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Intent i2 = new Intent(getApplicationContext(), Login.class);
//i.putExtra("id",na);
startActivity(i2);
}else{Toast.makeText(getApplicationContext(), result, 30).show();}
}
}
public void insert(View v)
{
String h,i,j,k,l,m,n;
h = a.getText().toString();
i = b.getText().toString();
j = c.getText().toString();
k = d.getText().toString();
l = e.getText().toString();
m = f.getText().toString();
n = g.getText().toString();
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/regis.php?name="+h+"&pass="+i+"&age="+j+"&ph="+k+"&addr="+l+"&em="+m+"&docph="+n });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, menu);
return true;
}
}
seems to me that the query url "__http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t" is where the program is encountering problem.
the 56th character is "=" which shouldnt be unexpected. However the spaces before the "31" in the string, can those be a point of concern?
If the spaces are not required as per your design, i would suggest you to remove and try it. If, they are however required, i would suggest escaping it before using the same.
Hope it helps.
note: ignore the undescores before the url. did that to prevent hyperlinking.
Problem are the blank spaces after the = symbol. You can avoid this simply with String:trimm(), but won't solve other problems, so, to avoid this, with URL's use java.net.URLEncoder to fit your needed enconding, for example:
URLEncoder.encode(url, "UTF-8");
In your case:
HttpGet httpGet = new HttpGet(URLEncoder.encode(url, "UTF-8"));
I would like to upload image to mysql database from android app using RESTful service.
Is their any service side and android side tutorial.Please kindly help in providing RESTful and android samples
Thank in advance
This Tutorial will help with uploading image files and
This tutorial will help you with writing images to database.
Adding parts of code:
Webservice for file upload:
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
/************************************************/
// CALL THE IMAGE UPLOAD TO DB CODE HERE.
// InsertImageTest.insertImage();
/*************************************************/
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JAVA CODE FOR IMAGE SAVING TO DB
public class InsertImageTest {
/**
* This is used to get the Connection
*
* #return
*/
public Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/technicalkeeda", "root", "");
} catch (Exception e) {
System.out.println("Error Occured While Getting the Connection: - "
+ e);
}
return connection;
}
/**
* Insert Image
*/
public void insertImage() {
Connection connection = null;
PreparedStatement statement = null;
FileInputStream inputStream = null;
try {
File image = new File("C:/honda.jpg");
inputStream = new FileInputStream(image);
connection = getConnection();
statement = connection
.prepareStatement("insert into trn_imgs(img_title, img_data) "
+ "values(?,?)");
statement.setString(1, "Honda Car");
statement.setBinaryStream(2, (InputStream) inputStream,
(int) (image.length()));
statement.executeUpdate();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException: - " + e);
} catch (SQLException e) {
System.out.println("SQLException: - " + e);
} finally {
try {
connection.close();
statement.close();
} catch (SQLException e) {
System.out.println("SQLException Finally: - " + e);
}
}
}
/***
* Execute Program
*
* #param args
* #throws SQLException
*/
public static void main(String[] args) throws SQLException {
InsertImageTest imageTest = new InsertImageTest();
imageTest.insertImage();
}
}
The best and easy way to upload any file from android to Mysql server is via using FTP client Library. Link
Find the ftp4j-1.6.jar file and import in your project
then you can upload image on your server via following code.
public void upload(){
FTPClient con = null;
con = new FTPClient();
con.connect("192.168.2.57"); // Your Server IP and Port you can use FTP domain credentials here also
if (con.login("XXXXXXXXX", "XXXXX")) // FTP username and Pass
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a"; // Your File Path
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/vivekm4a.m4a", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
}
Hope this Helps