Hi I have managed some code but its not working
I want to control send message from PC To Android over my application via USB not by WIFI
i tried this code
But it's giving me error that
07-13 20:08:28.530: W/System.err(8990): java.net.ConnectException: localhost/127.0.0.1:383 - Connection refused
I have done port forward by adb
For Desktop
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class comunicate {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(383);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
For Mobile
package demo.app.org;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DemoAppActivity extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("localhost", 383);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
Isn't this code for tcp communication over wifi? I think you can not communicate with android over USB except for logcat.
Related
I am trying to connect arduino Uno to android device using Wifi over a Common Lan connection but the following code is not giving me any response from Arduino. Arduino is working well with the desktop checking code.Here is my android part of the code on click of a toggle button
//WIFI socket code
ToggleButton toggle = (ToggleButton) findViewById(R.id.wifiTButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// wifi thread code
final Runnable r = new Runnable()
{
public void run()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
textOut = (TextView) findViewById(R.id.textOut);
textIn=(EditText) findViewById(R.id.textIn);
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111111);
//dataOutputStream.writeUTF("111111".toString() );//textOut.getText().toString());
textIn.setText(dataInputStream.readByte());
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
}
}
});
I was able to solve the problem. It is running well with the command button instead of a toggle button and properly using the thread syntax.
Here is a sample application mainActivity code.
package com.example.arduinoandroid;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Handler handler;
String TAG = "main Activity";
Button bt1;
TextView textOut;
EditText editIn;
static byte abc;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
class Task implements Runnable {
#Override
public void run() {
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111);
// dataOutputStream.writeUTF("111111".toString()
// );//textOut.getText().toString());
abc = dataInputStream.readByte();
Toast.makeText(getBaseContext(), abc, Toast.LENGTH_SHORT)
.show();
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textOut.setText("working ae");
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
// WIFI socket code
bt1 = (Button) findViewById(R.id.chkButton1);
textOut = (TextView) findViewById(R.id.textOut);
editIn = (EditText) findViewById(R.id.editIn);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Task()).start();
}
});
}
}
and the code for xml part is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/chkButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="140dp"
android:text="Check wifi" />
<TextView
android:id="#+id/textOut"
android:layout_width="wrap_content"
android:layout_height="39dp"
android:layout_gravity="bottom|right"
android:text="Output" />
<EditText
android:id="#+id/editIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:text="111111"/>
</LinearLayout>
Please include the following permissions in the manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
I've trying to connect 2 devices by sockets, but it never works. One of the devices is the Server that save the configuration (IP and port where listen) on a database, then the other device,the Client , connect with the database and take the configuration to conect.
Database querys and echos works fine (PHP) but the method wich open the client socket doesn't work, it run out of time to connect and throws an exception. I dont know if the ServerSocket doesn't receive the petition or the ClientSocket doesn't send it...
The code below: (bit bad, but is for test).
Server code:
public class Server{
private int puerto = 4567;
private ServerSocket serverSocket;
public void conectar() {
try {
serverSocket = new ServerSocket(puerto);
while (true) {
Log.i("SocketServer", "escuchando");
Socket cliente = serverSocket.accept();
Log.i("Socket","Cliente ha conectado");
BufferedReader ent = new BufferedReader(new InputStreamReader(
cliente.getInputStream()));
String linea = ent.readLine();
Log.i("Cliente", "Cliente envia=" + linea);
cliente.close();
Log.i("Servidor","Cliente desconectado");
}
} catch (IOException e) {
Log.e("Error", "Error en el servidor");
}
}
Client code:
public class Cliente {
private int puerto;
private InetAddress direccion;
public Cliente(int puerto, InetAddress direccion){
this.puerto = puerto;
this.direccion = direccion;
}
public void conectar(){
try{
Socket cliente = new Socket(direccion, puerto);
Log.i("Cliente", "Conectado");
conectado = true;
PrintWriter salida=new PrintWriter(cliente.getOutputStream(),true);
salida.println("Hola, soy el cliente");
Log.i("Cliente", "Mensaje enviado");
cliente.close();
}catch(SocketException e){
Log.e("ErrorSocket","Error al abrir socket " + e.getMessage());
} catch (IOException e) {
Log.e("ErrorSocket","Error al enviar " + e.getMessage());
}
}
}
I get the InetAddress by method below:
//The String result param is like: "192.168.0.1&23456"
public InetAddress getInetAddress(String result) {
InetAddress address = null;
//5 it an example
if (result.length() > 5 && result != null) {
try {
String[] data = result.split("&");
Log.i("Data", data[0] + " " + data[1]);
puerto = Integer.parseInt(data[1]);
Log.i("PUERTO", "Puerto:" + puerto);
String ip = data[0];
Log.i("IP", ip);
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
address = InetAddress.getByAddress(IP);
Log.i("InetAddress",address.getCanonicalHostName());
} catch (Exception e) {
Log.e("Error", "Error al conseguir InnetAddress");
}
} else {
Log.e("Error", "String capturado vacio");
return address;
}
return address;
}
Thanks :)
It a test project for my College Final Project, a GPS-Chat.
EDIT: 3G nat breaks this way to develop an android connection between 2 devices by sockets. I'll study the way to do it with GCM and another server.
For your client code I find that this works really well for me:
OutputStreamWriter wr = new OutputStreamWriter(cliente.getOutputStream());
Then to send data use:
wr.write("DATA TO SEND");
wr.flush();
It looks like you have good logging going on, I would also add Log output lines to see if it got past the socket and have it print out all of the data that you get. If all of the logs show the correct data but the client just won't connect, try the code I posted above, I haven't had problems with it.
ServerApplication.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class ServerApp {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){
try {
sock=clientSocket;
InputStreamReader isr=new InputStreamReader(sock.getInputStream());
reader=new BufferedReader(isr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
String message;
try {
while((message=reader.readLine())!=null)
{
System.out.println("read :"+message);
tellEveryone(message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void tellEveryone(String message) {
// TODO Auto-generated method stub
Iterator itr=clientOutputStreams.iterator();
while(itr.hasNext()){
PrintWriter pWriter=(PrintWriter)itr.next();
pWriter.println(message);
pWriter.flush();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ServerApp().createSocket();
}
private void createSocket() {
// TODO Auto-generated method stub
clientOutputStreams=new ArrayList();
try {
ServerSocket socket=new ServerSocket(5000);
while(true){
Socket clientSocket=socket.accept();
PrintWriter writer=new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("Got a Connection to the Client");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Chat Client Source Code
===================================================
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class ChatClient {
JTextField outgoing;
JTextArea incoming;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void layOutDesign(){
JFrame frame= new JFrame("Simple Chat Client");
JPanel mainPanel= new JPanel();
incoming= new JTextArea(15,25);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller=new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing=new JTextField(20);
JButton sendButton=new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setupNetworking();
Thread readerThread=new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setupNetworking() {
// TODO Auto-generated method stub
try {
sock=new Socket("10.30.10.156", 5000);
InputStreamReader isR=new InputStreamReader(sock.getInputStream());
reader=new BufferedReader(isR);
writer=new PrintWriter(sock.getOutputStream());
System.out.println("Network Established.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class SendButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent ev) {
// TODO Auto-generated method stub
try{
writer.println(outgoing.getText());
writer.flush();
}catch (Exception e1) {
// TODO: handle exception
e1.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ChatClient().layOutDesign();
}
public class IncomingReader implements Runnable{
String message;
#Override
public void run() {
// TODO Auto-generated method stub
try {
while((message=reader.readLine())!=null){
System.out.println("Read :"+message);
incoming.append(message+"\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Go to server code...
and change the IP of your System
then connect to the Clients
And enjoy the Chatting between your colleagues in your Network....
Better option for exchange information about GPS position is use websocket. I very simple server for this kind of application https://github.com/yoman07/geo_server demo class for android you can find here https://github.com/yoman07/PhotoShoter/blob/master/PhotoShoterModule/src/main/java/com/photoshoter/SocketClient.java .
I've finally managed to connect from my android phone to my device, put I have a problem when I try to read from my bluetooth socket.
So here is my code for establishing connecting to my device, its a class that extends AsyncTask
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class Connect extends AsyncTask<String, Void, String> {
private final static String TAG = "+++CONNECT THREAD+++";
ProgressDialog progressDialog;
Context context;
BluetoothSocket tmp;
BluetoothDevice device;
BluetoothAdapter ba;
Button connect;
int bt_port_to_connect;
ReadInput ri;
InputStream is;
byte[] test;
public Connect(Context context, BluetoothDevice device, BluetoothAdapter ba, Button connect) {
this.ba = ba;
this.context = context;
this.device = device;
this.connect = connect;
bt_port_to_connect = 9;
}
protected void onPreExecute() {
progressDialog=ProgressDialog.show(context,"Please Wait..","Connecting to device",false);
}
#Override
protected String doInBackground(String... arg0) {
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, bt_port_to_connect);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ba.cancelDiscovery();
tmp.connect();
ri = new ReadInput(tmp);
ri.start();
} catch (IOException e) {
Log.e("+++CONNECT1+++","EXCEPTION: " + e.getMessage());
try {
tmp.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + " insecure socket type" +
" socket during connection failure", e2);
}
Log.e("+++CONNECT2+++", e.getLocalizedMessage());
}
boolean isConnected = tmp.isConnected();
if(isConnected) {
return "connected";
}
else {
return "notConnected";
}
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
if(result.equals("connected")) {
connect.setEnabled(false);
Toast.makeText(context, "Connected to device: "+device.getName().toString(), Toast.LENGTH_LONG).show();
//new ReadIn(context, tmp).execute("");
}
else if(result.equals("notConnected")) {
Toast.makeText(context, "Can`t reach host", Toast.LENGTH_LONG).show();
}
}
}
As you can see, the line below tmp.connect(); I create a new object of a new class, this is the class which I want to handle the reading of the inputStream So here is the code for that class:
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ReadInput extends Thread {
BluetoothSocket socket;
private InputStream is;
public ReadInput(BluetoothSocket socket) {
Log.i("READINPUT", "INSIDE READ INPUT THREAD CONSTRUCTOR!!!");
InputStream tmpIn = null;
this.socket = socket;
is = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e("READINPUT", "Temp socket in created: " + e.getMessage());
}
is = tmpIn;
}
public void run() {
Log.i("READINPUT", "INSIDE READ INPUT THREAD RUN METHOD!!!");
byte[] buffer = new byte[1024];
int bytes = 0;
while(true) {
try {
bytes = is.read(buffer);
} catch (IOException e) {
Log.e("FROM RUN METHOD: ", e.getMessage());
}
Log.i("INPUTSTREAM GOT: ", Integer.toString(bytes));
}
}
}
I have two Log.i methods in my last code, this outputs the correct info to LogCat stating where in the code I am. But it doesnt output the content of the stream to LogCat. What am I doing wrong here? Yes, I've looked into the BluetoothChat example.
Thanks in advance!
EDIT 1
I've done some research in the constructor of the ReadInput Class.
is = tmpIn;
try {
Log.i("InputStream: ", Integer.toString(is.available()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This snippet will only output to logcat that is returns 0 which means that the InputStream is not available. Any suggestions?
I found using a buffered reader works well with a blietooth device. And then I just used a while.loop with br.isReady in a while true listener. Basically makes a "listener"
Hi guys im trying to create a application that uses a socket connection i was going across some examples, the piece of code below works fine when i run it on 2.3.3 and the same crashes in 3.0.
package com.simple.client;
import android.app.Activity;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Bundle;
public class SimpleClientActivity extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("172.16.2.172", 8899);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
I have tried all but not able to figure out what is happening,
My guess is, the error caused by StrictMode.ThreadPolicy. In android 3.0, you can't access network in the same UI thread.
Do you have multiple resource folders for your layouts? if yes, maybe you do not have its related layout.
Guys here is my code please review it because it gives NullPointerException on the line conn.setSSLSocketFactory(sslContext.getSocketFactory());........
Code:
package com.halosys.TvAnyTime;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.crypto.NullCipher;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
import android.app.Activity;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HomeScreen extends Activity {
StringEntity entry;
BasicHttpResponse httpResponse;
BufferedReader in = null;
//protected KeyStore sslContext;
KeyStore ksTrust;
TrustManagerFactory tmf;
SSLContext sslContext;
URL url;
HttpsURLConnection conn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button closeButton = (Button)this.findViewById(R.id.button1);
closeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Load the self-signed server certificate
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
return true;
}});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
char[] passphrase = "ssltestcert".toCharArray();
try {
ksTrust = KeyStore.getInstance("BKS");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ksTrust.load(getApplicationContext().getResources().openRawResource(R.raw.ssltestcert),
passphrase);
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
tmf.init(ksTrust);
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a SSLContext with the certificate
/*try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
} catch (KeyManagementException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
// Create a HTTPS connection
try {
url = new URL("https", "https://50.18.49.118/xmlrpcand", 443, "/ssltest");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn = (HttpsURLConnection) url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/* Uncomment the following line of code if you want to skip SSL */
/* hostname verification. But it should only be done for testing. */
/* See http://randomizedsort.blogspot.com/2010/09/programmatically-disabling-java-ssl.html */
// conn.setHostnameVerifier((HostnameVerifier) new NullCipher());
//conn.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
conn.setSSLSocketFactory(sslContext.getSocketFactory());
//MyHttpClient obj= new MyHttpClient(HomeScreen.this);
//obj.createClientConnectionManager();
/* HttpClient httpclient = new DefaultHttpClient();
String str2= "<?xml version=\"1.0\"?><methodCall><methodName>tva1.catalog.version</methodName><params></params></methodCall>";
HttpPost httppost = new HttpPost("https://50.18.49.118/xmlrpcand");
try {
entry = new StringEntity(str2,HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entry.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(entry);
try {
httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
try {
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = sb.toString(); //Responsed xml is stored in result
System.out.print(result);
}
*/ };
});
}
}
Does it print a stack trace just before throwing the exception? If url.openConnection() fails, it throws IOException, but all you're doing to handle that is to print the stack trace. I'd expect problems if you try to use conn after that happens.