Question

My app stops after I attempted to use a ListView to communicate to a server.

My layout:

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

}

and when I try to run it returns this error only:

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)
Was it helpful?

Solution

Your NullPointerException is caused by the wrong inflated layout. As you can see here:

setContentView(R.layout.activity_main);  

in your activity, you are setting the layout activity_main.xml and not the layout which is posted in your question as fragment_main.xml. Your activity try to find a view which is not on the right layout.

To avoid this, try to create another layout named activity_main.xml and copy/paste (or you should cut) all your views inside it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top