打开数据库时出现NullPointerException

时间:2014-06-22 21:18:11

标签: java android nullpointerexception android-sqlite

我不清楚为什么会发生 NullPointerException 。我想知道它是否与我在不同线程中访问数据库的事实有关?我注意到我能够从 MainActivity 打开数据库(.getWritableDatabase)而没有任何问题,但我尝试从另一个类访问它无法正常工作。我用"活动"扩展了课程。为了使用" Context。"那是对的吗?谢谢你的任何建议。

执行以下命令时,FetchXML.java文件中发生错误:

SQLiteDatabase db = dbTools.getWritableDatabase();

错误:

W/System.err﹕ java.lang.NullPointerException
W/System.err﹕ at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:256)
W/System.err﹕ at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
W/System.err﹕ at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
W/System.err﹕ at com.digitalalias.dndandroid.rss.FetchXML.parseXMLAndStoreIt(FetchXML.java:151)
W/System.err﹕ at com.digitalalias.dndandroid.rss.FetchXML$Fetch.doInBackground(FetchXML.java:79)
W/System.err﹕ at com.digitalalias.dndandroid.rss.FetchXML$Fetch.doInBackground(FetchXML.java:57)
W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err﹕ at java.lang.Thread.run(Thread.java:841)

FetchXML.java

public class FetchXML extends Activity {
    private static final String TAG = "dnda";

    private String urlString = null;
    private XmlPullParserFactory xmlFactoryObject;
    private XmlPullParser myparser;
    private DatabaseTools dbTools;
    private Post post;
    private List<Post> posts;
    private ContentValues values;

    /**
     * constructor
     * @param url
     */
    public FetchXML(String url) {
        this.urlString = url;
        posts = new ArrayList<Post>();
    }

    /**
     * Starts the new thread to download/parse XML
     */
    public void grabXml() {
        new Fetch().execute();
    }

    /**
     * fetch the XML file from the URL
     */
    public class Fetch extends AsyncTask<Void, Void, XmlPullParser> {
        @Override
        protected XmlPullParser doInBackground(Void... params) {
            try {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);

                // Starts the query
                conn.connect();
                InputStream stream = conn.getInputStream();

                xmlFactoryObject = XmlPullParserFactory.newInstance();
                xmlFactoryObject.setNamespaceAware(true);

                myparser = xmlFactoryObject.newPullParser();
//                myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                myparser.setInput(stream, null);

                parseXMLAndStoreIt(myparser);
                stream.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return myparser;
        }

        protected void onPostExecute(XmlPullParser result) {
        }
    }

    /**
     * parseXMLAndStoreIt
     * @param myParser
     */
    public void parseXMLAndStoreIt(XmlPullParser myParser) {
        int eventType;
        boolean item = false;   // used to indicate if the parser is within an ITEM tag
        String tagText = "";


        try {
            eventType = myParser.getEventType();

            // loop through xml
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = myParser.getName();

                // gather specific tags
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if (tagName.equalsIgnoreCase("item")) {
                            item = true;
                            post = new Post(); // new instance of post object
                        }
                        break;
                    case XmlPullParser.TEXT:
                        tagText = myParser.getText();
                        break;
                    case XmlPullParser.END_TAG:
                        if (item) {
                            if (tagName.equalsIgnoreCase("item")) {
                                posts.add(post); // add post object to list
                            } else if (tagName.equalsIgnoreCase("title")) {
                                post.setTitle(tagText);
                            } else if (tagName.equalsIgnoreCase("link")) {
                                post.setLink(tagText);
                            } else if (tagName.equalsIgnoreCase("pubDate")) {
                                post.setPubDate(tagText);
                            } else if (tagName.equalsIgnoreCase("guid")) {
                                post.setGuid(tagText);
                            } else if (tagName.equalsIgnoreCase("description")) {
                                post.setDescription(tagText);
                            }
                        }
                        break;
                }

                eventType = myParser.next();
            }

            // process list of posts
            if (!posts.isEmpty()) {
                values = new ContentValues();
                dbTools = new DatabaseTools(FetchXML.this);
                SQLiteDatabase db = dbTools.getWritableDatabase();

                // insert posts into database
                for (Post key : posts) {
                    values.put(dbTools.COLUMN_TITLE, key.getTitle());
                    values.put(dbTools.COLUMN_LINK, key.getLink());
                    values.put(dbTools.COLUMN_PUBDATE, key.getPubDate());
                    values.put(dbTools.COLUMN_GUID, key.getGuid());
                    values.put(dbTools.COLUMN_DESCRIPTION, key.getDescription());

                    db.insert(dbTools.DATABASE_TABLE, null, values);
                }

                db.close();
                dbTools.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}

1 个答案:

答案 0 :(得分:0)

您有class FetchXML extends Activity并且您可能使用new对其进行实例化。永远不要使用new实例化活动。它们不能以Context的方式使用。

相反,将有效的Context作为参数传递到需要的位置,或者如果您确实需要实例化某个活动,请使用Intent