java - 使用 TextView 获取空指针

标签 java android

在 Android 中获取 TextView 时,出现 nullPointerException。似乎有一天我可以设置 TextViews,它会起作用,但有时却不起作用。有人可以向我解释为什么我会从中得到一个空指针吗?它位于方法 setTextView() 的第一行,并且是从 Net 类调用的。

package com.tsunamistudios.computerwatch;

import java.io.IOException;
import java.io.OptionalDataException;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class Client extends Activity {

    private static String message;
    private static ArrayList<Program> programs = new ArrayList<Program>();
    private static Net net;
    private TextView txtView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);   
        new Thread(net = new Net()).start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.client, menu);
        return true;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        Client.message = message;
    }

    public ArrayList<Program> getPrograms() {
        return programs;
    }

    public void setTextView() {
        txtView = (TextView) findViewById(R.id.txtView);
        txtView.setText(getPrograms().get(0).getName() + getPrograms().get(0).getDescription());
    }

    public void setPrograms(ArrayList<Program> programs) {
        Client.programs = programs;
    }

    public Net getNet() {
        return net;
    }

    public void setNet(Net net) {
        Client.net = net;
    }


    public TextView getTxtView() {
        return txtView;
    }
}

Net.java

package com.tsunamistudios.computerwatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;
import java.io.PrintWriter;
import java.net.Socket;

public class Net extends Client implements Runnable {

    private static Socket echoSocket;
    private static PrintWriter out;
    private static BufferedReader in;
    private static ObjectInputStream inFromServer;

    @Override
    public void run() {
        try {
            String hostName = "192.168.0.105";
            int portNumber = 6984;
            echoSocket = new Socket(hostName, portNumber);
//          out = new PrintWriter(echoSocket.getOutputStream(), true);
//          in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
            inFromServer = new ObjectInputStream(echoSocket.getInputStream());   

            getPrograms().add((Program) getProgramsFromObject());           

            setTextView(getTxtView());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }

    public static Socket getEchoSocket() {
        return echoSocket;
    }

    public Object getProgramsFromObject() {     
        try {
            if(getObjectInputStream() != null) {
                return getObjectInputStream().readObject();
            } else {
                return new Program("Nullpointer", "NullPointer", "Null", null);
            }
        } catch (OptionalDataException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    public static void setEchoSocket(Socket echoSocket) {
        Net.echoSocket = echoSocket;
    }

    public static PrintWriter getOut() {
        return out;
    }

    public static void setOut(PrintWriter out) {
        Net.out = out;
    }

    public static BufferedReader getIn() {
        return in;
    }

    public ObjectInputStream getObjectInputStream() {
        return inFromServer;
    }

    public static void setInFromServer(ObjectInputStream inFromServer) {
        Net.inFromServer = inFromServer;
    }

    public static void setIn(BufferedReader in) {
        Net.in = in;
    }

}

xml

<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: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=".Client" >

    <TextView
        android:id="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="162dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

错误

12-21 12:57:17.043: E/AndroidRuntime(30909): FATAL EXCEPTION: Thread-1266
12-21 12:57:17.043: E/AndroidRuntime(30909): Process: com.tsunamistudios.computerwatch, PID: 30909
12-21 12:57:17.043: E/AndroidRuntime(30909): java.lang.NullPointerException
12-21 12:57:17.043: E/AndroidRuntime(30909):    at android.app.Activity.findViewById(Activity.java:1884)
12-21 12:57:17.043: E/AndroidRuntime(30909):    at com.tsunamistudios.computerwatch.Client.setTextView(Client.java:47)
12-21 12:57:17.043: E/AndroidRuntime(30909):    at com.tsunamistudios.computerwatch.Net.run(Net.java:30)
12-21 12:57:17.043: E/AndroidRuntime(30909):    at java.lang.Thread.run(Thread.java:841)

最佳答案

您的 Net 类声明为

public class Net extends Client implements Runnable {

通过继承层次结构,它还扩展了 Activity,它具有一个 window 实例变量,默认情况下将初始化为 null。当你打电话时

 setTextView(getTxtView());

它调用继承的方法

public void setTextView() {
    txtView = (TextView) findViewById(R.id.txtView);
    txtView.setText(getPrograms().get(0).getName() + getPrograms().get(0).getDescription());
}

但是由于您的 Net 是 Android 尚未提供 WindowActivity,因此它会在内部失败。 implementation Activity

public View findViewById(int id) {
    return getWindow().findViewById(id);
}

其中 getWindow() 将返回 null

您将不得不重新考虑您的设计。 Net 真的是一个 Activity 吗?

关于java - 使用 TextView 获取空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20721373/

相关文章:

Android Activity 垃圾收集

java - 从 FileInputStream 或 FileReader 中剥离 HTTP header 信息

javascript - 使用 native react 发送电子邮件(带附件,android)

android - 如何更改 xamarin 表单中的导航页面后退按钮

android - 避免与 android :layout_centerVertical ="true" in RelativeLayout 重叠

android - 使用 KitKat 存储访问框架后打开 Google Drive File Content URI

java - 一个 spring 集成管道中的多个数据源?

java - 将JAVA程序作为计划任务运行

java String 和 StringBuilder

android - 不同的 Facebook 应用程序使用相同的 key 哈希