How to get arraylist from java to android - java

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

Related

How to connect to PC (server) using sockets with Android app (client)?

I have a server set up on my PC (using Hercules), which is listening on a port # and waiting for a connection. I can't get the android app to receive messages from the server however on my android emulator (Strangely I can send messages to the server), and I can't do either from my physical android phone.
All the examples I'm finding online involve android devices connecting to each other, like this one: https://www.coderzheaven.com/2017/05/01/client-server-programming-in-android-send-message-to-the-client-and-back/
Would I still be able to connect to a PC by just implementing the client side on my android app? What changes would I have to make otherwise?
Directly copy pasting hasn't worked for me...
(Btw the phone and PC are both connected to the same ethernet network, not wifi if that makes a difference)
Thanks!
edit: Turns out my PC was on a different subnet from my phyiscal android phone, and so changing the PC to be on the same subnet as the phone fixed the problem of my phone not being able to even connect, but now it can connect it seems and send messages to the PC, but again not able to receive messages from the hercules server
edit2: My client code (android app)
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int SERVERPORT = xxxx;
public static final String SERVER_IP = "xxx.xxx.x.xxx";
private ClientThread clientThread;
private Thread thread;
private LinearLayout msgList;
private Handler handler;
private int clientTextColor;
private EditText edMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Client");
clientTextColor = ContextCompat.getColor(this, R.color.colorAccent);
handler = new Handler();
msgList = findViewById(R.id.msgList);
edMessage = findViewById(R.id.edMessage);
}
public TextView textView(String message, int color) {
if (null == message || message.trim().isEmpty()) {
message = "<Empty Message>";
}
TextView tv = new TextView(this);
tv.setTextColor(color);
tv.setText(message + " [" + getTime() + "]");
tv.setTextSize(20);
tv.setPadding(0, 5, 0, 0);
return tv;
}
public void showMessage(final String message, final int color) {
handler.post(new Runnable() {
#Override
public void run() {
msgList.addView(textView(message, color));
}
});
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.connect_server) {
msgList.removeAllViews();
showMessage("Connecting to Server...", clientTextColor);
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
showMessage("Connected to Server...", clientTextColor);
return;
}
if (view.getId() == R.id.send_data) {
String clientMessage = edMessage.getText().toString().trim();
showMessage(clientMessage, Color.BLUE);
if (null != clientThread) {
clientThread.sendMessage(clientMessage);
}
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String message = input.readLine();
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
showMessage(message, Color.RED);
break;
}
showMessage("Server: " + message, clientTextColor);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
void sendMessage(final String message) {
new Thread(new Runnable() {
#Override
public void run() {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}

How can I make my Socket on throughout the program and pass value through it

Here I created a socket that I want to make global and pass the integer value throught the socket by clicking the button.But I am getting Error when I try to make Socket global.So how can make the Socket global,and pass the integer value through it. how can make the Socket global,and pass the integer value through it.how can make the Socket global,and pass the integer value through it.
Main Activity:
public class MainActivity extends AppCompatActivity {
Button buttonOn;
Button button1;
Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOn = (Button) findViewById(R.id.ON);
button1 = (Button) findViewById(R.id.button1);
try {
System.out.println("HIIIII");
socket = new Socket("198.168.0.79",8888);
socket.getKeepAlive();
} catch (IOException e) {
e.printStackTrace();
}
buttonOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int temp = 2;
bhari b = new bhari();
b.execute(String.valueOf(temp));
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int temp = 1;
String fan = String.valueOf(temp);
bhari b = new bhari();
b.execute(fan);
}
});
}
}
class bhari:
class bhari extends AsyncTask<String,Void,Integer>{
Socket socket;
DataOutputStream dataOutputStream;
#Override
protected Integer doInBackground(String... params) {
String massage = params[0];
try {
if(socket== null){
System.out.println("if");
socket = new Socket("192.168.0.79",8888);
socket.getKeepAlive();
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.write(Integer.parseInt(massage));
dataOutputStream.flush();
// dataOutputStream.close();
}else {
System.out.println("Else");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.write(Integer.parseInt(massage));
dataOutputStream.flush();
// dataOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("End");
return null;
}
}
Actually you are creating another socket object inside of asynctask..
if you want to use same socket object you will have to pass it to asynctask too.
its Another solution is that you pass your integer value to asynctask but create socket only inside of asynctask
You just need to create a singleton
class Mysocket{
private static Socket socket;
public static Socket getInstance()
{
if(socket==null)
{
socket = new Socket("192.168.0.79",8888);
socket.getKeepAlive();
}
return socket;
}
}

Receive message from server in TCP Client and set it in TextView

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
.

Threads Streaming video

I have a Server in Java and a Client in Android. In Android I have an AsyncTask for the receive of the video continuous by the server and a Thread that read the video with the MediaPlayer.
I launch the MediaPlayer after 5s but only the receipt packets are read at the moment when the MediaPlayer is launched.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
vidSurface = (SurfaceView) findViewById(R.id.surfView);
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
Connexion connexion = new Connexion(list);
connexion.execute();
new Thread(new Task2(list)).start();
}
private class Connexion extends AsyncTask<Void, Void, Void> {
private ConcurrentLinkedDeque<OutputStream[]> list;
public Connexion(ConcurrentLinkedDeque<OutputStream[]> list) {
this.list = list;
}
#Override
protected Void doInBackground(Void... params) {
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
DownloadVideo dv = new DownloadVideo(list);
dv.connexion();
return null;
}
}
public void launchVideo() {
Thread.sleep(5000);
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(this);
}
class Task2 implements Runnable {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
Log.d("1", "Thread2");
launchVideo();
}
});
}
Thanks a lot.
Download Video :
public void connexion() {
try {
client = new Socket(IP_SERVER, 9003); // Creating the server socket.
if (client != null) {
// Receive video
InputStream in = client.getInputStream();
OutputStream out[] = new OutputStream[1];
// Store on device
out[0] = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Movies/chrono2.mp4");
byte buf[] = new byte[1024];
int n;
while ((n = in.read(buf)) != -1) {
out[0].write(buf, 0, n);
//Adding last in the queue
list.addLast(out);
Log.d("byte" , "" + out);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Access variable from another thread in Java

I'm working on a small code that uses socket communications on Java and I'm trying to do the following:
Receive a JSON object and parse it [Done]
If the command received was login then start a login [Done]
Print out to the socket the result of the login procedure
It's the last portion I'm having trouble with, my code is as follows:
public class LoginActivity extends Activity {
private Button btnLogin;
private Button btnDemo;
private EditText edtLogin;
private EditText edtSenha;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnDemo = (Button)findViewById(R.id.btnDemo);
edtLogin = (EditText)findViewById(R.id.edtLogin);
edtSenha = (EditText)findViewById(R.id.edtSenha);
pd = new ProgressDialog(this);
new Thread(new Runnable(){
public void run(){
try {
String inMsg;
JSONObject fromClient;
String cmd;
JSONArray args;
ServerSocket server;
Socket client;
BufferedReader in;
PrintWriter out;
//TODO: Getting reconnects on a proper method
System.out.println("Waiting for client on port 8888");
server = new ServerSocket(8888);
client = server.accept();
System.out.println("Just connected to " + client.getRemoteSocketAddress());
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
while(true)
{
inMsg = in.readLine();
if (inMsg == null)
{
System.out.println("Waiting for client on port 8888");
client = server.accept();
System.out.println("Just connected to " + client.getRemoteSocketAddress());
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
continue;
}
fromClient = new JSONObject(inMsg);
System.out.println("In: " + fromClient);
cmd = fromClient.getString("command");
args = new JSONArray(fromClient.getString("args"));
if(cmd.equals("login")){
final String login = args.getString(0);
final String pwd = args.getString(1);
AndroidUtil.mostrarProgressoAguarde(LoginActivity.this, pd);
new Thread(new Runnable() {
public void run() {
PagPop.getInstance().logar(LoginActivity.this, login, pwd, new ServidorListener<Cliente>() {
#Override
public void recebeuResposta(String mensagem, RespostaServidor<Cliente> resposta) {
handleResposta(mensagem, resposta);
}
});
}
}).start();
//out.println(mensagem);
}
else
{
out.println("Received");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String login = edtLogin.getText().toString();
final String senha = edtSenha.getText().toString();
System.out.print("Tentando Logar");
AndroidUtil.mostrarProgressoAguarde(LoginActivity.this, pd);
new Thread(new Runnable() {
public void run() {
PagPop.getInstance().logar(LoginActivity.this, login, senha, new ServidorListener<Cliente>() {
#Override
public void recebeuResposta(String mensagem, RespostaServidor<Cliente> resposta) {
handleResposta(mensagem, resposta);
}
});
}
}).start();
}
});
Near the middle of the code there is my failed attempt to print out the desired variable at //out.println(mensagem); If I try to compile my code with that the following happens:
[javac] /android/demo/LoginActivity.java:107: error: local variable out is accessed from within inner class; needs to be declared final
[javac] out.println(mensagem);
How can I either transport that variable mensagem out of there so I can out.println it from the if level or access out from that method without making out final?
Declare PrintWriter out as a global variable in the activity / fragment

Categories

Resources