应用程序停止启动ListView更新错误

时间:2014-04-07 01:59:59

标签: java android android-listview android-adapter

我尝试使用ListView与服务器通信后,我的应用停止了。

我的布局:

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.ghhwer.pcremote.Main$PlaceholderFragment"
    android:id="@+id/Layout">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Refresh"
        android:id="@+id/Refresh"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Connect"
        android:id="@+id/Connect"
        android:layout_alignTop="@+id/Refresh"
        android:layout_toLeftOf="@+id/Disconnect" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Disconnect"
        android:id="@+id/Disconnect"
        android:layout_alignTop="@+id/Connect"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Please make sure you are connected to the same WiFi as your host computer"
        android:id="@+id/Text"
        android:textSize="15dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/Text"
        android:layout_above="@+id/Refresh">

        <ListView
            android:id="@+id/ComputerList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>

</RelativeLayout>

Main.java:

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;


public class Main extends Activity {

    private ListView lvItem;
    private Button btnRefresh;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpView();
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    private void setUpView() {
        btnRefresh = (Button)this.findViewById(R.id.Refresh);
        lvItem = (ListView)this.findViewById(R.id.ComputerList);
        itemArrey = new ArrayList<String>();
        itemArrey.clear();
        itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
        lvItem.setAdapter(itemAdapter);
        btnRefresh.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                addItemList();
            }
        });
    }

    protected void addItemList() {
    ArrayList<String> newList = new ArrayList<String>();
    try{
        newList = RefreshList.GetServerRunningIps();
    }
    catch (UnknownHostException e){}
    catch (IOException e){}
    itemArrey = newList;
    itemAdapter.notifyDataSetChanged();

    }

    @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();
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}

RefreshList.java:

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.SocketTimeoutException;
import java.net.SocketException;
import java.net.InetAddress;

public class RefreshList {

    public static ArrayList<String> GetServerRunningIps() throws UnknownHostException, IOException
    {
        ArrayList<String> Res = new ArrayList<String>();
        ArrayList<String> Ips = new ArrayList<String>();
        Ips = ListIps();
        for(int x = 0;x<Ips.size()-1;x++)
        {
            String CanUse = WaitResponce(Ips.get(x));
            if(CanUse.contains("Here"))
            {
                Res.add(Ips.get(x));
            }
            else{
                Res.add("NOTHING FOUND");
            }
        }
        return Res;
    }

    private static ArrayList<String> ListIps() throws UnknownHostException, IOException
    {
        ArrayList<String> Res = new ArrayList<String>();
        InetAddress localhost = InetAddress.getLocalHost();
        byte[] ip = localhost.getAddress();
        for (int i = 1; i <= 254; i++)
        {
            ip[3] = (byte)i;
            InetAddress address = InetAddress.getByAddress(ip);
            if (address.isReachable(1000))
            {
                Res.add(address.toString());
            }
        }
        return Res;
    }

    private static String WaitResponce(String Ip)
    {
        DatagramSocket s;

        try {
            s = new DatagramSocket(5700);
            byte[] buf = new byte[1000];
            DatagramPacket dp = new DatagramPacket(buf, buf.length);
            InetAddress hostAddress = InetAddress.getByName(Ip);

            String outString = "ServerCheck_"+InetAddress.getLocalHost().getHostAddress();
            buf = outString.getBytes();

            DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 5600);
            s.send(out);

            s.setSoTimeout(2000);

            while(true){
                try {
                    s.receive(dp);
                    String rcvd = new String(dp.getData(), 0, dp.getLength());
                    return rcvd;
                }
                catch (SocketTimeoutException e) {
                    // timeout exception.
                    s.close();
                    return new String("Timeout reached!!! ");
                }
            }

        } catch (SocketException e1) {
            System.out.println("Socket closed " + e1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

当我尝试运行它时只返回此错误:

04-06 22:51:32.680  31163-31163/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.ghhwer.pcremote, PID: 31163
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ghhwer.pcremote/com.ghhwer.pcremote.Main}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.access$800(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5102)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.ghhwer.pcremote.Main.setUpView(Main.java:45)
            at com.ghhwer.pcremote.Main.onCreate(Main.java:31)
            at android.app.Activity.performCreate(Activity.java:5248)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.access$800(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5102)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

您的NullPointerException是由错误的夸大布局引起的。正如你在这里看到的那样:

setContentView(R.layout.activity_main);  

在您的活动中,您要将布局activity_main.xml设置为问题fragment_main.xml。您的活动尝试查找不在正确布局上的视图。

要避免这种情况,请尝试创建另一个名为activity_main.xml的布局,然后复制/粘贴(或者应该剪切)其中的所有视图。