在onCreate调用android app之前的java.lang.NullPointerException

时间:2014-11-24 21:02:21

标签: java android nullpointerexception

我在弄清楚如何以及为什么会收到java.lang.NullPointerException时遇到了很多麻烦。我不知道发生了什么,因为它似乎发生在我的程序加载之前。我在onCreate函数的第一行设置了一个断点,我的android日志仍然显示我抛出了这个异常,但程序继续启动,我到达了断点。但踩到我会得到非常奇怪的行为。我将发布有问题的代码以及日志。如果有任何其他信息需要帮助我这个请问。也请原谅。我是堆栈溢出的新手

package com.example.facta.myapplication;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;

import org.xmlpull.v1.XmlPullParser;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by facta on 11/21/2014.
 */
public class SiteConfig {
    private XmlResourceParser configParser;
    ArrayList<RSSProviderInfo> RSSProviderInfos;
    ArrayList<String> RSSProviderNames;

public SiteConfig()
{
    RSSProviderInfos = new ArrayList<RSSProviderInfo>();
    RSSProviderNames = new ArrayList<String>();
}

public ArrayList<RSSProviderInfo> getProvierInfos()
{
    return RSSProviderInfos;
}
public ArrayList<String> getProvierNames()
{
    return RSSProviderNames;
}

public void loadConfig(Context context, int resourceId)
{
    configParser = context.getResources().getXml(resourceId);
    RSSProviderInfos.clear();

    RSSProviderInfo providerInfo = new RSSProviderInfo();

    ArrayList<String> providerNames = loadProviders(configParser);

    for(int i=0; i < providerNames.size(); i++)
    {
        providerInfo = LoadProviderInfo(configParser, providerNames.get(i));
        if(providerInfo != null && providerInfo.isComplete()) {
            RSSProviderInfos.add(providerInfo);
        }
    }
}

private RSSProviderInfo LoadProviderInfo(XmlResourceParser parser, String provider) {

    RSSProviderInfo info = new RSSProviderInfo();
    String attrName = new String();

    try {
        parser.next();
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG
                    && parser.getName().equalsIgnoreCase("site" )) {

                attrName = parser.getAttributeValue(null, "name");

                if(attrName.equalsIgnoreCase(provider + ".enabled"))
                {
                  /*
                    String value = parser.getAttributeValue(null, "value");
                    if(value.equalsIgnoreCase("no")) {
                        Log.d("LoadProviderInfo", "value does equal no");
                        return null; //If it's not enabled don't include it in the config
                    }
                    */
                }
                else if(attrName.equalsIgnoreCase(provider + ".elementTag"))
                {
                    info.setElementTag(parser.getAttributeValue(null, "value"));
                }
                else if(attrName.equalsIgnoreCase(provider + ".titleTag"))
                {
                    info.setTitleTag(parser.getAttributeValue(null, "value"));
                }
                else if(attrName.equalsIgnoreCase(provider + ".linkTag"))
                {
                    info.setLinkTag(parser.getAttributeValue(null, "value"));
                }
                else if(attrName.equalsIgnoreCase(provider + ".descriptionTag"))
                {
                    info.setDescriptionTag(parser.getAttributeValue(null,"value"));
                }
                else if(attrName.equalsIgnoreCase(provider + ".url"))
                {
                    info.addUrl(parser.getAttributeValue(null, "value"));
                }
                break;
            }
            eventType = parser.next();
        }
    }
    catch (Exception e)
    {
        Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
        e.printStackTrace();
        StackTraceElement st[] = e.getStackTrace();
        for(int i=0; i < st.length; i++)
        {
            Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());

        }
    }



    return null;
}

private ArrayList<String> loadProviders(XmlResourceParser parser) {

    ArrayList<String> names = new ArrayList<String>();

    try {
        parser.next();
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG
                    && parser.getName().equalsIgnoreCase("siteproviders")) {

               String[] parsedNames = parser.getAttributeValue(null, "value").split(",");

                for (int i=0; i < parsedNames.length; i++)
                {
                    names.add(i, parsedNames[i]);
                }
                break;
            }
            eventType = parser.next();
        }
    }
    catch (Exception e)
    {
        Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
        e.printStackTrace();
        StackTraceElement st[] = e.getStackTrace();
        for(int i=0; i < st.length; i++)
        {
            Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());

        }

    }

    return names;
}


}

记录下面

11-23 18:20:40.830      537-537/com.example.facta.myapplication D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
11-23 18:20:41.569      537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:41.580      537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.040      537-537/com.example.facta.myapplication D/loadProviders﹕ Caught an exeption: java.lang.NullPointerException
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ java.lang.NullPointerException
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadProviders(SiteConfig.java:119)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadConfig(SiteConfig.java:42)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.fetch(ResultsActivity.java:94)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.onCreate(ResultsActivity.java:62)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Activity.performCreate(Activity.java:4465)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-23 18:20:42.040      537-537/com.example.facta.myapplication W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
11-23 18:20:42.070      537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:42.080      537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.270      537-537/com.example.facta.myapplication D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
11-23 18:37:36.440      669-669/com.example.facta.myapplication W/ActivityThread﹕ Application com.example.facta.myapplication is waiting for the debugger on port 8100...
11-23 18:37:36.490      669-669/com.example.facta.myapplication I/System.out﹕ Sending WAIT chunk
11-23 18:37:36.701      669-675/com.example.facta.myapplication I/dalvikvm﹕ Debugger is active
11-23 18:37:36.740      669-669/com.example.facta.myapplication I/System.out﹕ Debugger has connected
11-23 18:37:36.740      669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:36.900      669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:36.910      669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:37:36.940      669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.140      669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.680      669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.880      669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.079      669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.279      669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.369      669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:38.379      669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'

调用下面的活动

package com.example.facta.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import java.util.ArrayList;

/* TODO
   Need to make a config file that has the following format.
   site.names          = CNN,FOX,NBC,AP

   site.CNN.enabled   = yes
   site.CNN.searchtag = item
   site.CNN.titletag  = title
   site.CNN.linktag   = link
   site.CNN.descriptiontag = description
   site.CNN.numurls   = 10
   site.CNN.url.1     = "https://www.cnn.com/top_stories.rss
   site.CNN.url.2     = "https://www.cnn.com/world_politics.rss

   site.FOX.enabled   = no
   site.FOX.searchtag = story

 */



public class ResultsActivity extends Activity {

private ArrayList<String> finalUrls = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_results);
    finalUrls.add("http://rss.cnn.com/rss/cnn_topstories.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_world.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_us.rss");
    finalUrls.add("http://rss.cnn.com/rss/money_latest.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_allpolitics.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_crime.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_tech.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_health.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_showbiz.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_travel.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_living.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_freevideo.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_studentnews.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_mostpopular.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_latest.rss");
    finalUrls.add("http://rss.ireport.com/feeds/oncnn.rss");
    finalUrls.add("http://rss.cnn.com/rss/cnn_behindthescenes.rss");
    this.fetch();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_results, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void fetch() {
    /**TODO possibly load config then for each provider pass in RSSProviderInfo into HandleXML
     That way HandleXML can set all the tags it needs and then parse the urls from the param
     */

    SiteConfig siteConfig = new SiteConfig();
    siteConfig.loadConfig(this, R.xml.sites);
    ArrayList<RSSProviderInfo> siteConfigProvierInfos = siteConfig.getProvierInfos();

    for (int k = 0; k < siteConfigProvierInfos.size(); k++) {

        HandleXML obj = new HandleXML(siteConfigProvierInfos.get(k));
        obj.fetchXML();

        while (!obj.parsingComplete) {
            try {
                Thread.sleep(500, 0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            final ArrayList<RSSInfo> rssInfos = obj.getRssInfos();
            final TableLayout tableLayout = (TableLayout) findViewById(R.id.results_table);

            Log.d("fetch", "Size of rssinfos " + rssInfos.size());

            for (int i = 0; i < rssInfos.size(); i++) {
                final int index = i;
                final TableRow tableRow = new TableRow(this);
                tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));

                //Get information from infos
                final TextView textView = new TextView(this);
                textView.setText(rssInfos.get(index).getTitle());
                textView.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));

                tableRow.setClickable(true);
                tableRow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(rssInfos.get(index).getLink()));
                        startActivity(intent);
                    }
                });

                tableRow.addView(textView);
                tableLayout.addView(tableRow);

            }

            Log.d("fetch", "tableLayout = " + tableLayout.toString());

        }

    }

}
}

1 个答案:

答案 0 :(得分:0)

很抱歉这个混乱。我想我需要复习Android Studio。这是我的代码的先前版本的错误(注意昨天11-23的日期)。我认为logcat中的“全部清除”字面上清除了所有并删除它。我发现我错了。我所知道的目前没有NPE。抱歉浪费时间....使用android studio为我学习的课程。注意到这一点后,我能够找到导致程序不久后退出的逻辑错误。谢谢大家的帮助