I can not initiate the bluetooth connection between Java server(using bluecove 2.1.1 on Windows 7 x64, external bluetooth dongle) and Android client(OS version 2.3.6).
Device discovery works normally, but I cannot connect to service running on PC(BluetoothSocket::connect() throw an exception). Below is a very primitive version of server and client(I use MAC address of bluetooth dongle for reducing code length):
Java Server
import java.io.*;
import javax.microedition.io.*;
import javax.bluetooth.*;
public class RFCOMMServer {
public static void main(String args[]) {
try {
StreamConnectionNotifier service = (StreamConnectionNotifier) Connector
.open("btspp://localhost:"
+ new UUID("0000110100001000800000805F9B34FB",
false).toString() + ";name=helloService");
StreamConnection conn = (StreamConnection) service.acceptAndOpen();
System.out.println("Connected");
DataInputStream in = new DataInputStream(conn.openInputStream());
DataOutputStream out = new DataOutputStream(conn.openOutputStream());
String received = in.readUTF(); // Read from client
System.out.println("received: " + received);
out.writeUTF("Echo: " + received); // Send Echo to client
conn.close();
service.close();
} catch (IOException e) {
System.err.print(e.toString());
}
}
}
Android Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.UUID;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.widget.LinearLayout;
import android.widget.ArrayAdapter;
public class AndroidBluetoothEchoClientActivity extends ListActivity {
LinearLayout layout;
private ArrayAdapter<String> mArrayAdapter;
final Handler handler = new Handler();
final Runnable updateUI = new Runnable() {
public void run() {
mArrayAdapter.add(bluetoothClient.getBluetoothClientData());
}
};
BluetoothClient bluetoothClient;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
this.setListAdapter(mArrayAdapter);
bluetoothClient = new BluetoothClient(handler, updateUI);
bluetoothClient.start();
}
}
class BluetoothClient extends Thread {
BluetoothAdapter mBluetoothAdapter;
private String data = null;
final Handler handler;
final Runnable updateUI;
public BluetoothClient(Handler handler, Runnable updateUI) {
this.handler = handler;
this.updateUI = updateUI;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
public String getBluetoothClientData() {
return data;
}
public void run() {
BluetoothSocket clientSocket = null;
// Client knows the MAC address of server
BluetoothDevice mmDevice = mBluetoothAdapter
.getRemoteDevice("00:15:83:07:CE:27");
try {
clientSocket = mmDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mBluetoothAdapter.cancelDiscovery();
clientSocket.connect();
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
out.writeUTF("Hello"); // Send to server
data = in.readUTF(); // Read from server
handler.post(updateUI);
} catch (Exception e) {
}
}
}
Here is core of the problem(I guess):
BluetoothDevice mmDevice = mBluetoothAdapter
.getRemoteDevice("00:15:83:07:CE:27");//normally get device
try {
clientSocket = mmDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));//here also no problem
mBluetoothAdapter.cancelDiscovery();
clientSocket.connect();//here throw an exception
I try to use reflection:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
clientSocket = (BluetoothSocket) m.invoke(device, 1);
but it also not work.
For over a week I can not solve this problem, I would be grateful if you help with the decision.
Here is the log file:
02-27 08:32:33.656: W/ActivityThread(10335): Application edu.ius.rwisman.AndroidBluetoothEchoClient is waiting for the debugger on port 8100...
02-27 08:32:33.687: I/System.out(10335): Sending WAIT chunk
02-27 08:32:33.882: I/System.out(10335): Debugger has connected
02-27 08:32:33.882: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.085: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.289: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.492: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.687: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:34.890: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:35.093: I/System.out(10335): waiting for debugger to settle...
02-27 08:32:35.296: I/System.out(10335): debugger has settled (1493)
02-27 08:32:35.390: I/ApplicationPackageManager(10335): cscCountry is not German : SER
02-27 08:32:35.875: D/dalvikvm(10335): threadid=9: still suspended after undo (sc=1 dc=1)
02-27 08:32:45.351: D/BluetoothSocket(10335): create BluetoothSocket: type = 1, fd = -1, uuid = [00001101-0000-1000-8000-00805f9b34fb], port = -1
02-27 08:32:45.351: D/BLZ20_WRAPPER(10335): blz20_init: initializing...
02-27 08:32:45.351: D/BTL_IFC_WRP(10335): wsactive_init: init active list
02-27 08:32:45.460: D/BLZ20_WRAPPER(10335): blz20_init: success
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_create: CTRL
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_alloc_new_sock: wrp_alloc_new_sock sub 1
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_create: 43
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_connect: wrp_sock_connect brcm.bt.btlif:9000 (43)
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_connect: BTLIF_MAKE_LOCAL_SERVER_NAME return name: brcm.bt.btlif.9000
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_sock_connect: wrp_sock_connect ret:-1 server name:brcm.bt.btlif.9000
02-27 08:32:45.460: E/BTL_IFC_WRP(10335): ##### ERROR : wrp_sock_connect: connect failed (Connection refused)#####
02-27 08:32:45.460: E/BTL_IFC(10335): ##### ERROR : btl_ifc_ctrl_connect: control channel failed Connection refused#####
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wrp_close_full: wrp_close (43:-1) [brcm.bt.btlif]
02-27 08:32:45.460: D/BTL_IFC_WRP(10335): wsactive_del: delete wsock 43 from active list [ad3bc380]
Problem solved, simply verification code on my device and on PC was different, but Windows shown device in paired devices list. I repair device and it works.
Related
I am establishing server-client communication between Android app and ESP8266 NodeMCU-1.0. The ESP is creating server on specified network and the mobile is connecting to same network.
For testing purpose I am sending "try123" string when the send button is pressed. And receiving appropriate response on the serial monitor of IDE (i.e. data is received on server). But the server response which is "Test_successful" string. I am sending this string to client using client.print. In app I am toasting the server response.
The problem is that if I am making the HTTP request using browser using the locally generated URL, then the response "Test_successful" is visible. But In app toast it's showing empty and while debugging it's showing error Unexpected line status.
ESP code (server side):
#include <ESP8266WiFi.h>
const char* ssid = "DARSHAN95";
const char* password = "12345678";
//const char* ssid = "TP-LINK_42C148";
//const char* password = "";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
// Match the request
//client.flush();
delay(100);
// Send the response to the client
client.print("Test_Sucessfull");
delay(200);
Serial.println("Client disonnected");
}
Android App code:
Please ignore the text input block on the and its code.
package com.example.access.test123;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
EditText Message;
Button Send;
String data;
HttpURLConnection http;
String sendingMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Message = (EditText) findViewById(R.id.message);
Send = (Button) findViewById(R.id.send);
Send.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
HttpAsync task = new HttpAsync();
task.execute();
}
});
}
public void sendDataMethod() throws UnsupportedEncodingException{
sendingMessage = Message.getText().toString();
String data = "Error";
BufferedReader reader = null;
//Sending Data
try{
String ip = "http://192.168.43.76/?try123";
//String address = ip + sendingMessage;
//URL url = new URL(address);
URL url = new URL(ip);
URLConnection conn = url.openConnection();
http = (HttpURLConnection)conn;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);
http.setDoInput(true);
//Server Response
int i = http.getResponseCode();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
data = sb.toString();
}
catch(IOException e){;
Log.d("Error2", e.toString());
}
finally {
try{
if(reader != null) {
reader.close();
}
}
catch (IOException ex){
Log.d("Error3", ex.toString());
}
}
}
private class HttpAsync extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object[] objects) {
try {
sendDataMethod();
}
catch (UnsupportedEncodingException e) {
Log.d("Error", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
}
}
Debugging results:
02/07 22:40:23: Launching app
$ adb install-multiple -r -t A:\New folder\Test123\app\build\intermediates\split-apk\debug\dep\dependencies.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_1.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_2.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_3.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_6.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_9.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_8.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_7.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_4.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_5.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_0.apk A:\New folder\Test123\app\build\outputs\apk\debug\app-debug.apk
Split APKs installed
$ adb shell am start -n "com.example.access.test123/com.example.access.test123.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Connecting to com.example.access.test123
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1436)
W/System: ClassLoader referenced unknown path: /data/app/com.example.access.test123-2/lib/arm64
I/art: Starting a blocking GC HeapTrim
I/InstantRun: starting instant run server: is main process
I/art: Starting a blocking GC Instrumentation
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = null, this = DecorView#3280086[]
D/WindowClient: Add to mViews: DecorView#3280086[MainActivity], this = android.view.WindowManagerGlobal#d5cc9ee
D/OpenGLRenderer: Dumper init 4 threads <0x7c6a19ee40>
D/OpenGLRenderer: <com.example.access.test123> is running.
D/OpenGLRenderer: CanvasContext() 0x7c6773f880
D/ViewRootImpl[MainActivity]: hardware acceleration is enabled, this = ViewRoot{500151c com.example.access.test123/com.example.access.test123.MainActivity,ident = 0}
V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{500151c com.example.access.test123/com.example.access.test123.MainActivity,ident = 0}, this = DecorView#3280086[MainActivity]
D/OpenGLRenderer: CanvasContext() 0x7c6773f880 initialize window=0x7c73e55e00, title=com.example.access.test123/com.example.access.test123.MainActivity
D/Surface: Surface::allocateBuffers(this=0x7c73e55e00)
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/OpenGLRenderer: Created EGL context (0x7c6a19f600)
D/OpenGLRenderer: ProgramCache.init: enable enhancement 1
I/OpenGLRenderer: Get disable program binary service property (0)
I/OpenGLRenderer: Initializing program atlas...
I/ProgramBinary/Service: ProgramBinaryService client side disable debugging.
I/ProgramBinary/Service: ProgramBinaryService client side disable binary content debugging.
D/ProgramBinary/Service: BpProgramBinaryService.getReady
D/ProgramBinary/Service: BpProgramBinaryService.getProgramBinaryData
I/OpenGLRenderer: Program binary detail: Binary length is 249276, program map length is 124.
I/OpenGLRenderer: Succeeded to mmap program binaries. File descriptor is 74, and path is /dev/ashmem.
I/OpenGLRenderer: No need to use file discriptor anymore, close fd(74).
D/OpenGLRenderer: Initializing program cache from 0x0, size = -1
D/MALI: eglCreateImageKHR:513: [Crop] 0 0 896 1344 img[896 1344]
D/Surface: Surface::connect(this=0x7c73e55e00,api=1)
W/libEGL: [ANDROID_RECORDABLE] format: 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/OpenGLRenderer: CacheTexture 3 upload: x, y, width height = 0, 0, 189, 441
D/OpenGLRenderer: ProgramCache.generateProgram: 0
D/OpenGLRenderer: ProgramCache.generateProgram: 34359738371
D/OpenGLRenderer: ProgramCache.generateProgram: 5242945
D/OpenGLRenderer: ProgramCache.generateProgram: 5242944
D/OpenGLRenderer: ProgramCache.generateProgram: 240518168576
D/OpenGLRenderer: ProgramCache.generateProgram: 68724719680
V/InputMethodManager: onWindowFocus: android.support.v7.widget.AppCompatEditText{8687c92 VFED..CL. .F....ID 228,66-851,212 #7f070042 app:id/message} softInputMode=288 first=true flags=#81810100
D/OpenGLRenderer: ProgramCache.generateProgram: 103084458052
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: [socket][0] connection /192.168.43.76:80;LocalPort=-1(0)
[ 02-07 22:40:39.251 29396:29665 D/ ]
[Posix_connect Debug]Process com.example.access.test123 :80
I/System.out: [socket][/192.168.43.1:49348] connected
I/System.out: [OkHttp] sendRequest>>
I/System.out: [OkHttp] sendRequest<<
D/Error2: java.net.ProtocolException: Unexpected status line: Test_Sucessfull
D/WindowClient: Add to mViews: android.widget.LinearLayout{3957537 V.E...... ......I. 0,0-0,0}, this = android.view.WindowManagerGlobal#d5cc9ee
D/OpenGLRenderer: CanvasContext() 0x7c56092d40
D/ViewRootImpl[Toast]: hardware acceleration is enabled, this = ViewRoot{f7a400d Toast,ident = 1}
D/Surface: Surface::allocateBuffers(this=0x7c58339e00)
D/OpenGLRenderer: CanvasContext() 0x7c56092d40 initialize window=0x7c58339e00, title=Toast
D/Surface: Surface::connect(this=0x7c58339e00,api=1)
W/libEGL: [ANDROID_RECORDABLE] format: 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
D/OpenGLRenderer: ProgramCache.generateProgram: 1
D/Surface: Surface::disconnect(this=0x7c58339e00,api=1)
D/Surface: Surface::disconnect(this=0x7c58339e00,api=1)
D/WindowClient: Remove from mViews: android.widget.LinearLayout{3957537 V.E...... ......ID 0,0-156,140}, this = android.view.WindowManagerGlobal#d5cc9ee
I/art: Do partial code cache collection, code=28KB, data=28KB
I/art: After code cache collection, code=27KB, data=28KB
I/art: Increasing code cache capacity to 128KB
Note: At D/Error2: java.net.ProtocolException: Unexpected status line: Test_Sucessfull
The string is received but with above error.
Results:
IDE monitor displaying data sent from client i.e. app
Finally Found the solution, the error was with the syntax of the response packet sent from ESP side
so just replaced
client.print("Test_Successfull");
with
client.print("HTTP/1.1 200 OK\r\nConnection: Closed\r\n\r\nTest_Successful");
I am working on a project in android studio. The application is a client that connects to host written in c# using sockets. I am new to java this being my first project I am doing on my own. I am used with sockets in c# and in java I found a lot of similarities, but I encountered a strange problem: everything is fine until a new socket is initialized when the code execution seems to be interrupted. I will post the code than I will explain exactly what is happening.
First part, the main thread:
package com.example.alexandru.news;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Connection;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class login extends Activity {
EditText emadr;
EditText pasword;
Button log_in_butt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
log_in_butt = (Button) findViewById(R.id.login);
emadr= (EditText) findViewById(R.id.EmailAdr);
pasword= (EditText) findViewById(R.id.Password);
}
public void loginOnClick(View v)
{
final String mesaj=emadr.getText().toString()+"%"+pasword.getText().toString()+"%"+"^STOP^";
String[] perm={"android.permission.CAMERA"}; int a=200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(perm,a);
}
com.example.alexandru.news.Connection log_in_connection=new com.example.alexandru.news.Connection(mesaj);
log_in_connection.start();
}
}
The connection class is a class I created in the same folder with the "log in" class(the main class). The code behind the Connection class:
package com.example.alexandru.news;
import android.content.Context;
import android.util.Xml;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
/**
* Created by Alexandru on 14.08.2016.
*/
public class Connection extends Thread {
String ip="some ip";
int port=60000;
String mesaj;
Socket soc;
public Connection(String mesaj) {
this.mesaj=mesaj;
}
#Override
public void run() {
try {
int a=2;
soc= new Socket(ip, port);
DataOutputStream outstream =new DataOutputStream(soc.getOutputStream());
byte[] buffer;
buffer = this.mesaj.getBytes("UTF-8");
outstream.write(buffer);
outstream.flush();
outstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run the app and I press the button everything is executed until the statement =new Socket(ip,port) is met when this happen the thread isn't executing anymore (I think). When I am debugging and the breakpoint is set before that problematic line everything works. When that line is highlighted and I press F8 the debugging tab says: "Application is running" and then pressing F8 again doesn't make any changes. If I press the "log in" button again nothing happens.
I am using a USB device to debug the app which is connected to the same network as the PC trough WiFi.No port forward is made. I worked with sockets in a project with my high school team before and we had a java client and a c# host and everything worked. But we were using the Emulator. I used all the ip addresses "ipconfig" gave me I changed the port, nothing happens. It doesn't work. I seems that I am the only one with this problem. Sorry for long post and lack of details.
This is the log:
08-17 12:09:38.875 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libEGL_MRVL.so
08-17 12:09:38.882 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libGLESv1_CM_MRVL.so
08-17 12:09:38.890 30326-30326/com.example.alexandru.news D/libEGL: loaded /system/lib/egl/libGLESv2_MRVL.so
08-17 12:09:38.898 30326-30326/com.example.alexandru.news D/GC: <tid=30326> OES20 ===> GC Version : GC Ver SS_rls_pxa988_JB42_R1_RC2_GC13.16
08-17 12:09:38.914 30326-30326/com.example.alexandru.news D/OpenGLRenderer: Enabling debug mode 0
08-17 12:09:38.929 30326-30326/com.example.alexandru.news D/WritingBuddyImpl: getCurrentWritingBuddyView()
08-17 12:09:39.054 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60b55588
08-17 12:09:39.492 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60e51d40
08-17 12:09:39.984 30326-30326/com.example.alexandru.news D/v_gal: [tid=30326] gralloc_register_buffer: ===>Width = 480, Height = 800, surface = 0x60ef84b8
08-17 12:14:05.617 30326-30350/com.example.alexandru.news D/Er: Eroare
08-17 12:14:17.765 30326-30350/com.example.alexandru.news W/System.err: java.net.SocketTimeoutException: failed to connect to /25.74.114.6 (port 60000) after 1000ms
08-17 12:14:17.765 30326-30350/com.example.alexandru.news W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:159)
08-17 12:14:17.781 30326-30350/com.example.alexandru.news W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:112)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at java.net.Socket.connect(Socket.java:842)
08-17 12:14:17.796 30326-30350/com.example.alexandru.news W/System.err: at com.example.alexandru.news.Connection.run(Connection.java:45)
08-17 12:14:17.828 30326-30350/com.example.alexandru.news D/dalvikvm: threadid=13: still suspended after undo (sc=1 dc=1)
08-17 12:14:17.828 30326-30330/com.example.alexandru.news D/dalvikvm: GC_CONCURRENT freed 360K, 17% free 8692K/10472K, paused 11ms+7ms, total 60ms
I'm trying to upload an file via FTP from my Android Smartphone with my own app. I've got a done code, but it isn't working. Instead it throws me Exceptions in Logact. I hope you can help me.
Used Library: https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTP.html
My Code:
package com.florian.ftpupload;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import com.florian.ftpupload.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class UploadActivity extends Activity{
public static final String TAG = "Contacts";
public String host = "<serverip>";
public String username = "<username>";
public String password = "<password>";
public String database = "test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Thread t = new Thread(new Runnable(){
#Override
public void run(){
try {
DatabaseUpload();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
Log.i(TAG, "thread started");
}
protected void DatabaseUpload() throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect(host);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)){
Toast.makeText(getApplicationContext(), "FTP server refused connection.", Toast.LENGTH_SHORT).show();
}
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
InputStream fis = new FileInputStream(database);
ftp.storeFile("test.txt", fis);
fis.close();
ftp.logout();
ftp.disconnect();
}
}
My LogCat Errors:
D/Genymotion( 56): Received Ping
I/ActivityManager( 366): START u0 {act=android.intent.action.MAIN cat= [android.
intent.category.LAUNCHER] flg=0x10200000 cmp=com.florian.ftpupload/.UploadActivi
ty} from pid 586
D/dalvikvm( 366): GC_CONCURRENT freed 805K, 16% free 7450K/8816K, paused 1ms+2m
s, total 20ms
I/ActivityManager( 366): Start proc com.florian.ftpupload for activity com.flor
ian.ftpupload/.UploadActivity: pid=1421 uid=10051 gids={50051, 1028}
I/qtaguid ( 366): Failed write_ctrl(s 1 10051) res=-1 errno=1
W/NetworkManagementSocketTagger( 366): setKernelCountSet(10051, 1) failed with
errno -1
E/dalvikvm( 1421): Could not find class 'org.apache.commons.net.ftp.FTPClient',
referenced from method com.florian.ftpupload.UploadActivity.DatabaseUpload
W/dalvikvm( 1421): VFY: unable to resolve new-instance 1557 (Lorg/apache/commons
/net/ftp/FTPClient;) in Lcom/florian/ftpupload/UploadActivity;
D/dalvikvm( 1421): VFY: replacing opcode 0x22 at 0x0000
D/dalvikvm( 1421): DexOpt: unable to opt direct call 0x2a97 at 0x02 in Lcom/flor
ian/ftpupload/UploadActivity;.DatabaseUpload
I/Contacts( 1421): thread started
W/dalvikvm( 1421): threadid=10: thread exiting with uncaught exception (group=0x
a614c908)
E/AndroidRuntime( 1421): FATAL EXCEPTION: Thread-122
E/AndroidRuntime( 1421): java.lang.NoClassDefFoundError: org.apache.commons.net.
ftp.FTPClient
E/AndroidRuntime( 1421): at com.florian.ftpupload.UploadActivity.Database
Upload(UploadActivity.java:55)
E/AndroidRuntime( 1421): at com.florian.ftpupload.UploadActivity$1.run(Up
loadActivity.java:40)
E/AndroidRuntime( 1421): at java.lang.Thread.run(Thread.java:856)
W/ActivityManager( 366): Force finishing activity com.florian.ftpupload/.Uplo
adActivity
D/libEGL ( 1421): loaded /system/lib/egl/libEGL_genymotion.so
D/ ( 1421): HostConnection::get() New Host Connection established 0xb7b1a
f98, tid 1421
D/libEGL ( 1421): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
D/libEGL ( 1421): loaded /system/lib/egl/libGLESv2_genymotion.so
I/ActivityManager( 366): START u0 {act=android.intent.action.MAIN cat= [android.
intent.category.LAUNCHER] flg=0x10200000 cmp=com.florian.ftpupload/.UploadActivi
ty} from pid 586
W/EGL_genymotion( 1421): eglSurfaceAttrib not implemented
D/OpenGLRenderer( 1421): Enabling debug mode 0
I/Contacts( 1421): thread started
W/dalvikvm( 1421): threadid=11: thread exiting with uncaught exception (group=0x
a614c908)
I/Process ( 1421): Sending signal. PID: 1421 SIG: 9
I/qtaguid ( 366): Failed write_ctrl(s 0 10051) res=-1 errno=1
W/NetworkManagementSocketTagger( 366): setKernelCountSet(10051, 0) failed with
errno -1
I/ActivityManager( 366): Process com.florian.ftpupload (pid 1421) has died.
I/WindowState( 366): WIN DEATH: Window{533f06e4 u0 com.florian.ftpupload/com.fl
orian.ftpupload.UploadActivity}
W/ActivityManager( 366): Force removing ActivityRecord{5348c488 u0 com.florian.
ftpupload/.UploadActivity}: app died, no saved state
I/WindowState( 366): WIN DEATH: Window{5343b134 u0 com.florian.ftpupload/com.fl
orian.ftpupload.UploadActivity}
W/EGL_genymotion( 586): eglSurfaceAttrib not implemented
W/InputMethodManagerService( 366): Window already focused, ignoring focus gain
of: com.android.internal.view.IInputMethodClient$Stub$Proxy#53330148 attribute=n
ull, token = android.os.BinderProxy#533c6a54
D/Genymotion( 56): Received Ping
I hope you understand my problem ;)
~Florian
I am creating a basic test application for android that can connect to a socket server and send and receive data. i have been able to get the sending of data from the client to the server working but seem to have a problem getting the android to receive data. the server works as i have been able to test that using a external application.
here is my code
package com.socket_sending_and_receving_test;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Sending_And_Receiving extends Activity {
private Socket socket;
String message = "";
String mClientMsg;
TextView text;
final Handler myHandler = new Handler();
int count = 0;
public static String SERVERPORT;
public static int SERVERPORT2;
public static String SERVER_IP;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending_and_receaving);
text = (TextView) findViewById(R.id.textView);
text.setText("0");
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(mClientMsg);
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
String st = null;
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
{
BufferedReader input = null;
try {
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void connect(View view) {
EditText ip = (EditText) findViewById(R.id.ip);
EditText port = (EditText) findViewById(R.id.port);
SERVER_IP = ip.getText().toString();
SERVERPORT = port.getText().toString();
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
}
public void Disconnect(View view) {
try {
socket.shutdownInput();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.ko);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
SERVERPORT2 = Integer.parseInt(SERVERPORT);
socket = new Socket(serverAddr, SERVERPORT2);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
after the connection is made the application crashes. I don't think it is due to the UI updating but i think its due to the receiving of data.
here is the logcat
07-08 21:59:57.915 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
07-08 21:59:57.920 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
07-08 21:59:57.925 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ Device driver API match
Device driver API version: 10
User space API version: 10
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test D/OpenGLRenderer﹕ Enabling debug mode 0
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test E/SensorManager﹕ thread start
07-08 21:59:57.970 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ registerListener :: handle = 0 name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 22:00:03.235 7041-7193/com.socket_sending_and_receving_test W/dalvikvm﹕ threadid=13: thread exiting with uncaught exception (group=0x41e792a0)
07-08 22:00:03.240 7041-7193/com.socket_sending_and_receving_test E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2791
java.lang.NullPointerException
at com.socket_sending_and_receving_test.Sending_And_Receiving$CommsThread.run(Sending_And_Receiving.java:74)
at java.lang.Thread.run(Thread.java:856)
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ unregisterListener:: Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/Sensors﹕ Remain listener = Sending .. normal delay 200ms
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/Sensors﹕ sendDelay --- 200000000
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ JNI - sendDelay
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/SensorManager﹕ Set normal delay = true
07-08 22:00:09.870 7041-7041/com.socket_sending_and_receving_test I/Choreographer﹕ Skipped 392 frames! The application may be doing too much work on its main thread.
07-08 22:00:11.680 7041-7193/com.socket_sending_and_receving_test I/Process﹕ Sending signal. PID: 7041 SIG: 9
Any help on this problem would be greatly appreciated
Cheers :)
Your socket is NULL. This is because of a race condition:
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
Both threads are started here, but ClientThread will initialise the socket while CommsThread tries to use it. But it is not initialised at this point.
You may call CommsThread's run() right after socket=... or if you really need a 2nd thread, start it there.
Your CommsThread is running before your ClientThread has completed the connection. So, 'socket' is still null and you get an NPE.
There is absolutely no reason for these to be two different threads. Combine them, so that the connection is made first and then the I/O starts. Using two threads to perform tasks that must be sequential is basically inane.
Im trying to read a text file from the raw folder in res using final Scanner input = new Scanner(new File(R.raw.xmlsource)).useDelimiter("[\\;]+"); but it isn't reading because of the resource id being int in R.java file, my code is below
EDIT Made some changes to my code below, still doesn't run but using the debugger i can tell that it actually reads the file, the problem seems to be at String[] RssLinksArray = readLine.split("[\\;]+"); where the code terminates, i can't for the life of me figure out why. i'm attaching the logcat also.
Any help would be tremendously appreciated.
package com.simplerssreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService extends IntentService
{
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService()
{
super("RssService");
}
#Override
protected void onHandleIntent(Intent intent)
{
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
while ((readLine = br.readLine()) != null)
{
}
} catch (IOException e)
{
e.printStackTrace();
}
String[] RssLinksArray = readLine.split("[\\;]+");
final String RSS_LINK = RssLinksArray[0];
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link)
{
try
{
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e)
{
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
LOGCAT
10-24 23:07:49.908: D/dalvikvm(1189): GC_FOR_ALLOC freed 101K, 9% free 2778K/3040K, paused 68ms, total 72ms
10-24 23:07:49.938: I/dalvikvm-heap(1189): Grow heap (frag case) to 3.939MB for 1127536-byte allocation
10-24 23:07:50.089: D/dalvikvm(1189): GC_FOR_ALLOC freed 2K, 7% free 3877K/4144K, paused 149ms, total 149ms
10-24 23:07:50.461: W/dalvikvm(1189): threadid=11: thread exiting with uncaught exception (group=0x41465700)
10-24 23:07:50.504: E/AndroidRuntime(1189): FATAL EXCEPTION: IntentService[RssService]
10-24 23:07:50.504: E/AndroidRuntime(1189): java.lang.NullPointerException
10-24 23:07:50.504: E/AndroidRuntime(1189): at com.simplerssreader.RssService.onHandleIntent(RssService.java:48)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Looper.loop(Looper.java:137)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.HandlerThread.run(HandlerThread.java:61)
10-24 23:07:50.899: D/libEGL(1189): loaded /system/lib/egl/libEGL_emulation.so
10-24 23:07:50.940: D/(1189): HostConnection::get() New Host Connection established 0x2a1db628, tid 1189
10-24 23:07:51.078: D/libEGL(1189): loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-24 23:07:51.279: D/libEGL(1189): loaded /system/lib/egl/libGLESv2_emulation.so
10-24 23:07:51.699: W/EGL_emulation(1189): eglSurfaceAttrib not implemented
10-24 23:07:51.729: D/OpenGLRenderer(1189): Enabling debug mode 0
10-24 23:07:51.769: I/Choreographer(1189): Skipped 85 frames! The application may be doing too much work on its main thread.
10-24 23:07:56.358: I/Choreographer(1189): Skipped 265 frames! The application may be doing too much work on its main thread.
InputStream inputStream = getResources().openRawResource(R.raw.xmlsource);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));