Android client socket is always null - android

I have made client server connection and it connects well but the socket always returns null, I don't know why.
The server is MATLAB and has no problem and it runs well. When I try to write the ip of the server in browser it give me the message that the client should receive.
Here is the server code
data = 'Hello World..\n'
tcpipServer = tcpip('0.0.0.0',80,'NetworkRole','Server');
set(tcpipServer,'OutputBufferSize',length(data)+1);
fopen(tcpipServer);
fwrite(tcpipServer,data);
fclose(tcpipServer);
And here is the client code
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends ActionBarActivity {
Socket socket;
TextView txt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView) findViewById(R.id.txt1);
final byte[] data = new byte[1024];
new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.185.10");
socket = new Socket(serverAddr, 80);
socket.getInputStream().read(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
txt1.setText(new String(data));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the problem the socket is always equal to null
socket = new Socket(serverAddr, 80);
Note: It connects to the server but does not receive any thing
and I even have the internet permission in the manifest.

Related

In wireshark, I cannot see the packet I sent from android multicast socket

I follow the step here to set up a multicast server, but for some reason, I am not able to see my packet in wireshark. I am monitoring my wifi interface. Here is the code I used
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener((e) -> {
try {
boom();
} catch (Exception e1) {
e1.printStackTrace();
}
});
}
private void boom() throws Exception
{
new AsyncServer().execute("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class AsyncServer extends AsyncTask<String, Void, Void> {
private Exception exception;
protected Void doInBackground(String... args)
{
String msg = "Hello";
InetAddress group = null;
try {
group = InetAddress.getByName("239.1.2.3");
MulticastSocket s = new MulticastSocket(4333);
// s.setInterface(InetAddress.getByName("192.168.232.2")); // To use wifi interface, but doesn't seem to be necessary. The message I will send at 75 and receive at 79 will have address 192.168.232.2
s.joinGroup(group);
DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), group, 4333);
s.send(hi);
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
s.receive(recv);
System.out.println("Received Message: " + recv.getData());
System.out.println("Send By: " + recv.getAddress());
// OK, I'm done talking - leave the group...
s.leaveGroup(group);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
I try something similar in a Java application and it work just fine, so I am assuming this is something wrong with android. Do you guy have any idea ?
Thank you

Building a chat client Android app, how should I approach recieving messages?

I'm making an Android application that connects to my computer, with this I am trying to make it so I can send messages back and forth. As of right now messages can be sent and recieved server-side but for my Android application I don't know how to constantly check for messages and update the UI. I'm using a BufferedReader for input and I want to display the messages on a TextView. Here's what I have so far:
package com.example.david.chatclient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
/**
* After connecting to server, how can i recieive messages, append it, and then reloop through it
*/
public class MainActivity extends AppCompatActivity {
private String IP;
private int portNumber;
private Socket clientSocket;
private PrintWriter writer;
private BufferedReader reader;
private Button connectButton;
private Button sendButton;
private EditText userMessage;
private TextView chatHistory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 10.0.2.2 = Android Emulator IP Address (Reaches development machine, not emulator itself)
IP = "10.0.2.2";
portNumber = 25565;
connectButton = (Button) findViewById(R.id.connect_button);
sendButton = (Button) findViewById(R.id.send_button);
userMessage = (EditText) findViewById(R.id.user_message);
chatHistory = (TextView) findViewById(R.id.chat_history);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void connectClient(View view) {
ConnectToServer task = new ConnectToServer();
task.execute();
} // end connectClient
public void sendMessage(View view) {
String message = userMessage.getText().toString() + "\n";
writer.write(message);
writer.flush();
chatHistory.append("CLIENT: " + message);
userMessage.setText("");
}
private class ConnectToServer extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
try{
clientSocket = new Socket(IP, portNumber);
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
writer = new PrintWriter(clientSocket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(MainActivity.this, "Successfuly connected, streams are esablished", Toast.LENGTH_SHORT).show();
}
} // end ConnectToServer
} // end MainActivity
Here's what the UI looks like:
https://gyazo.com/dbf99c78ca7874939a404ef7d23d8ff8
There are two aproaches.
Checking periodically if new message awaits on server this method is called Fetch - this is very battery and data unfriendly.
Keeping open connection all time aka push messaging - that's the modern way to go. Google handles this on android and ios with GCM

HttpURLConnection method empty when called

I'm calling a
(getData()
that should run HttpURLConnection and return a string (later to be casted as Long), the string should be the one line from this URL:
https://blockchain.info/tobtc?currency=USD&value=1
Trying to see if it is returning anything , I'm displaying the returned string in the layout.xml file and showing a toast. But both both show as blank
Please do not pay attention to the fact that I'm doing this on the main thread, I'm just trying to make it work first.
What I'm I doing wrong? why it's not returning the string value.
thanks
package app.com.cryptosudan.android.cryptosudan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}
//to create an instance of button OnClickListener
View.OnClickListener sdgpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateSdg.class));
}
};
//to create an instance of button OnClickListener
View.OnClickListener btcpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateBtc.class));
}
};
public static String getData () {
BufferedReader reader = null;
try {
URL url = new URL("https://blockchain.info/tobtc?currency=USD&value=1");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) !=null) {
sb.append (line + "/n");
} return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
For http request on main thread change you onCreate method with StrictMode.ThreadPolicy.Builder().permitAll()
I Don't recommend Http request in main thread !!!!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}

getting text from EditText in android

I have written this code for searching a text file for a string. The problem is, it says that the string is not found even if it is present. Process is to receive the text from the EditText and then start the searching process. But it shows that string is found every time.
package com.example.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button;
final EditText obedittext;
button =(Button)findViewById(R.id.button1);
obedittext =(EditText)findViewById(R.id.editText1);
button.setOnClickListener(
new View.OnClickListener()
{
boolean textfound;
public void onClick(View view)
{
textfound = searchtext(obedittext.getText().toString());
if(textfound)
maketoast(obedittext.getText().toString());
else
maketoast("Unsuccessfull");
}
});
}
protected boolean searchtext(String string) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new InputStreamReader(getAssets().open("mneumo.txt")));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.equals(string)) {
return true;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
finally{
}
return false;
}
private void maketoast(String string) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, string , Toast.LENGTH_SHORT);
toast.show();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So when i tried to give the string inside the code itself instead of getting it from the edittext,it works fine. Like this,
string = "SPINAL ANESTHESIA AGENTS";
The sample text file is,
SPINAL ANESTHESIA AGENTS
XYLOCAINE: WHERE NOT TO USE WITH EPINEPHRINE
GENERAL ANAESTHESIA: EQUIPMENT CHECK PRIOR TO INDUCING
So how can i rectify this problem? Can anyone say why i am getting this problem?
Should i any other method to compare the strings?
The text file is correctly placed in the assets folder. And i accessed it using the assetmanager. And i am a total newbie to android development.
May be your editText contain some white space already, To get text from your editText try this:
obedittext.getText().toString().trim();
and inside your searchtext() method, replace your if condition with:
if(sCurrentLine.equalsIgnoreCase(string))

Cannot be resolved to type - Android

So I get this error saying "xy cannot be resolved to type" and "the method onCreateOptionsMenu(Menu) of type KalandActivity must override or implement a supertype method" the code was written on another computer and worked well on that one. I imported it and got a lot of problems. I tried some solutions I found online, but nothing seemed to help. There are other classes which have problems too. Could someone give some advice?
package hu.treasurefinder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.R;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
public class KalandActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kaland);
TextView cim = (TextView) findViewById(R.id.cimView);
final ImageView kep = (ImageView) findViewById(R.id.kepView);
TextView szoveg = (TextView) findViewById(R.id.szovegView);
Intent param = getIntent();
Kaland kaland = (Kaland)param.getSerializableExtra("kaland");
cim.setText("2");
cim.setText(kaland.getNev());
szoveg.setText(kaland.getLeiras());
AsyncTask<String,Void,byte[]> task = new AsyncTask<String,Void,byte[]>() {
#Override
protected byte[] doInBackground(String... kep) {
URL url;
try {
url = new URL("http://www.programozas-oktatas.hu/kaland/"+kep[0]);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readBytes;
while ((readBytes = is.read(buffer)) != -1) {
baos.write(buffer, 0, readBytes);
}
is.close();
return baos.toByteArray();
} catch (IOException ex) {
return null;
}
}
#Override
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
Bitmap bmp = BitmapFactory.decodeByteArray(result, 0, result.length);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bmp, kep.getWidth(), kep.getHeight(), true);
kep.setImageBitmap(resizedBitmap);
}
};
task.execute(kaland.getKep());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.kaland, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories

Resources