Android Studio。 NullPointerException没有任何指向我的项目的链接

时间:2017-12-01 20:16:26

标签: java android nullpointerexception jsoup

我正在使用jsoup从网站获取一些数据并对其进行过滤然后在ListView上显示它,但无论我对我的代码做什么,我每次都会收到一个奇怪的错误。它没有任何链接到我的项目,而是链接到Android库和一些奇怪的东西,如zygote等。 这是我的代码:

package com.shapedhorizon.teymur.epiknovel;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;


public class SeriInfo extends AppCompatActivity {


    ListView listView ;
    Context ncontext;
    String[] tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seri_info);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //something
            }
        });
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        ncontext = this;
        listView = findViewById(R.id.seri_bolum);
        Log.i("Message", message);
        AsyncInternet task = new AsyncInternet();
        task.execute(message);
        Log.i("OMG", "You got to be kidding with me");
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        return;
    }
    private class AsyncInternet extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            Elements els;
            Document doc= null;
            Log.e("try",strings[0]);
            try {
                int ttsi = 0;
                doc = Jsoup.connect(strings[0]).get();
                els = doc.getElementsByAttributeValueStarting("href","https://www.epiknovel.com/seri");
                Integer size = 0;
                for (Element e: els
                        ) {
                    if(!(e==null)) {
                        if(!e.parent().tagName("span").text().contains("Premium")){

                            size++;

                            Log.i("e.text",e.text());
                        }
                    }
                }
                Log.e("size", size.toString());
                tts = new String[size];
                for (Element e: els
                        ) {

                    if(!(e==null)) {
                        if(!e.parent().tagName("span").text().contains("Premium")){
                            Log.i("e.text",e.text());
                            tts[ttsi] = e.text();
                        }
                    }
                }
            } catch (IOException c) {
                c.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if(!(tts ==null)) {
                Log.i("tts","IS NOT NULL");
                ArrayAdapter adapter = new ArrayAdapter<String>(ncontext, R.layout.seri_view, tts);
                Log.i("Adapter", "Check if we set up the adapter");
                if(!(adapter==null)) {
                    listView.setAdapter(adapter);
                    Log.i("LW", "Weird that we passed that part");
                }else{
                    Log.e("ADAPTER", "IS NULL");
                }
            }else{
                Log.e("tts","IS NULL");
            }
            Log.i("OMG","Still?! What the hell is wrong with you?!");
            return;
        }
    }
}

我的错误是:l

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.shapedhorizon.teymur.epiknovel, PID: 27846
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                      at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
                      at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
                      at android.widget.AbsListView.obtainView(AbsListView.java:2474)
                      at android.widget.ListView.measureHeightOfChildren(ListView.java:1301)
                      at android.widget.ListView.onMeasure(ListView.java:1203)
                      at android.view.View.measure(View.java:19162)
                      at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:934)
                      at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:973)
                      at android.view.View.measure(View.java:19162)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6115)
                      at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
                      at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                      at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                      at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
                      at android.view.View.measure(View.java:19162)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6115)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:223)
                      at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                      at android.view.View.measure(View.java:19162)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6115)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1723)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:788)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:648)
                      at android.view.View.measure(View.java:19162)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6115)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:223)
                      at android.view.View.measure(View.java:19162)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6115)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1723)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:788)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:648)
                      at android.view.View.measure(View.java:19162)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6115)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:223)
                      at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2690)
                      at android.view.View.measure(View.java:19162)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2530)
                      at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1490)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1744)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1371)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6773)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:896)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:698)
                      at android.view.Choreographer.doFrame(Choreographer.java:633)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:882)
                      at android.os.Handler.handleCallback(Handler.java:815)
                      at android.os.Handler.dispatchMessage(Handler.java:104)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5811)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:768)

编辑1:我添加了

for (Object obj: tts
                 ) {
                if (obj.equals(null)){
                    Log.e("BIG ERROR", "There is null in tts");
                }
            }

在doInBackground函数中,我遇到了一个新错误:

 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
                  Process: com.shapedhorizon.teymur.epiknovel, PID: 30862
                  java.lang.RuntimeException: An error occurred while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:309)
                      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                      at java.lang.Thread.run(Thread.java:818)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
                      at com.shapedhorizon.teymur.epiknovel.SeriInfo$AsyncInternet.doInBackground(SeriInfo.java:102)
                      at com.shapedhorizon.teymur.epiknovel.SeriInfo$AsyncInternet.doInBackground(SeriInfo.java:62)
                      at android.os.AsyncTask$2.call(AsyncTask.java:295)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                      at java.lang.Thread.run(Thread.java:818) `

和(SeriInfo.java:102)引用if (obj.equals(null)){

编辑2:我将数组更改为List。以下是 AsyncInternet 函数中已更改的内容:

private class AsyncInternet extends AsyncTask<String, Void, List<String>>{

    @Override
    protected List<String> doInBackground(String... strings) {
        Elements els;
        Document doc= null;
        List<String> adapterData = new ArrayList<>();
        Log.e("try",strings[0]);
        try {
            int ttsi = 0;
            doc = Jsoup.connect(strings[0]).get();
            els = doc.getElementsByAttributeValueStarting("href","https://www.epiknovel.com/seri");
            for (Element e: els
                    ) {

                    if(!e.parent().tagName("span").text().contains("Premium")){
                        if(e.text() != null) {
                            if(e.parent().parent().html().contains("td")) {
                                Log.i("e.text", e.text());
                                adapterData.add(e.text());
                            }
                    }
                }
            }
        } catch (IOException c) {
            c.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<String> result) {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(ncontext, R.layout.seri_view, result);
        Log.i("Adapter", "set up the adapter");
        listView.setAdapter(adapter);
        Log.i("LW", "Weird that we passed that part");
    }
}

}

现在我得到了错误:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.shapedhorizon.teymur.epiknovel, PID: 5914
              java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                  at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337)
                  at android.widget.ListView.setAdapter(ListView.java:491)
                  at com.shapedhorizon.teymur.epiknovel.SeriInfo$AsyncInternet.onPostExecute(SeriInfo.java:97)
                  at com.shapedhorizon.teymur.epiknovel.SeriInfo$AsyncInternet.onPostExecute(SeriInfo.java:63)
                  at android.os.AsyncTask.finish(AsyncTask.java:651)
                  at android.os.AsyncTask.-wrap1(AsyncTask.java)
                  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

(SeriInfo.java:97)listView.setAdapter(adapter);

2 个答案:

答案 0 :(得分:0)

在尝试使用onPostExecute方法创建适配器之前,请检查tts数组是否包含null元素。我的猜测是在这个方法的第三行触发异常:ArrayAdapter adapter = .... 您还可以在其周围放置try / catch(Exception ex)以查看它是否以及它捕获的异常。

修改 我想我发现了这个问题 - 你的 doInBackground 方法应该返回你的List(或Array),而不是null。然后通过 onPostExecute 将返回的值用作输入参数。这来自官方文档

  

doInBackground(Params ...)...此步骤必须返回计算结果,并将其传递回最后一步......

答案 1 :(得分:0)

对于初学者== null是正确的空检查。你可以用!= null否定它。

但无论如何,我建议不要使用数组,并使用List作为适配器。

开始
extends AsyncTask<String, Void, List<String>>

然后

    @Override
    protected List<String> doInBackground(String... strings) {
        Elements els;
        Document doc= null;
        List<String> adapterData = new ArrayList<>();
        Log.e("try",strings[0]);
        try {
            // add non null strings to adapterData 
        } catch (IOException c) {
            c.printStackTrace();
        }
        return adapterData;
 } 

现在你在onPostExecute中有一个非空的列表对象。如果你在这里初始化适配器

,那么适配器就不会为空
    @Override
    protected void onPostExecute(List<String> result) {
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(ncontext, R.layout.seri_view, result);
            Log.i("Adapter", "set up the adapter");
            listView.setAdapter(adapter);
            Log.i("LW", "Weird that we passed that part");
    }

您还应该将适配器移动到Activity中的某个字段,并使用onCreate中的空列表初始化它