If I run my app in the emulator my app crashes immediately. I get the error 'Caused by: java.lang.IllegalArgumentException: host=null, port=4444.' Logcat says the error comes from InetSocketAdress. This is my server code:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* Created by Charlie on 26-3-2015.
*/
public class Server extends AsyncTask<Void, Void, String> {
private String message;
private String ip;
public static int port = 4444;
private String serverResponse = null;
public Server(String ip, int port, String message ) {
super();
//IP, Port en bericht om naar server te sturen
this.message = message;
this.ip = ip;
this.port = port;
}
#Override
protected String doInBackground(Void... params) {
try {
Socket serverSocket = new Socket();
serverSocket.connect(new InetSocketAddress(this.ip, this.port), 4444);
this.sendMessage(message, serverSocket);
InputStream input;
try {
input = serverSocket.getInputStream();
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(input));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();
this.serverResponse = stringBuilder.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Response: " + serverResponse);
} catch (UnknownHostException e) {
Log.d("debug", "can't find host");
} catch (SocketTimeoutException e) {
Log.d("debug", "time-out");
} catch (IOException e) {
e.printStackTrace();
}
return serverResponse;
}
private void sendMessage(String message, Socket serverSocket) {
OutputStreamWriter outputStreamWriter = null;
try {
outputStreamWriter = new OutputStreamWriter(serverSocket.getOutputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
if (outputStreamWriter != null) {
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
PrintWriter writer = new PrintWriter(bufferedWriter, true);
writer.println(message);
}
}
}
The code of the class where the user can fill in the IP:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.ExecutionException;
public class GebruikerIP extends Activity {
private Boolean serverCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Slotenbedrijf De Sleutelaar");
//Check voor internet verbinding
if(NetwerkCheck.isInternetAvailable(GebruikerIP.this))
{
}
else
{
Toast.makeText(GebruikerIP.this, "Er is helaas geen internetverbinding geconstateerd, daarom wordt nu de laatst opgehaalde informatie getoond.!", Toast.LENGTH_LONG).show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gebruikerip);
Button ipButton = (Button) findViewById(R.id.serverbutton);
ipButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
verbindServer();
}
});
//Enter key afvangen
EditText ipInvoer = (EditText) findViewById(R.id.ipinvoeren);
ipInvoer.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_ENTER:
verbindServer();
break;
default:
return false;
}
return true;
}
});
}
//server connectie maken voor ophalen van diensten
public void verbindServer() {
TextView ipVeld = (TextView) findViewById(R.id.ipinvoeren);
String ip = ipVeld.getText().toString();
Log.i("ip", ip);
String response = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("slotenlijst", "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
try {
response = new Server(ip,
4444, jsonObject.toString()).execute().get();
//exceptions afvangen
} catch (InterruptedException e)
{
}
} catch (ExecutionException e1)
{
}
if (response == null) {
serverCheck = false;
Toast.makeText(this, "Verbinden met server mislukt, staat server aan?", Toast.LENGTH_LONG).show();
} else {
//doorgaan naar MainActivity
serverCheck = true;
HoofdschermFragment.serverIp = ip;
Intent startApp = new Intent(this, MainActivity.class);
startActivity(startApp);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_gebruiker_ip, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
I can't find out how I can fix this error. Help would me appreciated. Thanks!
change it to
InetAddress inetServer = InetAddress.getByName(IP);
than
Socket socket = new Socket(inetServer, devicePort);
and if you are using for Server Socket than use below line
ServerSocket socket = new ServerSocket(devicePort,int backlognumber, inetServer);
Related
My data is not inserting to database of webhost.
Here is my ActionActivity.java from where I will send data to the database.
import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
public class ActionActivity extends Activity {
private String t;
TextView timer;
EditText e1,e2;
Button save;
static InputStream is = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action);
Bundle time = getIntent().getExtras();
t = (String) time.get("com.example.masba.timemanagement.MESSAGE");
e1 = (EditText) findViewById(R.id.editText);
e1.setText(t, TextView.BufferType.EDITABLE);
e2 = (EditText) findViewById(R.id.editText2);
save = (Button) findViewById(R.id.save);
}
public void insert(View view){
String actionName = e1.getText().toString();
String time = e2.getText().toString();
Toast.makeText(this, "Data Inserting...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(actionName, time);
e1.setText("");
e2.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Now my SignupActivity.java Which extends Asynctask.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String actionName = arg0[0];
String time = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?actioname=" + URLEncoder.encode(actionName, "UTF-8");
data += "&time=" + URLEncoder.encode(time, "UTF-8");
link = "http://masumalmasba.comli.com/insertdata.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Now my insertdata.php code is:
<?php
$servername="mysql6.000webhost.com";
$username = "a1871724_masum";
$password = "almasba012";
$dbname = "a1871724_actiont";
$conn = new mysqli($servername , $username , $password , $dbname);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$action = $_GET['actionname'];
$time = $_GET['time'];
$sql = "INSERT INTO actiontime (name,time) VALUES ('($action)','($time)')";
if($conn->query($sql)===TRUE){
echo "New record created succesfully";
}
else{
echo "Error";
mysql_close($conn);
}
?>
I have two seekbars in my main activity but I can only use one of them at a time, so I need to retrieve a value seekbarx and seekbary, store either of them in a string variable to use it forward. I already used onProgressChange and onStopTrackingTouch but I guess it doesn't hold the value long enough.
This is what I had for the seekbars
package edu.itdurango.servocontrolyun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
// TODO: adjust ARDUINO_IP_ADDRESS
public final String ARDUINO_IP_ADDRESS = "192.168.1.71"; //Dirección IP del Arduino Yun
public final String TAG = "ArduinoYun";
public String servo;
private SeekBar SeekBarX; //Barra de búsqueda del eje X
private SeekBar SeekBarY; //Barra de búsqueda del eje Y
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBarX = (SeekBar) findViewById(R.id.barraEjeX);
/*SeekBarX.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeX) {
servo = "servox/";
}
});*/
SeekBarX.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onProgressChanged(SeekBar barraEjeX, int progressX,
boolean fromUser) {
servo = "servox/";
log("touching X bar. servo = " + servo);
QueueX.offer(progressX);
}
});
SeekBarY = (SeekBar) findViewById(R.id.barraEjeY);
/*SeekBarY.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeY) {
servo = "servoy/";
}
});*/
SeekBarY.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onProgressChanged(SeekBar barraEjeY, int progressY,
boolean fromUser) {
servo = "servoy/";
log("touching Y bar. servo = " + servo);
QueueY.offer(progressY);
}
});
}
#Override
protected void onStart() {
mStop.set(false);
if(sNetworkThreadSend == null){
sNetworkThreadSend = new Thread(mNetworkRunnableSend);
sNetworkThreadSend.start();
}
super.onStart();
}
#Override
protected void onStop() {
mStop.set(true);
QueueX.clear();
QueueX.offer(-1);
QueueY.clear();
QueueY.offer(-1);
if(sNetworkThreadSend != null) sNetworkThreadSend.interrupt();
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void log(String s){
Log.d(">==< "+TAG+" >==<", s);
}
private ArrayBlockingQueue<Integer> QueueX = new ArrayBlockingQueue<Integer>(100);
private ArrayBlockingQueue<Integer> QueueY = new ArrayBlockingQueue<Integer>(100);
private AtomicBoolean mStop = new AtomicBoolean(false);
private static Thread sNetworkThreadSend = null;
private final Runnable mNetworkRunnableSend = new Runnable() {
#Override
public void run() {
log("starting network thread for sending");
String urlBase = "http://"+ARDUINO_IP_ADDRESS+"/arduino/"+servo;
String url;
try {
while(!mStop.get()){
int val;
if (servo == "servoy/"){
val = QueueY.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
if (servo == "servox/"){
val = QueueX.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
log("returning from network thread for sending");
sNetworkThreadSend = null;
}
};
private static Thread sNetworkThreadReceive = null;
private final Runnable mNetworkRunnableReceive = new Runnable() {
#Override
public void run() {
log("starting network thread for receiving");
String url = "http://"+ARDUINO_IP_ADDRESS+"/data/get/D9";
while(!mStop.get()){
try {
String string = readURL(url);
String value = "";
try {
JSONObject jsonMain = new JSONObject(string);
value = jsonMain.get("value").toString();
log("value = "+value);
} catch (Exception e) {
e.printStackTrace();
}
updateText(value);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log("returning from network thread for receiving");
sNetworkThreadReceive = null;
}
};
public void updateText(final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(value);
}
});
}
public String readURL(String value){
URL url;
StringBuilder builder = new StringBuilder();
try {
url = new URL(value);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
builder.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
It prints in the LogCat touching Y bar. servo = servoy/ but when I want to use the servo value it prints null.
How can I hold the value for this string?
I'm trying to get strings from my Arduino with my Android phone, everything goes well except for when I press my updatebutton the second time, it unfortunately stops.
I can't seem to track the problem and I ran out of options so I'm asking for help to you guys now.
package com.TRY.udp2;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private String rcvStr, serverIP="192.168.0.15";
private TextView textLog;//Log for outputs
private EditText textMsg;
Button updateButton;//(dis)connect Button
Boolean connected=false;//stores the connectionstatus
DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button updateButton = (Button) findViewById(R.id.updateButton);
textMsg = (EditText) findViewById(R.id.textMsg);
textLog = (TextView) findViewById(R.id.textLog);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String textlogMsg = textMsg.getText().toString();
new synchTask().execute(textlogMsg);
}
});
}
private class synchTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String msg=params[0].toString();
InetAddress toAddress = null;
try
{
toAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
int port=5000;
DatagramSocket dtSocket = null;
try
{
dtSocket = new DatagramSocket(port);
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] dataBytes = msg.getBytes();
DatagramPacket sndPacket = new DatagramPacket(dataBytes, dataBytes.length, toAddress, port);
try
{
dtSocket.send(sndPacket);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
return rcvStr;
}
protected void onPostExecute(String result) {
textLog.setText(rcvStr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and if there's a better way of getting strings from arduino please help out.
You probably need to close dtSocket at the end of doInBackground(). Otherwise you will try to create a socket on a bound port when you execute it the second time.
Heres my Server Code
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Threading;
public class SynchronousSocketListener
{
private const int portNum = 4444;
private static ArrayList ClientSockets;
private static bool ContinueReclaim = true;
private static Thread ThreadReclaim;
public static void StartListening()
{
ClientSockets = new ArrayList();
ThreadReclaim = new Thread(new ThreadStart(Reclaim));
ThreadReclaim.Start();
TcpListener listener = new TcpListener(portNum);
try
{
listener.Start();
int TestingCycle = 3;
int ClientNbr = 0;
// Start listening for connections.
Console.WriteLine("Waiting for a connection...");
while (TestingCycle > 0)
{
TcpClient handler = listener.AcceptTcpClient();
if (handler != null)
{
Console.WriteLine("Client#{0} accepted!", ++ClientNbr);
// An incoming connection needs to be processed.
lock (ClientSockets.SyncRoot)
{
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
Console.WriteLine("Added sock {0}", i);
}
--TestingCycle;
}
else
break;
}
listener.Stop();
ContinueReclaim = false;
ThreadReclaim.Join();
foreach (Object Client in ClientSockets)
{
((ClientHandler)Client).Stop();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
private static void Reclaim()
{
while (ContinueReclaim)
{
lock (ClientSockets.SyncRoot)
{
for (int x = ClientSockets.Count - 1; x >= 0; x--)
{
Object Client = ClientSockets[x];
if (!((ClientHandler)Client).Alive)
{
ClientSockets.Remove(Client);
Console.WriteLine("A client left");
}
}
}
Thread.Sleep(200);
}
}
public static int Main(String[] args)
{
while (true)
{
StartListening();
}
return 0;
}
}
class ClientHandler
{
TcpClient ClientSocket;
bool ContinueProcess = false;
Thread ClientThread;
public ClientHandler(TcpClient ClientSocket)
{
this.ClientSocket = ClientSocket;
}
public void Start()
{
ContinueProcess = true;
ClientThread = new Thread(new ThreadStart(Process));
ClientThread.Start();
}
private void Process()
{
// Incoming data from the client.
string data = null;
// Data buffer for incoming data.
byte[] bytes;
if (ClientSocket != null)
{
NetworkStream networkStream = ClientSocket.GetStream();
ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds
while (ContinueProcess)
{
bytes = new byte[ClientSocket.ReceiveBufferSize];
try
{
int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize);
//BytesRead--;
if (BytesRead > 0)
{
Console.WriteLine("Bytes Read - Debugger " + BytesRead);
data = Encoding.ASCII.GetString(bytes, 0, BytesRead);
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] sendBytes = Encoding.ASCII.GetBytes("I rec ya abbas");
networkStream.Write(sendBytes, 0, sendBytes.Length);
if (data == "quit") break;
}
}
catch (IOException) { } // Timeout
catch (SocketException)
{
Console.WriteLine("Conection is broken!");
break;
}
Thread.Sleep(200);
} // while ( ContinueProcess )
networkStream.Close();
ClientSocket.Close();
}
} // Process()
public void Stop()
{
ContinueProcess = false;
if (ClientThread != null && ClientThread.IsAlive)
ClientThread.Join();
}
public bool Alive
{
get
{
return (ClientThread != null && ClientThread.IsAlive);
}
}
} // class ClientHandler
Heres my Client Code:
package com.example.socketclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class SocketCode extends Activity {
public TextView txt;
protected SocketCore Conn;
public Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_code);
b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
Conn = new SocketCore(this,txt);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Conn.execute();
}
});
}
}
SocketCore
package com.example.socketclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
class SocketCore extends AsyncTask<Context, Integer, String>
{
String text = "";
String finalText = "";
private Context ctx;
ProgressDialog dialog;
TextView Msg;
Socket socket;
public SocketCore(Context applicationContext,TextView Change)
{
// TODO Auto-generated constructor stub
ctx = applicationContext;
dialog = new ProgressDialog(applicationContext);
Msg = Change;
}
#Override
protected String doInBackground(Context... arg0) {
// TODO Auto-generated method stub
try {
InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
Log.d("TCP", "C: Connecting....");
socket = new Socket(serverAddr,4444);
// Log.d("TCP", "C: I dunno ...");
String message = "Hello Server .. This is the android client talking to you .. First we are testing Server Crashing";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//serverReturnString = System.Text.Encoding.ASCII.GetString(response, 0, bytes);
out.println("quit");
//out.print("h");
while ((text = in.readLine()) != null) {
finalText += text;
if(text=="quit")
{
socket.close();
}
Log.d("TCP", "C: Done."+finalText);
}
// Msg.setText("LOLZ");
Log.d("TCP", "C: Sent.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} /*finally {
socket.close();
Log.d("TCP", "S: Closed");
} */
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
//dialog.setMessage("Recieved: "+finalText);
return "COMPLETE";
}
protected void onPostExecute(String x)
{
super.onPostExecute("Finished");
dialog.dismiss();
Msg.setText(finalText);
}
protected void onPreExecute()
{dialog.setTitle("Initializing Connection");
dialog.setMessage("Connecting");
dialog.show();
}
}
Server can read from android phone also the android client get message from server.
The Problem is whenever The Server detects connection and start Receives text and Sends Reply . The code doesnt accept more connection after that .
Note:
I tried to to test using C# client it works fine so i got a problem on the client side
You can't use more then AsyncTask.
The simplest approach is to move the code inside doInBackground() to a Runnable and then start a new Thread with that runnable on every click.
Example:
private Runnable rSocketCore = new Runnable() {
public void run() {
//here goes your connection code
}
};
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(rSocketCore).start();
}
Note: You will also need an Handler if you want to communicate from the thread to the UI.
Regards.
Hey all..I am struck here, I have to display news in a separate list view from a news link web site, but when I debug the cursor goes null. How do I resolve this? Here is my code
package adn.GoMizzou.NB;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class NB extends ListActivity {
public static final String URL = "http://nbsubscribe.missouri.edu/news-releases/feed/atom/";
private String msg;
private boolean success;
private int scrollIndex;
private int scrollTop;
private HttpClient httpClient;
private NBDBAdapter dbAdapter;
private ProgressDialog pDialog;
private Context ctx = this;
private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
//private Cursor cur;
private Cursor q;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg){
pDialog.dismiss();
fillList();
}
};
/* ACTIVITY METHODS */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.nb);
setTitle("News");
q=null;
scrollIndex = 0;
dbAdapter = new NBDBAdapter(this);
dbAdapter.open();
registerForContextMenu(getListView());
getData();
}
public void getData(){
pDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
new Thread(){
public void run(){
dbAdapter.deleteAll();
dbAdapter.close();
doPost(URL, "");
dbAdapter.open();
handler.sendEmptyMessage(0);
}
}.start();
}
public boolean doPost(String url, String postMsg){
HttpResponse response = null;
createHttpClient();
try {
URI uri = new URI(url);
HttpPost httppost = new HttpPost(uri);
StringEntity postEntity = new StringEntity(postMsg);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
postEntity.setContentType("application/x-www-form-urlencoded");
httppost.setEntity(postEntity);
response = httpClient.execute(httppost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response == null){
msg = "No internet connection.";
return false;
}
if(response.getStatusLine().getStatusCode()!= 200){
msg = "Server error.";
return false;
}
return doParse(response);
}
public void createHttpClient(){
if(httpClient == null){
httpClient = new DefaultHttpClient();
}
}
public boolean doParse(HttpResponse response){
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
NBParser respHandler = new NBParser(ctx);
xr.setContentHandler(respHandler);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buffEntity = new BufferedHttpEntity(entity);
xr.parse(new InputSource(buffEntity.getContent()));
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
if(e.getMessage().toString().contains("nothing found")){
msg = e.getMessage().toString();
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = q;
q.moveToPosition(position);
//Intent i = new Intent(this, NB.class);
//i.putExtra("link", c.getString(c.getColumnIndexOrThrow(NBDBAdapter.NB_LINK)));
String newsLinkString = q.getString(q.getColumnIndexOrThrow(NBDBAdapter.NB_LINK));
TextView linkTV = (TextView) v.findViewById(R.id.rowlink);
newsLinkString = linkTV.getText().toString();
if (newsLinkString.startsWith("http://")){
Uri uri = Uri.parse(newsLinkString);
Intent i = new Intent(this, NB.class);
// Save ListView position
i.putExtra("link", c.getString(c.getColumnIndexOrThrow(NBDBAdapter.NB_LINK)));
startActivity(i);
}
}
//else {
//showLinkError();
//}
// Sends an error message to the user if the news item link is malformed
//public void showLinkError() {
//Toast.makeText(getApplicationContext(), "Error - Link to story unavailable with news source could not load the News Story", Toast.LENGTH_SHORT).show();
//}
private void showLinkError() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Error - Link to story unavailable with news source could not load the News Story", Toast.LENGTH_SHORT).show();
}
public void fillList(){
if(!success) {
TextView emptyView = (TextView) findViewById(android.R.id.empty);
emptyView.setText(msg);
msg = "";
}
if(!dbAdapter.isOpen()) dbAdapter.open();
Cursor cursor = dbAdapter.fetchAll();
startManagingCursor(cursor);
String [] from = new String[] { dbAdapter.NB_AUTHOR, dbAdapter.NB_TITLE,dbAdapter.NB_LINK };
int[] to = new int[] { R.id.rowAuthor, R.id.rowTitle, R.id.rowlink };
SimpleCursorAdapter list = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
setListAdapter(list);
}
}
Which cursor are you talking about?
If it's when you click on an item it's because you assign the cursor q null in onCreate and then call moveToPosition on it in onListItemClick.