Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我在填充后得到空对象?_Java_Android_Nullpointerexception - Fatal编程技术网

Java 为什么我在填充后得到空对象?

Java 为什么我在填充后得到空对象?,java,android,nullpointerexception,Java,Android,Nullpointerexception,我从网站上得到一些输入流(即) 我有xml解析器,在一个类中,我通过解析这个流来生成自己的对象xml。如果我在那里检查一下,一切都很好。在我试图通过getter从另一个类获取这个对象之后,我得到了null指针异常,我不明白为什么 头等舱 public class Connection { private final String URLSTRING = "http://blabla.html"; private Xml xml; private Context context; private

我从网站上得到一些输入流(即) 我有xml解析器,在一个类中,我通过解析这个流来生成自己的对象xml。如果我在那里检查一下,一切都很好。在我试图通过getter从另一个类获取这个对象之后,我得到了null指针异常,我不明白为什么

头等舱

public class Connection {

private final String URLSTRING = "http://blabla.html";
private Xml xml;
private Context context;
private String result;
private boolean connection;

public Xml getXml() {
    return xml;
}

public void setXml(Xml xml) {
    this.xml = xml;
}

public String getResult() {
    return result;
}

public void setResult(String result) {
    this.result = result;
}

public boolean getConnection() {
    return connection;
}

public void setConnection(boolean connection) {
    this.connection = connection;
}

public Connection(Context context) {
    this.context = context;
}
public void connect() {
    ConnectivityManager connMgr = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        new DownloadWebpageTask().execute(URLSTRING);
        connection = true;

    } else {
        connection = false;
    }
}


private class DownloadWebpageTask extends AsyncTask<String, Void,    String> {
@Override
protected String doInBackground(String... urls) {

    // params comes from the execute() call: params[0] is the url.
    try {
        return downloadUrl(urls[0]);
    } catch (IOException e) {
        return "Unable to retrieve web page. URL may be invalid.";
    }
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
    result = "";
}
}
    private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        //Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();


        String contentAsString ="aa";
        XmlParser xmlParser = new XmlParser();
        xml = xmlParser.getParsedXml(is);
        return contentAsString;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
尝试设置TextView时出现错误。 谢谢你的建议。 编辑:logcat

FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.example.blackess.connectiontest.MainActivity$1.onClick(MainActivity.java:48)
        at android.view.View.performClick(View.java:2485)
        at android.view.View$PerformClick.run(View.java:9080)
        at android.os.Handler.handleCallback(Handler.java:587)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:130)
        at android.app.ActivityThread.main(ActivityThread.java:3687)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
        at dalvik.system.NativeStart.main(Native Method)

这是一个并发性问题

方法
connect()

不等待
下载WebPagetTask
异步任务完成。它立即返回

你能做的就是做一个倾听者。将其放入
连接中

public interface ConnectionListener {
    public void onGotXML(XMl xml);
}
将其添加到构造函数中:

ConnectionListener listener;
public Connection(Context context, ConnectionListener listener) {
    this.context = context;
    this.listener = listener;
}
postExecute

@Override
protected void onPostExecute(String result) {
    listener.onGotXML(this.xml);
}
然后在活动中实现此侦听器:

Connection con;
TextView textView;    

public void onCreate(){
...
   textView = (TextView) findViewById(R.id.textView2);
   con = new Connection(context, new Connection.ConnectionListener(){

   @Override
   public void onGotXML(XMl xml){
      if(xml != null){
         textView.setText(xml.getDate());
      }else{
          Toast.makeText(getApplicationContext(),
                "no connection", Toast.LENGTH_LONG).show();
      }
     }
   });

   button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
         con.connect();
      }

    });

} 

我的英语不好,如果你有问题,请评论

根据,您应该在UI线程中调用
downloadWebPagetTask
,换句话说,就是
View.OnClickListener.onClick()

并让您的
下载WebPagetAsk
类更新按钮的文本


我同意@InMystry

提供实际错误将有助于人们在我编写textView.setText(xml.getDate());时,帮助人们了解
MainActivity
第48行的内容。在第一个类中,即使在调试模式下,mainActivity对象中的xml中也有所有值。xml为null。我应该怎么做才能让该任务完成加载?现在只有Toast位于错误的位置,但我可以修复它。完美的非常感谢。
@Override
protected void onPostExecute(String result) {
    listener.onGotXML(this.xml);
}
Connection con;
TextView textView;    

public void onCreate(){
...
   textView = (TextView) findViewById(R.id.textView2);
   con = new Connection(context, new Connection.ConnectionListener(){

   @Override
   public void onGotXML(XMl xml){
      if(xml != null){
         textView.setText(xml.getDate());
      }else{
          Toast.makeText(getApplicationContext(),
                "no connection", Toast.LENGTH_LONG).show();
      }
     }
   });

   button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
         con.connect();
      }

    });

}