i'm new in android and i'm trying to pass a string from a TextView from the MainActivity to the Client.java class without activity.
I'm actually trying to make it doing in MainActivity :
Intent i = new Intent(MainActivity.this, Client.class);
i.putExtra("STRING_I_NEED", String.valueOf(indr));
While in Client :
Context context;
Intent intent = ((Activity) context).getIntent();
static Bundle getIp = getIntent.getExtra("STRING_I_NEED");
public static final Bundle SERVERIP = getIp;
But that's saying "
Cannot resolve symbol "getIntent" in the string
static Bundle getIp = getIntent.getExtra("STRING_I_NEED");
Client code:
public class Client {
private static String mIP= "";
private String serverMessage;
public static final String SERVERIP = mIP;
public static final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedReader in;
public void setIp(String _IP) {
mIP = _IP;
}
public Client(OnMessageReceived listener) {
mMessageListener = listener;
}
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
InetAddress serverAddr = InetAddress.getByName(String.valueOf(SERVERIP));
Log.e("TCP Client", "C: Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
public interface OnMessageReceived {
void messageReceived(String message);
}
}
And here is the MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
Client client;
public static String message,ippi;
public static TextView terminale,indr,msg;
TextView log;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings,helps,allerts,home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
new connectTask().execute("");
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
Cursor cursor = myDB.fetchData();
if(cursor.moveToFirst()){
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
}while(cursor.moveToNext());
}
client.setIp(indr.getText().toString());
cursor.close();
server.Parti();
message = indr.getText().toString();
if (client != null) {
client.sendMessage(message);
}
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,Client.SERVERIP, Toast.LENGTH_LONG).show();
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
public class connectTask extends AsyncTask<String,String,Client> {
#Override
protected Client doInBackground(String... message) {
//we create a TCPClient object and
client = new Client(new Client.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
client.run();
return null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
}
Problem:
Since Client.java (according to you) is not an Activity type class, you cannot call/invoke Client.java using an Intent. Intent is only used for invoking: Activities, BroadcastReceiver, and Services.
Your Client.java does not extend an Activity, Broadcast, or a Service. This is the reason why you don't have the getIntent() function, or even the functions onCreate(), onReceive(),onStartCommand()oronHandleIntent()'` for that matter.
Correct way:
1. So what you have to do is create an object of that class just like any other object and call its setter. You can define a public method in you class to set the value of IP:
YourClass {
private String mIP;
public void setIp(String _IP) {
mIp = _IP;
}
}
And in the MainActivity class you can just call that method after the object is initialized:
MyClassObject.setIp("127.0.0.1");
2. Define an overloaded constructor, and set the value using it.
3. Create a public static String IP in MainActivity, assign value to it and then in your class do this to retrieve the value:
YourClass {
private String mIP;
public void getIp() {
mIP = MainActivity.IP;
}
}
In your Client class.
public void setString(String yourString){
variableToStoreStringInClass = yourString;
}
And in your MainActivity, where you want to send the string to the Client.
Client yourClient = new Client();
yourClient.setString("Enter the string");
Or you can use an static method:
In Client class:
public static void setString(String yourString){
variableToStoreStringInClass = yourString;
}
And in your MainActivity
Client.setString("Enter the string");
In your Settings activity when you set the String in that TextView also save it in a shared preference like this:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
prefs.edit().putString("IP", IP_String).apply();
And then in main activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
String ip = prefs.getString("IP", "AnyDefaultValue");
client.setIp(ip);
Intialize static string in MainActivity and assign textView text to that string.
In Client.java call like this MainActivity.IntializedString
Try following sample
public class Client {
Context context;
Intent intent;
String value = "";
public Client(Activity activity) {
context = activity;
intent = ((Activity) context).getIntent();
value = intent.getStringExtra("String_i_need");
}
}
Related
I'm doing an application and I need to receive an udp array from java to android and put it in a Spinner. Does anyone know how to do it?
Now, this is the code that I'm working with but I only receive a string.
Does anyone have an idea of how I can receive the array working from this code?
UDPClientSocketActivity
public class UDPClientSocketActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
buttonSend.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
sendMessage(mEditTextSendMessage.getText().toString());
break;
}
}
private void sendMessage(final String message) {
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
String stringData;
#Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
// IP Address below is the IP address of that Device where server socket is opened.
InetAddress serverAddr = InetAddress.getByName("xxx.xxx.xxx.xxx");
DatagramPacket dp;
dp = new DatagramPacket(message.getBytes(), message.length(), serverAddr, 9001);
ds.send(dp);
byte[] lMsg = new byte[1000];
dp = new DatagramPacket(lMsg, lMsg.length);
ds.receive(dp);
stringData = new String(lMsg, 0, dp.getLength());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
handler.post(new Runnable() {
#Override
public void run() {
String s = mTextViewReplyFromServer.getText().toString();
if (stringData.trim().length() != 0)
mTextViewReplyFromServer.setText(s + "\nFrom Server : " + stringData);
}
});
}
});
thread.start();
}
}
If you want to put data into Spinner there is a link: https://developer.android.com/guide/topics/ui/controls/spinner
I have a client-server app with a java server and the client is an android app.
I create my socket in the android app when the user clicks on a button in a asynktask like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connection);
TextBienvenue = (TextView) findViewById(R.id.textView_Bienvenue);
Intent intent = getIntent();
Bundle b = intent.getExtras();
if (b != null) {
juge = (String) b.get("NomJuge");
TextBienvenue.setText("Bienvenue " + juge);
}
}
public void send_data(View v) {
Intent intent = getIntent();
Bundle b = intent.getExtras();
String nom = (String) b.get("NomJuge");
String message = nom + " est connecter";
MessageSender b1 = new MessageSender();
b1.execute("connect:" + message);
}
public class MessageSender extends AsyncTask<String, Void, Void> {
// Déclaration des sockets pour client
Handler h = new Handler();
String reponse;
String Karateka;
String[] data;
#Override
protected Void doInBackground(String... voids) {
try {
String message = voids[0];
socket = new Socket("10.0.1.90", 8181);
isReader = new InputStreamReader(socket.getInputStream());
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(isReader);
while((reponse = reader.readLine()) != null){
data = reponse.split(":");
if (data[0].equals("connection"))
{
h.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),data[1],Toast.LENGTH_LONG).show();
Intent goToNextActivity = new Intent(getApplicationContext(), AttenteKarateka.class);
goToNextActivity.putExtra("NomJuge", juge);
startActivity(goToNextActivity);
}
});
if (message != null) {
writer.write(message + "\n");
writer.flush();
}
}
if (data[0].equals("karateka"))
{
Karateka = data[1];
h.post(new Runnable() {
#Override
public void run() {
Intent goToNextActivity = new Intent(getApplicationContext(), ActivityFormulaire.class);
goToNextActivity.putExtra("NomJuge", juge);
goToNextActivity.putExtra("NomKarateka",Karateka);
startActivity(goToNextActivity);
}
});
//writer.write("test:" + juge + " est pret a envoyer son resultat" + "\n");
//writer.flush();
}
}
}catch(IOException e){
e.printStackTrace();
}
return null;
}
}
If the string received from the server starts with "karateka", I go to another activity where there is a form and a button, I want to write to the server from this activity...
public class ActivityFormulaire extends AppCompatActivity {
// Déclaration du textview
private TextView TextNomJuge;
private TextView TextNomKarateka;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formulaire);
// On assigne la text view de notre activity
TextNomJuge = (TextView)findViewById(R.id.textView_InputNomJuge);
TextNomKarateka = (TextView)findViewById(R.id.textView_InputParticipant);
// On recoit l'intent du changement d'activity
Intent intent= getIntent();
Bundle b = intent.getExtras();
// Si le bundle recu n'est pas vide on assigne la string a notre textView
if(b!=null)
{
String j =(String) b.get("NomJuge");
String participant = (String) b.get("NomKarateka");
TextNomJuge.setText(j);
TextNomKarateka.setText(participant);
}
}
public class ResultSender extends AsyncTask<String, Void, Void> {
// Déclaration des sockets pour client
Socket socket;
PrintWriter writer;
Handler h = new Handler();
#Override
protected Void doInBackground(String... voids) {
try {
String message = voids[0];
h.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"resultat envoyer",Toast.LENGTH_LONG).show();
}
});
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
public void send_result(View v) {
String message = "resultat: resultat du juge recu du formulaire";
ResultSender b2 = new ResultSender();
b2.execute(message);
}
}
I have tried to make my writer Public static in the Activity where I start the socket, and try to use it in the new activity but it doesn't seem to work.
I heard about a singleton to handle my socket but I don't understand how to do it.
Can anyone can help me? It's the last step I need to get working.
I am attempting to use the MyBluetoothService class straight from the Android tutorials and call the write method from the main activity as suggested by the text. I would just like some guidance on how to pass a string from the main activity to the write method and send it to a connected Bluetooth device.
public class MyBluetoothService {
private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler mHandler; // handler that gets info from Bluetooth service
// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
// ... (Add other message types here as needed.)
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams; using temp objects because
// member streams are final.
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_READ, numBytes, -1,
mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
// Share the sent message with the UI activity.
Message writtenMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
writtenMsg.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
// Send a failure message back to the activity.
Message writeErrorMsg =
mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast",
"Couldn't send data to the other device");
writeErrorMsg.setData(bundle);
mHandler.sendMessage(writeErrorMsg);
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
}
this code will help you to find all the devices in the surrounding
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
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 android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class DeviceList extends AppCompatActivity {
ListView blist;
Button b;
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
b=(Button)findViewById(R.id.button);
blist=(ListView)findViewById(R.id.listView);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pairedDevices();
}
});
}
private void pairedDevices()
{
pairedDevices=myBluetooth.getBondedDevices();
ArrayList list=new ArrayList();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
blist.setAdapter(adapter);
blist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, ledControl.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};
}
this code helps to send the message to the device connected
public class ledControl extends AppCompatActivity {
Button btnOn, btnOff, btnDis;
TextView lumn;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgtes
btnOn = (Button) findViewById(R.id.button2);
btnOff = (Button) findViewById(R.id.button3);
btnDis = (Button) findViewById(R.id.button4);
lumn = (TextView) findViewById(R.id.lumn);
new ConnectBT().execute(); //Call the class to connect
//commands to be sent to bluetooth
btnOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOnLed();
//method to turn on
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOffLed(); //method to turn off
}
});
btnDis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Disconnect(); //close connection
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("F".toString().getBytes());
//Log.e("message",)
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
//Toast.makeText(ledControl.this,"oning",Toast.LENGTH_SHORT).show();
btSocket.getOutputStream().write("O".toString().getBytes());
Log.e("message",btSocket.toString());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
I'm having some troubles while trying to visualize the message send from the TCP Server as response to my TCP Client
Here is my Client.java code
public class Client {
public static String SERVER_IP; //server IP address
public static String ipp;
public static final int SERVER_PORT = 4444;
// 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 = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public Client(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* 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.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//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.e("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) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
While here is the MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
static Client client;
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
static String ipp;
static String trm;
static DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
startConnection.postDelayed(runnableConnection,5000);
startMessage.postDelayed(runnableMessage,5500);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public static class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
messageReceived(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("test", "response " + values[0]);
}
}
static Handler startConnection = new Handler();
static Runnable runnableConnection = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
}
};
static Handler startMessage = new Handler();
static Runnable runnableMessage = new Runnable() {
#Override
public void run() {
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
if (client != null) {
client.sendMessage(ipp + "#" + trm);
}
}
};
}
So what i'm trying to do is receive message from the server and visualize it in help.java activity in a TextView called msgServer set as static.
Actually i don't know which value i have to attribute to the help.msgServer.setText() and where to put it in MainActivity.
Fixed by setting in AsyncTask in MainActivity following code:
msgServer.setTextColor(Color.parseColor("#00FF00"));
msgServer.setText("ONLINE");
in the onProgressUpdate method.
So i identified the right place from where i can get the message sent by the server, the message is contained in:
values
.
I am trying to write an Android app that could communicate over WiFi with ESP8266 module and exchange some simple, basic text data. My problem is I can not get any communication to work. I am not sure if my problem is with the Android code or some bad network configuration on the ESP.
On the Android side, I am using a standard TCPclient class code from this thread to transmit data. In this app I can get WiFi to work and to connect with ESP module using SSID and password authorization.
This is how my app looks like.
Here is TCPclient.java class code I used.
package com.example.wexfo.wifi_com;
import ...
public class TCPclient {
private String serverMessage;
public static final String SERVER_IP = "192.168.0.102";
public static final int SERVER_PORT = 4444;
private OnMessageReceived messageListener = null;
private boolean run = false;
public static final String LOG_TAG = "TCP";
PrintWriter out;
BufferedReader in;
public TCPclient(OnMessageReceived listener) {
messageListener = listener;
}
public void sendMessage(String message) {
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient() {
run = false;
if (out != null) {
out.flush();
out.close();
}
messageListener = null;
in = null;
out = null;
serverMessage = null;
}
public void run() {
run = true;
try {
InetAddress serverAddress = InetAddress.getByName(SERVER_IP);
Log.e(LOG_TAG, "C: Connecting...");
Socket socket = new Socket(serverAddress, SERVER_PORT);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e(LOG_TAG, "C: Sent.");
Log.e(LOG_TAG, "C: Done.");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (run) {
serverMessage = in.readLine();
if (serverMessage != null && messageListener != null) {
messageListener.messageReceived(serverMessage);
}
//serverMessage = null;
}
Log.e(LOG_TAG, "S: Received message: '" + serverMessage + "'.");
}
catch (Exception e) {
Log.e(LOG_TAG, "S: Error", e);
}
finally {
socket.close();
}
}
catch (Exception e) {
Log.e(LOG_TAG, "C: Error", e);
}
}
public interface OnMessageReceived {
void messageReceived(String message);
}
}
Below is MainActivity.java code.
package com.example.wexfo.wifi_com;
import ...
public class MainActivity extends AppCompatActivity {
// Labels and edits
private TextView connectionText;
private EditText messageText;
private TextView chatText;
// Buttons
private ToggleButton connectButton;
private Button sendButton;
// Wifi connection
private static final String NET_SSID = "AI-THINKER";
private static final String NET_PASSWD = "aiTHINKERwifi";
private WifiConfiguration wifiConfig;
private WifiManager wifiManager;
// Other
private TCPclient tcpClient;
private void printChatLine(String text) {
chatText.append("\n>> " + text);
}
private void printChatLine(String who, String text) {
chatText.append("\n" + who + ": " + text);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionText = (TextView) findViewById(R.id.connectionText);
messageText = (EditText) findViewById(R.id.messageText);
chatText = (TextView) findViewById(R.id.chatText);
chatText.setMovementMethod(new ScrollingMovementMethod());
printChatLine("chat test");
// WiFi setup (authorization hard-coded for now)
wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + NET_SSID + "\"";
wifiConfig.preSharedKey = "\"" + NET_PASSWD + "\"";
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(wifiConfig);
connectButton = (ToggleButton) findViewById(R.id.connectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (connectButton.isChecked()) {
connectionText.setText("Disconnect WiFi");
if (!wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(true);
List<WifiConfiguration> netList = wifiManager.getConfiguredNetworks();
for (WifiConfiguration net : netList) {
if (net.SSID != null && net.SSID.equals("\"" + NET_SSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(net.networkId, true);
wifiManager.reconnect();
break;
}
}
// Start server connection thread
new ConnectTask().execute("");
}
else {
connectionText.setText("Connect WiFi");
if (wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(false);
// Stop server connection thread
if (tcpClient != null)
tcpClient.stopClient();
}
}
});
sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = messageText.getText().toString();
printChatLine("ME", message);
messageText.setText("");
// Send message to ESP
if (tcpClient != null)
tcpClient.sendMessage(message);
}
});
}
public class ConnectTask extends AsyncTask<String,String,TCPclient> {
#Override
protected TCPclient doInBackground(String... message) {
tcpClient = new TCPclient(new TCPclient.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
tcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Received message from ESP
printChatLine("ES", values[0]);
}
}
}
Now the ESP8266 is set to work as SoftAP
AT+CWMODE?
+CWMODE:3
OK
Then I make a basic setup for multiple connections and start a new server.
AT+CIPSTA="192.168.0.102"
OK
AT+CIPMUX=1
OK
AT+CIPSERVER=1,4444
OK
Here is my IP data.
AT+CIFSR
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"1a:fe:34:8e:81:58"
+CIFSR:STAIP,"192.168.0.102"
+CIFSR:STAMAC,"18:fe:34:8e:81:58"
OK
Now when I run my app I can confirm I am connected to ESP's access point.
AT+CWLIF
192.168.4.2,00:27:15:77:82:02
OK
However there is no sign of an opened connection on the ESP and clicking SEND button does not make any data transfer. When I try to connect through ESP, I get an ERROR.
AT+CIPSTART=0,"TCP","192.168.4.2",4444
0,CLOSED
ERROR
My feeling is the app works fine but I do something horribly wrong on the ESP side and I can not figure out what it is. Maybe I have a wrong idea about the entire setup?