服务器端Android应用程序无法启动

时间:2016-03-20 11:15:45

标签: java android sockets server data-stream

这是我的第一个问题,我现在一直坚持这个未知问题。该应用程序成功运行,直到我添加了一些新代码来制作自定义列表视图组件并从客户端读取一些消息。

MainActivity.java

 `public class MainActivity extends Activity {

    TextView info, infoip, msg;
    String message = "";
    ServerSocket serverSocket;

    ArrayList<String> list = new ArrayList<String>();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
    */
    private GoogleApiClient client;

    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     info = (TextView) findViewById(R.id.info);
     infoip = (TextView) findViewById(R.id.infoip);
     msg = (TextView) findViewById(R.id.msg);




     //instantiate custom adapter
     MyCustomAdapter adapter = new MyCustomAdapter(list, this);

     //handle listview and assign adapter
     ListView lView = (ListView)findViewById(R.id.myListView);
     lView.setAdapter(adapter);

     infoip.setText(getIpAddress());

     Thread socketServerThread = new Thread(new SocketServerThread());
       socketServerThread.start();
     // ATTENTION: This was auto-generated to implement the App Indexing API.
     // See https://g.co/AppIndexing/AndroidStudio for more information.
     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }
     public void addOrder(String ordername)
     {
      list.add(ordername);

    }
     @Override
    protected void onDestroy() {
    super.onDestroy();

       if (serverSocket != null) {
      try {
       serverSocket.close();
        } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
    }

    @Override
    public void onStart() {
     super.onStart();

     // ATTENTION: This was auto-generated to implement the App Indexing API.
     // See https://g.co/AppIndexing/AndroidStudio for more information.
     client.connect();
     Action viewAction = Action.newAction(
          Action.TYPE_VIEW, // TODO: choose an action type.
          "Main Page", // TODO: Define a title for the content shown.
          // TODO: If you have web page content that matches this app activity's    content,
          // make sure this auto-generated web page URL is correct.
          // Otherwise, set the URL to null.
          Uri.parse("http://host/path"),
          // TODO: Make sure this auto-generated app deep link URI is correct.
          Uri.parse("android-app://com.buzzer.ventern.clientservertrial/http/host/path")
  );
  AppIndex.AppIndexApi.start(client, viewAction);
 }

 @Override
 public void onStop() {
  super.onStop();

       // ATTENTION: This was auto-generated to implement the App Indexing API.
       // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
          Action.TYPE_VIEW, // TODO: choose an action type.
          "Main Page", // TODO: Define a title for the content shown.
               // TODO: If you have web page content that matches this app    activity's content,
             // make sure this auto-generated web page URL is correct.
          // Otherwise, set the URL to null.
          Uri.parse("http://host/path"),
          // TODO: Make sure this auto-generated app deep link URI is correct.
              Uri.parse("android-app://com.buzzer.ventern.clientservertrial/http/host/path")
  );
  AppIndex.AppIndexApi.end(client, viewAction);
  client.disconnect();
 }

 public class SocketServerThread extends Thread {
    String ordername;
  static final int SocketServerPORT = 8080;
  int count = 0;
    MainActivity ma= new MainActivity();
  @Override
  public void run() {
   Socket socket = null;
   DataInputStream dataInputStream = null;
   DataOutputStream dataOutputStream = null;

   try {
    serverSocket = new ServerSocket(SocketServerPORT);
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      info.setText("I'm waiting here: "
              + serverSocket.getLocalPort());
     }
    });

    while (true) {
     socket = serverSocket.accept();
     dataInputStream = new DataInputStream(
             socket.getInputStream());
     dataOutputStream = new DataOutputStream(
             socket.getOutputStream());

     String messageFromClient = "";

     //If no message sent from client, this code will block the program
     messageFromClient = dataInputStream.readUTF();
        ordername=dataInputStream.readUTF();
    ma.addOrder(ordername);
     count++;
     message += "#" + count + " from " + socket.getInetAddress()
             + ":" + socket.getPort() + "\n"
             + "Msg from client: " + messageFromClient + "\n";

     MainActivity.this.runOnUiThread(new Runnable() {

      @Override
      public void run() {
       msg.setText(message);
      }
     });

     String msgReply = "Hello from server, order #" + count+" has been accepted.";
     dataOutputStream.writeUTF(msgReply);
        dataOutputStream.flush();


    }
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    final String errMsg = e.toString();
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
     public void run() {
      msg.setText(errMsg);
     }
    });

   } finally {
    if (socket != null) {
     try {
      socket.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }

    if (dataInputStream != null) {
     try {
      dataInputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }

    if (dataOutputStream != null) {
     try {
      dataOutputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
  }

 }

 private String getIpAddress() {
  String ip = "";
  try {
   Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
           .getNetworkInterfaces();
   while (enumNetworkInterfaces.hasMoreElements()) {
    NetworkInterface networkInterface = enumNetworkInterfaces
            .nextElement();
    Enumeration<InetAddress> enumInetAddress = networkInterface
            .getInetAddresses();
    while (enumInetAddress.hasMoreElements()) {
     InetAddress inetAddress = enumInetAddress.nextElement();

     if (inetAddress.isSiteLocalAddress()) {
      ip += "SiteLocalAddress: "
              + inetAddress.getHostAddress() + "\n";
     }

    }

   }

  } catch (SocketException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   ip += "Something Wrong! " + e.toString() + "\n";
  }

  return ip;
 }
}`

MyCustomAdapter

public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
    private ArrayList<String> list = new ArrayList<String>();
    private Context context;



    public MyCustomAdapter(ArrayList<String> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int pos) {
        return list.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return 0;
        //just return 0 if your list items do not have an Id variable.
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.layout_list_item, null);
        }

        //Handle TextView and display string from your list
        TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
        listItemText.setText(list.get(position));

        //Handle buttons and add onClickListeners
        Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);


        deleteBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //send acknowledgement to client
                list.remove(position); //or some other task
                notifyDataSetChanged();
            }
        });


        return view;
    }
}

content_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="Server V1.0"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/infoip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="255dp" >

        <TextView
            android:id="@+id/msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/myListView"
        android:layout_gravity="center_horizontal" />

    ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:clickable="true"
        android:contextClickable="false" />

</LinearLayout>

和layout_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/list_item_string"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:paddingLeft="8dp"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/delete_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="5dp"
        android:text="Okay" />



</RelativeLayout>

我是android新手,很多这个代码都是从一些android-er帖子中引用的,还有一些来自之前的stackoverflow答案。如果有人能告诉我为什么我的应用程序在启动时崩溃了。

编辑:解决了错误,但现在在客户端的ASyncTAsk中异常,在doInBackground()中 客户端应用程序的doInBackground()的代码

protected Void doInBackground(Void... arg0) {

        Socket socket = null;
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;

        try {
            socket = new Socket(dstAddress, dstPort);
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataInputStream = new DataInputStream(socket.getInputStream());
            item=ma.getStr();
            dataOutputStream.writeUTF(item);
            dataOutputStream.flush();
            response = dataInputStream.readUTF();

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }`

0 个答案:

没有答案