I am trying out the WebSockets with Fallbacks transports for Android, Node.js and Atmosphere example. I get an the following error:
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:87: error: cannot access JsonParseException
return mapper.readValue(data, Message.class);
class file for org.codehaus.jackson.JsonParseException not found
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:68: error: cannot access ObjectCodec
return mapper.writeValueAsString(data);
class file for org.codehaus.jackson.ObjectCodec not found
Here is the androidchat code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.atmosphere.wasync.ClientFactory;
import org.atmosphere.wasync.Decoder;
import org.atmosphere.wasync.Encoder;
import org.atmosphere.wasync.Event;
import org.atmosphere.wasync.Function;
import org.atmosphere.wasync.Request;
import org.atmosphere.wasync.RequestBuilder;
import org.atmosphere.wasync.impl.AtmosphereClient;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.Date;
public class wAsyncChat extends Activity {
private Button bt;
private TextView tv;
private String serverIpAddress = "http://10.0.2.2:8080";
private final static ObjectMapper mapper = new ObjectMapper();
private final Handler uiHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
AtmosphereClient client = ClientFactory.getDefault().newClient(AtmosphereClient.class);
RequestBuilder request = client.newRequestBuilder()
.method(Request.METHOD.GET)
.uri(serverIpAddress + "/chat")
.trackMessageLength(true)
.encoder(new Encoder<Message, String>() {
#Override
public String encode(Message data) {
try {
return mapper.writeValueAsString(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
})
.decoder(new Decoder<String, Message>() {
#Override
public Message decode(Event type, String data) {
data = data.trim();
// Padding
if (data.length() == 0) {
return null;
}
if (type.equals(Event.MESSAGE)) {
try {
return mapper.readValue(data, Message.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
})
.transport(Request.TRANSPORT.WEBSOCKET);
final org.atmosphere.wasync.Socket socket = client.create();
socket.on("message", new Function<Message>() {
#Override
public void on(final Message t) {
uiHandler.post(new Runnable() {
#Override
public void run() {
Date d = new Date(t.getTime());
tv.append("Author " + t.getAuthor() + "# " + d.getHours() + ":" + d.getMinutes() + ": " + t.getMessage() + "\n");
}
});
}
}).on(new Function<Throwable>() {
#Override
public void on(Throwable t) {
tv.setText("ERROR 3: " + t.getMessage());
t.printStackTrace();
}
}).open(request.build());
bt.setOnClickListener(new OnClickListener() {
String name = null;
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
if (name == null) {
name = str;
}
socket.fire(new Message(name, str));
et.setText("");
Log.d("Client", "Client sent message");
} catch (Throwable e) {
tv.setText("ERROR 3: " + e.getMessage());
e.printStackTrace();
}
}
});
} catch (Throwable e) {
tv.setText("Unable to connect: " + e.getMessage());
e.printStackTrace();
}
}
}
I have the library for nodeserver connection. You can use it from git
SocketIO socketio = new SocketIO() {
#Override
public void onConnect() {
}
#Override
public void onDisconnect() {
}
#Override
public void onMessage(String message) {
Log.d("===Server Answer====",message);
}
};
socketio.Connect("192.168.0.1", 9000);
after onConnect() send the message:
socketio.send("Your message to socket");
it work with latest socketIO, and use RFC 6455 websocket protocol
I am trying to establish a chatting application between a server and a client, but the application could not run because of this line of code : message = (String) input.readObject();
because at first, inputStream is null ! any one can help please ? here is my code
package com.example.test;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button send;
private Button connect;
private EditText userText;
private TextView chatWindow;
private String serverIP;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private Socket connection;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
serverIP = "192.168.1.4";
//userText.setEnabled(false);
send = (Button)findViewById(R.id.button1);
connect = (Button)findViewById(R.id.button2);
chatWindow =(TextView)findViewById(R.id.textView1);
userText = (EditText)findViewById(R.id.editText1);
userText.setHint("Enter your message here");
connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//connect to the server
try{
connectToServer();
setupStreams();
}catch(EOFException eofException){
showMessage("\n client terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String message = userText.getText().toString();
sendMessage(message);
userText.setText("");
}
});
while(true){
try{
message = (String) input.readObject();
showMessage("\n" + message + " NULL ");
chatWindow.refreshDrawableState();
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n I don't know that object type");
}
catch(NullPointerException e){
e.printStackTrace();
}
catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // end of onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//connect to the server
private void connectToServer() throws IOException {
showMessage("Attempting connection... \n");
connection = new Socket( "192.168.1.4", 6789);
showMessage("Connected to " + connection.getInetAddress().getHostName() );
}
//setup streams to send and receive messages
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Your streams are now good to go! \n ");
}
//whileChatting with server
private void whileChatting() throws IOException{
try{
message = (String) input.readObject();
showMessage("\n" + message + " NULL ");
chatWindow.refreshDrawableState();
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n I don't know that object type");
}
}
//close the streams and sockets
private void closeCrap(){
showMessage("\n closing crap down");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
// gives user permission to type into the text box
private void ableToType(final boolean tof){
userText.setEnabled(tof);
}
// send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n somethine messed up sending message!");
}
}
//change/update chatWindow
private void showMessage(final String m){
chatWindow.append(m);
chatWindow.refreshDrawableState();
}
} // end of class MainActivity
Your code is definitely not following any good UI guidelines: You are doing network operations on the Main (UI) Thread, and you have an infinite loop in onCreate(). Android should actually offer to force close your app if nothing crashes. Now, a likely cause for the null problem you are facing:
setupStreams() is only called upon a button click. However, your while (true) loop is in the root of onCreate(). This means that as soon as the click listeners are made and set, the loop runs, attempts to read in from input and fails since setupStreams() hasn't been called.
So please don't do away with StrictMode - it's there to help, and thing about your code from an event driven standpoint ("Once X happens, then do Y"). And also get rid of loops in the Main (UI) Thread. Loops are fine for Console windows, but with UIs (which have their own complex lifecycle), you can't do this without freezing a lot of things.
Do all of your network tasks in doInBackground() ofAsyncTask then update your UI variables in onPostExecute(). Something like
public class TalkToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
//do your work here
return something;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// do something with data here-display it or send to mainactivity
}
Here is the documentation on AsyncTask
Another thing to consider is you are using the variable message in different places which may cause you problems. It looks like you have it defined as a member variable then as a local variable to other methods. You don't want to re-use the same variable name this way. Don't define String message multiple times in the same Activity
I am trying to use NanoHTTP to serve up an HTML file. However, NanoHTTP is relatively un-documented, and I am new to Android. My question is, where do I store the html file, and how specifically can I serve it up using NanoHTTP.
A late answer but may be useful to others.
Here is a simple hello Web Server, not exactly what you ask, but you can continue from here. The following program supposes you have a www directory in the root of the SD Card and a file index.html inside.
Main activity Httpd.java:
package com.inforscience.web;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.io.*;
import java.util.*;
public class Httpd extends Activity
{
private WebServer server;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
server = new WebServer();
try {
server.start();
} catch(IOException ioe) {
Log.w("Httpd", "The server could not start.");
}
Log.w("Httpd", "Web server initialized.");
}
// DON'T FORGET to stop the server
#Override
public void onDestroy()
{
super.onDestroy();
if (server != null)
server.stop();
}
private class WebServer extends NanoHTTPD {
public WebServer()
{
super(8080);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
String answer = "";
try {
// Open file from SD Card
File root = Environment.getExternalStorageDirectory();
FileReader index = new FileReader(root.getAbsolutePath() +
"/www/index.html");
BufferedReader reader = new BufferedReader(index);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
reader.close();
} catch(IOException ioe) {
Log.w("Httpd", ioe.toString());
}
return new NanoHTTPD.Response(answer);
}
}
}
Obviously the NanoHTTPD class must be in the same package.
You need to grant internet permission in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
and read external storage permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
EDIT: To access the server open you web browser with the IP of your device, e.g. 192.168.1.20:8080.
NOTES:
Tested in Android 2.3
The use of port 80 is restricted to the root user(http://www.mail-archive.com/android-developers#googlegroups.com/msg47377.html).
Pretty good source code can be found here:
https://github.com/Teaonly/android-eye
Chceck assets folder where html and JavaScript files are stored
https://github.com/Teaonly/android-eye/tree/master/assets
TeaServer - server implementation
https://github.com/Teaonly/android-eye/blob/master/src/teaonly/droideye/TeaServer.java
MainActivity - server initialization
https://github.com/Teaonly/android-eye/blob/master/src/teaonly/droideye/MainActivity.java
Updated WebServer class (see rendon's reply) that works with current NanoHTTPD version:
private class WebServer extends NanoHTTPD {
public WebServer() {
super(8080);
}
#Override
public Response serve(IHTTPSession session) {
String answer = "";
try {
// Open file from SD Card
File root = Environment.getExternalStorageDirectory();
FileReader index = new FileReader(root.getAbsolutePath() +
"/www/index.html");
BufferedReader reader = new BufferedReader(index);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
reader.close();
} catch(IOException ioe) {
Log.w("Httpd", ioe.toString());
}
return newFixedLengthResponse(answer);
}
}
Take a look at how I serve HTML files and other type of files too.
I have a AndroidWebServer class which extends the Nanohttpd class.
This is my response method -->
public Response serve(IHTTPSession session) {
String uri=session.getUri();
String msg = "<html><body><h1>Hello server</h1>\n";
File [] arrayfile;
int i=0;
try{
session.parseBody(new HashMap<String, String>());
}catch (ResponseException | IOException r){
r.printStackTrace();
}
Map<String, String> parms = session.getParms();
if (parms.get("username") == null) {
msg += "<form action='?' method='get'>\n <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
} else {
msg += "<p>Hello, " + parms.get("username") + "!</p>";
}
msg += "<br><br><a href='/Open_rap'>Open Image of Lionel Messi</a><br><br>";
msg += "<br><br><a href='/files'>Browse Files</a><br><br>";
msg += "<br><br><a href='/getmethod'>GET METHOD OPERATION</a><br><br>";
msg += "<br><br><a href='/postmethod'>POST METHOD OPERATION</a><br><br>";
msg += "<br><br><a href='/jquery'>JQUERY OPERATION</a><br><br>";
if(uri.equals("/hello")){
String response="Hello World";
return newFixedLengthResponse(response);
}
else if(uri.equals("/getmethod")){
String html="<html><head><h1>Welcome to the Form</h1><head/><body>";
if(parms.get("name")==null){
html +="<form action='' method='get'> \n " +
"<p>Enter Your Name:</p> <input type='text' name='name'>" +
"</form>" +
"</body>";
}
else{
html +="<p>Hello Mr. "+ parms.get("name") +"</p>"+
"</body> ";
}
html +="</html>";
return newFixedLengthResponse(html);
}
else if(uri.equals("/postmethod")){
String html="<html><head><h1>Welcome to the Form</h1><head/><body>";
Map<String, String> files = new HashMap<String, String>();
Method method = session.getMethod();
String postParameter="";
html +="<form action='' method='post'> \n " +
"<p>Enter Your Name:</p> <input type='text' name='name'>" +
"</form>";
if (Method.POST.equals(method) || Method.PUT.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
try {
// return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.d("Exception", e.getMessage());
}
} catch (ResponseException re) {
try {
// return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.d("Exception", re.getMessage());
}
}
}
html +="</body></html>";
String postBody = session.getQueryParameterString();
postParameter = session.getParms().get("name");
Log.d("Postbody",postBody+"\n"+postParameter);
if(postParameter!=null){
String html1="<html><head><h1>"+ postParameter +"</h1><head></html>";
return newFixedLengthResponse(html1);
}
return newFixedLengthResponse(Response.Status.OK,"text/html",html);
}
else if(uri.equals("/Open_rap")){
File root= Environment.getExternalStorageDirectory();
FileInputStream fis = null;
File file = new File(root.getAbsolutePath() + "/www/messi.jpg");
Log.d("Path",root.getAbsolutePath());
try{
if(file.exists())
{
fis = new FileInputStream(file);
}
else
Log.d("FOF :", "File Not exists:");
}catch (FileNotFoundException e)
{
e.printStackTrace();
}
return newFixedLengthResponse(Response.Status.OK,"image/jpeg",fis, file.length() );
}
else {
return newFixedLengthResponse(msg + "</body></html>\n");
}
}
As you can see, I have implemented GET and POST method. You can find each in this part of the code uri.equals("/getmethod") and uri.equals("/getmethod").
Also, you can see the part --> uri.equals("/openrap") , here I am serving a JPG file to the client's browser and the image is present in the internal directory at /www/ folder.
Ping me if you have any doubts.
Try this...
Create 2 packages(activity, util), only for organization
In activity create the class MainActivity.java in util create the class AndroidWebServer.java
package awserverfatepi.com.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import awserverfatepi.com.R;
import awserverfatepi.com.util.AndroidWebServer;
public class MainActivity extends AppCompatActivity {
private static final int DEFAULT_PORT = 8080;
private AndroidWebServer androidWebServer;
private BroadcastReceiver broadcastReceiverNetworkState;
private static boolean isStarted = false;
private CoordinatorLayout coordinatorLayout;
private EditText editTextPort;
private FloatingActionButton floatingActionButtonOnOff;
private View textViewMessage;
private TextView textViewIpAccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initGui();
setIpAccess();
floatingActionButtonOnOff = (FloatingActionButton) findViewById(R.id.floatingActionButtonOnOff);
floatingActionButtonOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isConnectedInWifi()) {
if (!isStarted && startAndroidWebServer()) {
isStarted = true;
textViewMessage.setVisibility(View.VISIBLE);
floatingActionButtonOnOff.setBackgroundTintList(ContextCompat.getColorStateList(MainActivity.this,
R.color.colorGreen));
editTextPort.setEnabled(false);
} else if (stopAndroidWebServer()) {
isStarted = false;
textViewMessage.setVisibility(View.INVISIBLE);
floatingActionButtonOnOff.setBackgroundTintList(ContextCompat.getColorStateList(MainActivity.this,
R.color.colorRed));
editTextPort.setEnabled(true);
}
} else {
Snackbar.make(coordinatorLayout, getString(R.string.wifi_message), Snackbar.LENGTH_LONG).show();
}
}
});
initBroadcastReceiverNetworkStateChanged();
}
private void initGui() {
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
editTextPort = (EditText) findViewById(R.id.editTextPort);
textViewMessage = findViewById(R.id.textViewMessage);
textViewIpAccess = (TextView) findViewById(R.id.textViewIpAccess);
}
private boolean startAndroidWebServer() {
if (!isStarted) {
int port = getPortFromEditText();
try {
if (port == 0) {
throw new Exception();
}
androidWebServer = new AndroidWebServer(port);
androidWebServer.start();
return true;
} catch (Exception e) {
e.printStackTrace();
Snackbar.make(coordinatorLayout, "A porta " + port + " não está funcionando, por favor altere para outra no intervalo" +
" entre 1000 e 9999.", Snackbar.LENGTH_LONG).show();
}
}
return false;
}
private boolean stopAndroidWebServer() {
if (isStarted && androidWebServer != null) {
androidWebServer.stop();
return true;
}
return false;
}
private void setIpAccess() {
textViewIpAccess.setText(getIpAccess());
}
private void initBroadcastReceiverNetworkStateChanged() {
final IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
broadcastReceiverNetworkState = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setIpAccess();
}
};
super.registerReceiver(broadcastReceiverNetworkState, filters);
}
private String getIpAccess() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
return "http://" + formatedIpAddress + ":";
}
private int getPortFromEditText() {
String valueEditText = editTextPort.getText().toString();
return (valueEditText.length() > 0) ? Integer.parseInt(valueEditText) : DEFAULT_PORT;
}
public boolean isConnectedInWifi() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
NetworkInfo networkInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()
&& wifiManager.isWifiEnabled() && networkInfo.getTypeName().equals("WIFI")) {
return true;
}
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent evt) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isStarted) {
new AlertDialog.Builder(this)
.setTitle(R.string.warning)
.setMessage(R.string.dialog_exit_message)
.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(getResources().getString(android.R.string.cancel), null)
.show();
} else {
finish();
}
return true;
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
stopAndroidWebServer();
isStarted = false;
if (broadcastReceiverNetworkState != null) {
unregisterReceiver(broadcastReceiverNetworkState);
}
}
}
In the AndroidWebserver.java
package awserverfatepi.com.util;
import java.util.Map;
import fi.iki.elonen.NanoHTTPD;
public class AndroidWebServer extends NanoHTTPD {
public AndroidWebServer(int port) {
super(port);
}
public AndroidWebServer(String hostname, int port) {
super(hostname, port);
}
#Override
public Response serve(IHTTPSession session) {
String msg = "<html><body><h1>Hello World</h1>\n";
Map<String, String> parms = session.getParms();
if (parms.get("username") == null) {
msg += "<form action='?' method='get'>\n <p>Seu nome: <input type='text' name='username'></p>\n" + "</form>\n";
} else {
msg += "<p>Hello, " + parms.get("username") + "!</p>";
}
return newFixedLengthResponse( msg + "</body></html>\n" );
}
}
Don't forget Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And last
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:src="#drawable/header" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/colorPrimaryLight"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textViewIpAccess"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://000.000.000.000:"
android:textColor="#android:color/white"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="#+id/editTextPort"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="8080"
android:inputType="numberDecimal"
android:maxLength="4"
android:text="8080"
android:textColor="#android:color/white"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
<TextView
android:id="#+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="#string/message"
android:textColor="#android:color/white"
android:textSize="18sp"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatingActionButtonOnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="16dp"
android:elevation="4dp"
android:src="#drawable/on_btn"
app:backgroundTint="#color/colorRed" />
</android.support.design.widget.CoordinatorLayout>
One more example based on previous posts with AssetManager, MimeTypes and routing.
This static server will work for React apps. Your can run React app by using Andorid WebView. Create main/assets/index.html or copy React build folder into main/assets/ directory. Add url http://localhost:8080 to your WebView or browser.
package com.example.httpd;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import java.io.*;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Random;
import fi.iki.elonen.NanoHTTPD;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private HttpServer server;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = new HttpServer();
try {
server.start();
} catch (IOException ioe) {
Log.d(TAG, "The server could not start.");
}
Log.d(TAG, "Web server initialized.");
}
// DON'T FORGET to stop the server
#Override
public void onDestroy() {
super.onDestroy();
if (server != null)
server.stop();
}
private class HttpServer extends NanoHTTPD {
public static final String
MIME_PLAINTEXT = "text/plain",
MIME_HTML = "text/html",
MIME_JS = "application/javascript",
MIME_CSS = "text/css",
MIME_PNG = "image/png",
MIME_DEFAULT_BINARY = "application/octet-stream",
MIME_XML = "text/xml";
private static final int PORT = 8080;
private static final String TAG = "HttpServer";
private AssetManager assetManager;
public HttpServer() {
super(PORT);
}
#Override
public Response serve(IHTTPSession session) {
assetManager = getAssets();
InputStream inputStream;
Response response = newChunkedResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT, null);
String uri = session.getUri();
try {
if (session.getMethod() == Method.GET && uri != null) {
if (uri.contains(".js")) {
inputStream = assetManager.open(uri.substring(1));
return newChunkedResponse(Response.Status.OK, MIME_JS, inputStream);
} else if (uri.contains(".css")) {
inputStream = assetManager.open(uri.substring(1));
return newChunkedResponse(Response.Status.OK, MIME_CSS, inputStream);
} else if (uri.contains(".png")) {
inputStream = assetManager.open(uri.substring(1));
return newChunkedResponse(Response.Status.OK, MIME_PNG, inputStream);
} else if (uri.contains("/mnt/sdcard")) {
Log.d(TAG, "request for media on sdCard " + uri);
File file = new File(uri);
FileInputStream fileInputStream = new FileInputStream(file);
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentType = fileNameMap.getContentTypeFor(uri);
Response streamResponse = newChunkedResponse(Response.Status.OK, contentType, fileInputStream);
Random random = new Random();
String hexString = Integer.toHexString(random.nextInt());
streamResponse.addHeader("ETag", hexString);
streamResponse.addHeader("Connection", "Keep-alive");
return streamResponse;
} else {
inputStream = assetManager.open("index.html");
return newChunkedResponse(Response.Status.OK, MIME_HTML, inputStream);
}
}
} catch (IOException e) {
Log.d(TAG, e.toString());
}
return response;
}
}
}
build.gradle
dependencies {
...
implementation 'org.nanohttpd:nanohttpd:2.3.1'
...
}
res/values/strings.html
<resources>
<string name="http_index">index.html</string>
</resources>
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Have a nice day! :)
I'm trying to make a client in Android. This clients runs a thread that creates the client socket and launches another thread that is always listening to the socket to receive Strings. Everything is OK when I send a String from the client to a Java server running in a PC, but when I send a String from the server to the Android client the app finishes. Why do I get this error?
Here is the code of the main Activity of the client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView chatHistorial;
EditText msg;
Socket client;
DataInputStream in;
DataOutputStream out;
Boolean cerrar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable(){
#Override
public void run() {
try{
client = new Socket("192.168.1.33", 4444);
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
cerrar = false;
chatHistorial = (TextView) findViewById(R.id.chatHistorial);
msg = (EditText) findViewById(R.id.msg);
ThreadLectura tl = new ThreadLectura(in, cerrar, chatHistorial);
tl.start();
}
catch(Exception e){
// ...
}
}
});
t.start();
findViewById(R.id.enviar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cadena = msg.getText().toString();
try {
out.writeUTF(cadena);
} catch (IOException e) {
// ...
}
if(cadena.equals("exit"))
cerrar = true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class ThreadLectura extends Thread{
DataInputStream in;
String cadena;
TextView chatHistorial;
Boolean cerrar;
public ThreadLectura(DataInputStream in, Boolean cerrar, TextView tv){
this.in = in;
this.cerrar = cerrar;
chatHistorial = tv;
}
#Override
public void run(){
try{
while(!cerrar){
cadena = in.readUTF();
chatHistorial.append("Has recibido: " + cadena);
}
}
catch(IOException ioe){
System.out.println("Error de entrada/salida: "+ioe.getMessage());
}
}
}
It's hard to say without seeing your logcat output, but I'm betting it's because you are attempting to modify the UI from within your background thread. This line within ThreadLectura:
chatHistorial.append("Has recibido: " + cadena);
is probably the issue, as chatHistorial is a TextView. You need to only modify the UI from within the main UI thread.
this is my code. there is some error here and i couldn't settle it. can anyone pls help me? there is an error at view.OnClickListener and View v. If i using quick fix to fix an error,another error will appear. pls help me :'(
package com.android;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.view.View.*;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.text.Editable;
public class Net extends Activity implements View.OnClickListener
{
EditText edt;
TextView text;
Button ping;
#Override
protected void onCreate(Bundle savedInstanceState) //To do auto generated method
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt=(EditText)findViewById(R.id.edt);
text=(TextView)findViewById(R.id.text);
ping=(Button)findViewById(R.id.ping);
Button.setOnClickListener(this);
}
public void onClick(View v) //To do auto generated method
{
Editable host=edt.getText();
}
InetAddress addr=null;
{
Object host;
try
{
addr=InetAddress.getByName(host.toString());
}
catch(UnknownHostException e) //To do auto generated catch block
{
e.printStackTrace();
}
try
{
if(addr.isReachable (5000))
{
text.append("\n" +host+ "-Respond Ok");
}
else
{
text.append("\n"+host);
}
}
catch(IOException e){
text.append("\n"+e.toString());
}
try
{
String pingCmd="ping -c5"+host;
String pingResult="";
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!=null)
{
System.out.println(inputLine);
text.setText(inputLine+"\n\n");
pingResult += inputLine;
text.setText(pingResult);
}
in.close();
}
catch(IOException e)
{
System.out.println(e);
}
TextView tv = new TextView(this);
tv.setText("\t\t\t\t** Network Tracer ** \n\n\t\tWelcome to Android Network Tracer!");
setContentView(tv);
}
}
If error is compile time then most probably here on line:
public void onClick(View v) //To do auto generated method
{
Editable host=edt.getText();
}
InetAddress addr=null;
you have closed method definition having only statement, if you want to place all the following code into onClick method, follow as:
public void onClick(View v) //To do auto generated method
{
Editable host=edt.getText();
InetAddress addr=null;
Object host;
try
{
addr=InetAddress.getByName(host.toString());
}
catch(UnknownHostException e) //To do auto generated catch block
{
e.printStackTrace();
}
try
{
if(addr.isReachable (5000))
{
text.append("\n" +host+ "-Respond Ok");
}
else
{
text.append("\n"+host);
}
}
catch(IOException e){
text.append("\n"+e.toString());
}
try
{
String pingCmd="ping -c5"+host;
String pingResult="";
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!=null)
{
System.out.println(inputLine);
text.setText(inputLine+"\n\n");
pingResult += inputLine;
text.setText(pingResult);
}
in.close();
}
catch(IOException e)
{
System.out.println(e);
}
TextView tv = new TextView(this);
tv.setText("\t\t\t\t** Network Tracer ** \n\n\t\tWelcome to Android Network Tracer!");
setContentView(tv);
}
How about replacing this code:
protected void onCreate(Bundle savedInstanceState) //To do auto generated method
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt=(EditText)findViewById(R.id.edt);
text=(TextView)findViewById(R.id.text);
ping=(Button)findViewById(R.id.ping);
Button.setOnClickListener(this);
}
with this:
protected void onCreate(Bundle savedInstanceState) //To do auto generated method
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt=(EditText)findViewById(R.id.edt);
text=(TextView)findViewById(R.id.text);
ping=(Button)findViewById(R.id.ping);
ping.setOnClickListener(this);
}