unable to run my android application - android

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

Related

I would like to create a Simple Http server in android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have used the https://github.com/NanoHttpd/nanohttpd code for reference.
When i ran my simple android application. I am getting "application not supported" error. While running my android application in eclipse.
My main activity code is :
package com.example.nanoservertest;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Map;
import java.util.Properties;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8085;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// hello = (TextView) findViewById(R.id.hello);
}
#Override
protected void onResume() {
super.onResume();
System.out.println("inside resume");
try {
server = new MyHTTPD();
server.stratServer();
//server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT);
}
//Start
public void stratServer(){
ServerRunner.run(MyHTTPD.class);
}
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
String msg = "<html><body><h1>Hello server</h1>\n";
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 += "</body></html>\n";
return new NanoHTTPD.Response(msg);
}
}
}
And My Server runner class is
import java.io.IOException;
public class ServerRunner {
public static void run(Class serverClass) {
try {
executeInstance((NanoHTTPD) serverClass.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void executeInstance(NanoHTTPD server) {
try {
server.start();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
System.exit(-1);
}
System.out.println("Server started, Hit Enter to stop.\n");
try {
System.in.read();
} catch (Throwable ignored) {
}
server.stop();
System.out.println("Server stopped.\n");
}
}
I am unable to start my application.
Try to use this library, it seems to respond to your needs:
AndroidAsync

Connecting to FTP server using AsyncTask

I am quite new to android developing
I have written the following code to connect my android to a ftp server
package com.example.test1;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.*;
public class MainActivity extends Activity {
public FTPClient mFTPClient = null;
Button but;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
CharSequence c = ""+e;
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),c,d);
toast.show();
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but=(Button)findViewById(R.id.button1);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ftpConnect("127.0.0.1","userName","Password",21);
}
});
}
}
But this gives a networkOnMainThread Exception so after searching i found out i have to use AsyncTask but i have no idea how to implement it!
public void onClick(View v) {
new AsyncTask() {
publc Object doInBackground(Object...) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
return e;
}
}
}
public void onPostExecute(Object res) {
if (res instanceof Exception) {
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),""+res,d);
toast.show();
}
}
}.execute();
Another temporary 'workaround' is to set your android:targetSdkVersion="9" or below in AndroidManifest.xml, as this exception was introduced in API level 10.
Documentation on Android Developers is pretty rich on such an important topic. You'll get it through with that.
http://developer.android.com/reference/android/os/AsyncTask.html
You may want to refer the NetworkConnect sample from the Android SDK.

Android: Force close when reading from Socket

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.

pass object stream use intent method

how can I pass object stream (exmple: BufferedReader or DataOutputStream n etc) to other activity (from Client_layoutActivity.class to chat_wall.class ) if i use intent method like this:
Intent i = new Intent(Client_layoutActivity.this, chat_wall.class);
startActivity(i);
I made a chat application that consists of several pages. The first page is the login page. in the first page, client use socket to communicated with server. After login process is success than server will send "login success". After that clien side will change layout from first page (login page) to second page (chat wall page). I mean to use socket, BufferedReader and DataOuputstream method from first page (i assume socket for login process is still connected so i can still used this socket to communicate in second page - chatting process). So i want to pass object Socket, BufferedReader and DataOuputstream to second page to used this. i write my code bellow:
PAGE 1 : for login purpose
public void login(){
try {
String name = usrname.getText().toString(); // usrname is android object edit
text
String pass = password.getText().toString();// password is android
object edit text
String sending = "login."+name + "." + pass + "." +"\n";
System.out.println("Sending Message: "+sending);
Socket clientsock = new Socket("192.168.136.6", 28000);
System.out.println("connect to the server...");
BufferedReader in = new BufferedReader(new
InputStreamReader(clientsock.getInputStream()));
DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
out.writeBytes(sending);
String line = in.readLine();
if (line.contentEquals("login success")){
Toast.makeText(this, "login success", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "receive data from
server:"+clientsock.getInetAddress(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(Client_layoutActivity.this, chat_wall.class);
startActivity(i);
} else {
Toast.makeText(this, "Error ", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
System.out.println(e);
System.out.println("Connection Failed");
}
PAGE 2 : for Chat purpose
package com.willis.layout;
import java.io.*;
import java.net.*;
import android.widget.*;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.R.integer;
public class chat_wall extends Activity {
Client_layoutActivity ob;
public EditText chatroom;
public Button sendbtn;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.chatwall);
sendbtn = (Button)findViewById(R.id.sendmsg);
sendbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendingmsg();
}
});
chatroom = (EditText)findViewById(R.id.chatroom);
}
public void sendingmsg (){
try
{
BufferedReader in = new BufferedReader(new
InputStreamReader(clientsock.getInputStream()));
DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
String name = chatroom.getText().toString();
String send = "chat."+name+". \n";
System.out.println("Sending message: "+send);
out.writeBytes(send);
String msgin = in.readLine();
Toast.makeText(this, msgin, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
System.out.println(e);
System.out.println("Connection Failed");
}
}
}
As I understood what you want is to use the same socket for login and chat purposes. Instead of sending a Socket object with Intent between activities consider another options:
Define a class to manage opened sockets and create it's static instance or make it a Singleton.
Use a local Service as described in documentation. Define your sendingmsg and login methods in it and bind with Activity on it's onResume:
private ChatService mService;
...
#Override
protected void onResume() {
doBindService();
sendbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
mService.sendingmsg();
}
});
}
#Override
protected void onPause() {
doUnbindService();
}

how do I want to fix OnClickListener1

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);
}

Categories

Resources