I have a problem. When I run my android program I have a error: "unfortunately has stopped android". Why I see this error when I run application? hear is my file:
enter code here
import java.io.IOException;
import java.io.PrintWriter;
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;
public class SimpleClientActivityActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//textField = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//messsage = textField.getText().toString(); //get the text message on the text field
//textField.setText(""); //Reset the text field to blank
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
I would like to send sms to PC server with my adnroid client
It may be because you are doing network operations on the main thread. Look into your logcat and there will be info, in red.
try this
new Thread(){
#Override
public void run(){
// your onClick code here
}
}.start();
Also you can use AsyncTask for network operations
public class YourTask extends AsyncTask{
private Context context;
private ProgressDialog dialog;
public SplitCueTask(Context context) {
this.context = context;
this.dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage(getResources().getString(R.string.loading));
dialog.show();
}
#Override
protected Boolean doInBackground(Object... objects) {
// you logic here, return result
return someObject.
}
#Override
protected void onPostExecute(Object someObject) {
if (dialog.isShowing())
dialog.dismiss()
// handle result here, post it on UI or something else
}
}
Run task
new YourTask(context).execute();
And dont forget to add INTERNET PERMISSION to AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
Related
The problem as seen in the title appears in line 102 of the code down below. Im very new to this topic and Im trying to make an app which can control an arduino... This part of code I show you is supposed to manage the connection to the Bluetooth Module and in my MainActivity I plan to send the letters to the other device.
I hope someone can help.
My code (BT_Classic.java):
package com.car.bluetooth.bluetoothcar;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BT_Classic extends AppCompatActivity {
private Button pairedButton;
private Button discoveredButton;
private Button btonButton;
private Button btoffButton;
private ProgressDialog progress;
ListView listView;
BluetoothSocket bluetoothSocket;
BluetoothDevice bluetoothDevice;
private final static UUID uuid = UUID.fromString("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
private ArrayList<String> mDeviceList = new ArrayList<String>();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
//BLUETOOTH VERBINDUNG
private static final int REQUEST_ENABLED = 0;
private static final int REQUEST_DISCOVERABLE = 0;
private class ConnectingThread extends Thread {
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
BluetoothDevice bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
btAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
/*
manageBluetoothConnection(bluetoothSocket);
*/
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt__classic);
pairedButton = (Button) findViewById(R.id.pairedButton);
discoveredButton = (Button) findViewById(R.id.discoveredButton);
btonButton = (Button) findViewById(R.id.btonButton);
btoffButton = (Button) findViewById(R.id.btoffButton);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = btAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
//Pairing Button
pairedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<String>();
for (BluetoothDevice bt : pairedDevices){
devices.add(bt.getName());
devices.add(bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(BT_Classic.this, android.R.layout.simple_list_item_1, devices);
listView.setAdapter(arrayAdapter);
}
});
discoveredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!btAdapter.isDiscovering()){
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(bton, REQUEST_DISCOVERABLE);
}
}
});
btonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bton, REQUEST_ENABLED);
}
});
btoffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.disable();
}
});
}
}
You have an extra } in this section
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
} // Close try
} // Close cancel()
} // Close ConnectingThread
} // DELETE THIS CURLY BRACE
First, it was problem with extra curly braces as Chris has mentioned.
Second, you haven't define your ListView as listView = findViewById(R.id.your_id);
That's it, and good luck. :)
I want to send data via a socket on a button click while I am connected to the server. I tried to call the setOnClickListener inside my ConnectTask class and also in my TcpClient class, but it shows me an error. While I create it inside ConnectTask, it does not show me an error but it did not work. How can I do it? Below are my classes.
Here is my main class:
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.util.Log;
import android.widget.EditText;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
Button btn;
EditText edt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
edt=(EditText)findViewById(R.id.editText);
ConnectTask connectTask=new ConnectTask();
connectTask.execute("testing");
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
Log.d("TCP Client", "checking");
TcpClient mTcpClient;
//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
}
And here is my TcpClient class:
import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.os.Handler;
import static android.os.Looper.*;
public class TcpClient extends MainActivity{
public static final String TAG = TcpClient.class.getSimpleName();
public static final String SERVER_IP = "10.0.2.2"; //server IP address
public static final int SERVER_PORT = 9000;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = true;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
Context context=getApplicationContext();
/**
* Constructor of the class. OnMessagedReceived listens for the messages
received from server
*/
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(final String message) {
Runnable runnable = new Runnable() {
#Override
public void run() {
if (mBufferOut != null) {
Log.d(TAG, "Sending: " + message);
mBufferOut.println(message);
mBufferOut.flush();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
/**
* Close the connection and release the members
*/
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run () {
mRun = true;
try {
//here you must put your computer's IP address.
//InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
if(socket.isConnected()){
Log.d("hati","connected");
}
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
sendMessage("testing");
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null)
{
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) must be implemented in the Activity
//class at on AsyncTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
Move TcpClient mTcpClient to MainActivity class:
public class MainActivity extends AppCompatActivity {
Button btn;
EditText edt;
TcpClient mTcpClient;
Remove TcpClient mTcpClient; from protected TcpClient doInBackground
protected TcpClient doInBackground(String... message) {
Log.d("TCP Client", "checking");
// remove this line TcpClient mTcpClient
add action listener to your button and call tcpClientto send message
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTcpClient.senMessage("get Text from text box");
}
});
edt=(EditText)findViewById(R.id.editText);
ConnectTask connectTask=new ConnectTask();
connectTask.execute("testing");
}
public class TcpClient extends MainActivity{
Pretty bad to not have Activity in the name of a class that extends an activity. To make your code more readable you should change that to
public class TcpClientActivity extends MainActivity{
You would then get
mTcpClient = new TcpClientActivity(new TcpClientActivity.OnMessageReceived() {
upon which every body would stand up and cry: You are not allowed to instantiate an activity with the new operator.
First of all, I should say that I am a newbie on Java and Android programming. I am very experienced in C programming for embedded systems, but now I need to communicate one of my embedded projects with an Android app, in a very simple way. I am using one of those ESP8266, configured as default. Thus, it behaves as a basic telnet server. My microcontroller has to send a question (through a string, which is not constant) to my app, and receive a "Y" or "N" reply. I have tested it using a telnet client, and it is working fine. However, I want to have an app that pops up an alert dialog and/or show the message in a TextView element, and sends the reply after some button click. For this, I have adapted a telnet client code from:
http://android-er.blogspot.com.br/2014/08/simple-android-chat-application-client.html
I have put everything in one single panel, and reduced the number of elements to a textview element and 4 buttons (connect, disconnect, yes, and no). I am using a fixed IP and port to connect the app to my laptop, which is running a telnet server (hercules). The connection is confirmed, and the YES and NO buttons are sending the correct messages. However, the question string never shows up at the TextView element. I have also added an AlertDialog to pop up, because I think it is more appropriate to the kind of app I am developing.
Notice that the testing of the message income happens inside a thread, and I am calling the TextView update and the AlertDialog show using runOnUiThread.
Here is the Java code (not optimized yet):
package br.unicamp.smpci;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
static final int SocketServerPORT = 80;
final Context context = this;
LinearLayout Panel;
Button buttonConnect;
TextView chatMsg;
Button buttonSendYes;
Button buttonSendNo;
Button buttonDisconnect;
String msgLog = "";
ChatClientThread chatClientThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Panel = (LinearLayout)findViewById(R.id.panel);
buttonConnect = (Button) findViewById(R.id.connect);
buttonDisconnect = (Button) findViewById(R.id.disconnect);
chatMsg = (TextView) findViewById(R.id.chatmsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
buttonSendYes = (Button)findViewById(R.id.sendYes);
buttonSendYes.setOnClickListener(buttonSendYesOnClickListener);
buttonSendNo = (Button)findViewById(R.id.sendNo);
buttonSendNo.setOnClickListener(buttonSendNoOnClickListener);
}
OnClickListener buttonDisconnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.disconnect();
}
};
OnClickListener buttonSendYesOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
};
OnClickListener buttonSendNoOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("N" + "\n");
}
};
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String textAddress = "192.168.1.11";
msgLog = "NO MESSAGES";
chatMsg.setText(msgLog);
chatClientThread = new ChatClientThread(
textAddress, SocketServerPORT);
chatClientThread.start();
}
};
private class ChatClientThread extends Thread {
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
ChatClientThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog = dataInputStream.readUTF();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
chatMsg.invalidate();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("ALERT");
alertDialogBuilder
.setMessage(MsgLog)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (chatClientThread == null) {
return;
}
chatClientThread.sendMsg("N" + "\n");
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} 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();
}
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//loginPanel.setVisibility(View.VISIBLE);
//chatPanel.setVisibility(View.GONE);
}
});
}
}
private void sendMsg(String msg){
msgToSend = msg;
}
private void disconnect(){
goOut = true;
}
}
}
I have done extensive research on how to make sure that the UI thread updates my elements, and I am using the Show() method for the alertdialog, and invalidating the TextView element to force it to update. I have used debug, and I am sure that the instructions are being executed, but with no result on my app ( I am using a real device for debugging).
I have seen that maybe I could use AsyncTask for this purpose, but as a newbie I am facing difficulties to make the changes, and I believe that calling the updates with a runOnUiThread should do the work.
Can anyone explain why I cannot see my message, and maybe provide me a code correction?
Thanks in advance,
Antonio Quevedo
I am getting this error on line 174
code was working fine but after last update I am getting this error that Cannot initiate the type View.onclicklistner
this is client code for chat functionality using websockets
how to fix this???
package de.lauridmeyer.com.tests;
import org.jwebsocket.api.WebSocketClientEvent;
import org.jwebsocket.api.WebSocketClientTokenListener;
import org.jwebsocket.api.WebSocketPacket;
import org.jwebsocket.client.plugins.rpc.Rpc;
import org.jwebsocket.client.plugins.rpc.RpcListener;
import org.jwebsocket.client.plugins.rpc.Rrpc;
import org.jwebsocket.client.token.BaseTokenClient;
import org.jwebsocket.kit.WebSocketException;
import org.jwebsocket.token.Token;
import org.jwebsocket.token.TokenFactory;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SimpleJWAndroidClientActivity extends Activity implements WebSocketClientTokenListener{
//GUI Elements
private static TextView log;
private static TextView Chatlog;
private static EditText ipadress;
private static EditText Message;
private static Button send;
private static Button conBtn;
private String entered_msg=null;
TextView customDialog_TextView;
Button customDialog_Yes, customDialog_No;
static final int CUSTOM_DIALOG_ID = 0;
public static String decision=null;
//stores if the SLider is changed by the user or the server
private static Boolean isDragging=false;
//stores the connection status
private static Boolean connected=false;
//used for the connection
private static BaseTokenClient btc = new BaseTokenClient();//create a new instance of the base token client
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
log = (TextView)findViewById(R.id.log);//Textview to Display Messages
ipadress=(EditText)findViewById(R.id.ipadress);//inputfield for the ipadress
Chatlog=(TextView)findViewById(R.id.chat);
conBtn= (Button)findViewById(R.id.conBtn);//(dis)connection button
Message=(EditText)findViewById(R.id.Message);
send= (Button)findViewById(R.id.Send);
//add the listener for the slider and the (dis)connection Button
conBtn.setOnClickListener(buttonConnectOnClickListener);
//add the listener for the websocket connection
btc.addListener(this);//add this class as a listener
btc.addListener(new RpcListener());//add an rpc listener
Rpc.setDefaultBaseTokenClient(btc);//set it to the default btc
Rrpc.setDefaultBaseTokenClient(btc);//same here
//set the connection status to "not connected" on startup
changeConnectionStatus(false);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
entered_msg = Message.getText().toString();
Token firstToken = TokenFactory.createToken("com.lauridmeyer.tests.LauridsPlugIn","Welcomemessage");
firstToken.setString("message",entered_msg);//add the message to the token
try {
btc.sendToken(firstToken);//try to send the token to the server
} catch (WebSocketException ex) {
outputText("error:"+ex.getMessage());//log errors
}
}
});
}
private OnClickListener buttonConnectOnClickListener = new OnClickListener() {
public void onClick(View v){
if(!connected){//if not connected
try{
String ipAdress=ipadress.getText().toString();//get the ip-adress from the inputfield
outputText("connecting to "+ipAdress+" ...");//debug
btc.open(ipAdress);//try to open the connection to your server
}catch(Exception e){
outputText("Error while connecting...");//log errors
}
}else{//if connected
try{
btc.close();//try to close
}catch(Exception e){
outputText(e.toString());//log errors
}
}
}
};
// private static SeekBar.OnSeekBarChangeListener seekbarchangedListener = new SeekBar.OnSeekBarChangeListener(){
// //Method is fired everytime the seekbar is changed
// #Override
// public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// if(isDragging && connected){//if the ssekbar is changed by the user and not by the server
// //create a new Token with the namspace, and type
// Token tempToken = TokenFactory.createToken("com.lauridmeyer.tests.LauridsPlugIn","sliderChanged");
// tempToken.setInteger("value",progress);//add an integer to the token
// try {
// btc.sendToken(tempToken);//try to send the token to the server
// } catch (WebSocketException ex) {
// outputText("error:"+ex.getMessage());//log errors
// }
// }
// }
//
// #Override
// public void onStartTrackingTouch(SeekBar seekBar) {
// isDragging=true;//turn the sending mechanism on
// }
//
// #Override
// public void onStopTrackingTouch(SeekBar seekBar) {
// isDragging=false;//turn the sending mechanism off
// }
// };
/* Method is called when the connection status has changed
* connected <-> disconnected */
public static void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
//seekBar.setEnabled(isConnected);//enable/disable seekbar
if(isConnected){//if connection established
outputText("successfully connected to server");//log
conBtn.setText("DISCONNECT");//change Buttontext
}else{
outputText("disconnected from Server!");//log
conBtn.setText("CONNECT");//change Buttontext
}
}
/* Method prints text to the log textfield*/
public static void outputText(String msg) {
log.append(msg+"\n");
}
/* Message handler is used to process incoming tokens from the server*/
private Handler messageHandler = new Handler() {
#Override
public void handleMessage(Message aMessage) {
if(aMessage.what==0){//if it's a token
Token aToken =(Token) aMessage.obj;//get the received token
//if the namespace matches my plugin
if(aToken.getNS().equals("com.lauridmeyer.tests.LauridsPlugIn")){
//and it's a command that the slider has changed
//String wM = aToken.getString("Welcomemessage");
if(aToken.getString("reqType").equals("sliderHasChanged")){
int value=aToken.getInteger("value");//get the slider value
isDragging=false;//make sure that the slider changes are not recognized as user inputs
//seekBar.setProgress(value);//move the slider to the recieved position
}
if(aToken.getString("reqType").equals("Welcomemessage")){
String message=aToken.getString("Welcomemessage");//get the slider value (here)
Chatlog.setOnClickListener(new View.OnClickListener());
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
}
}
}
};
#Override
public void processOpened(WebSocketClientEvent aEvent) {
changeConnectionStatus(true);//when connected change the status
}
#Override
public void processClosed(WebSocketClientEvent aEvent) {
changeConnectionStatus(false);//when disconnected change the status
}
#Override
public void processToken(WebSocketClientEvent aEvent, Token aToken) {
//for some reason you can't process the token directly
//you have to use the messagehandler
Message lMsg = new Message();//create a new mess
lMsg.what = 0;
lMsg.obj = aToken;
messageHandler.sendMessage(lMsg);
}
//following Methods are not used in this example, but have to be there :)
#Override
public void processPacket(WebSocketClientEvent aEvent, WebSocketPacket aPacket) {
}
#Override
public void processOpening(WebSocketClientEvent aEvent) {
}
#Override
public void processReconnecting(WebSocketClientEvent aEvent) {
}
}
The line:
Chatlog.setOnClickListener(new View.OnClickListener());
It doesn't look like you're overriding a onClick() method.
I am trying to send data from android app
Client class src:
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class CClient
implements Runnable
{
private Socket socket;
private String ServerIP = "10.0.0.14";
public void run()
{
try
{
socket = new Socket("10.0.0.14", 16606);
}
catch(Exception e)
{
System.out.print("Whoops! It didn't work!:");
System.out.print(e.getLocalizedMessage());
System.out.print("\n");
}
}
public void Send(String s)
{
try
{
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
outToServer.print(s + "\n");
outToServer.flush();
}
catch (UnknownHostException e) {
System.out.print(e.toString());
} catch (IOException e) {
System.out.print(e.toString());
}catch (Exception e) {
System.out.print(e.toString());
}
}
}
Use CClient class in activity to create connection and send data.
Here is activity code
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
public class Auth extends Activity {
private ProgressBar mProgress;
private TextView mTV;
private CClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
mTV = (TextView) findViewById(R.id.textView4);
mClient = new CClient();
Thread myThready = new Thread(mClient);
myThready.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auth, menu);
return true;
}
public void proc_Login(View v)
{
for (int i=0; i<5; i++)
mClient.Send("asaadsasdasd");
}
}
Problem: recive only one message from client (C# server, without any errors) and next messages wont sent.
This code works. I had to add a simple button to trigger the proc_Login call, I tested with netcat -l -p 8546 on my server (debian), I got 5 'asaadsasdasd' each time I pressed the button.
(I used the port 8546 because it was already opened on my firewall).
Of course I added
<uses-permission android:name="android.permission.INTERNET" />
in the AndroidManifest.xml file.
Maybe your server code closes the socket after receiving a line.
Note also you don't need a Thread, an AsyncTask would be more appropriate, though for the example it works.
MainActivity.java:
package com.defranoux.testtcpsend;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private CClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mClient = new CClient();
Thread myThready = new Thread(mClient);
myThready.start();
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
proc_Login(arg0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void proc_Login(View v)
{
for (int i=0; i<5; i++)
mClient.Send("asaadsasdasd");
}
}
CClient.java:
package com.defranoux.testtcpsend;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class CClient
implements Runnable
{
private Socket socket;
private String ServerIP = "<my server ip goes here>";
private static final int ServerPort = 8546;
#Override
public void run()
{
try
{
socket = new Socket(ServerIP, ServerPort);
}
catch(Exception e)
{
System.out.print("Whoops! It didn't work!:");
System.out.print(e.getLocalizedMessage());
System.out.print("\n");
}
}
public void Send(String s)
{
try
{
PrintWriter outToServer = new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()));
outToServer.print(s + "\n");
outToServer.flush();
}
catch (UnknownHostException e) {
System.out.print(e.toString());
} catch (IOException e) {
System.out.print(e.toString());
}catch (Exception e) {
System.out.print(e.toString());
}
}
}
You are never cleaning up the connection to the server. You need to close these output stream once you flush the stream.
outToServer.flush();
outToServer.close();