将jsonData插入SQLite数据库的异常

时间:2018-02-27 19:16:38

标签: java android json nullpointerexception android-sqlite

如何将json解析数据插入sqiteDB?我是一个初学者,我已经尝试了所有这些工作,引用了每篇文章,但当我试图将数据插入SQLite时,我得到一个空指针异常。有一些我想念但我无法找到的东西。需要帮助

这是MainActivity.java

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    SQLiteDatabase sqLiteDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SqliteDBHelper dbHelper = new SqliteDBHelper(this);


        Log.d(TAG, "onCreate: Async started");
        GetJsonData getJsonData = new GetJsonData();
        getJsonData.execute("URL_HERE");
        Log.d(TAG, "onCreate: done");


    }
}

GetJsonData.java  {

public class GetJsonData extends AsyncTask<String, Void, String > {

    Context context;
    SqliteDBHelper helper = new SqliteDBHelper(context);
    private static final String TAG = "GetJsonData";

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.d(TAG, "onPostExecute: parameter is " + s );
    }

    @Override
    protected String doInBackground(String... strings) {
        Log.d(TAG, "doInBackground: starts");
        String result = onDownloadComplete(strings[0]);
        if(result == null){
            Log.e(TAG, "doInBackground: Error in downloading" );
        }else
        {
            try{
                JSONObject jsonObject = new JSONObject(result);
                JSONArray jsonArray = jsonObject.getJSONArray("messages");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonMessageObject = jsonArray.getJSONObject(i);

                    String message = jsonMessageObject.getString("message");
                    String role = jsonMessageObject.getString("role");
                    String timestamp = jsonMessageObject.getString("timestamp");



                    //*************Error on this line*******************
                    //its givng me a null pointer Exception
                    helper.insertData(message,role,timestamp); 



                }

            }catch (JSONException e){
                e.printStackTrace();
            }
        }
        return result;
    }

    public String onDownloadComplete(String data) {
        HttpURLConnection httpURLConnection = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(data);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            InputStream stream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line+"\n");
                Log.d(TAG, "Data: " + line); //data
            }
            return stringBuffer.toString();

        } catch (MalformedURLException e ) {
            e.printStackTrace();
        } catch (IOException e ) {
            e.printStackTrace();
        } catch (SecurityException e ){
            e.printStackTrace();
        }
        return null;
    }
}

}

SqliteDBHelper.java

public class SqliteDBHelper extends SQLiteOpenHelper {
    private static final String TAG = "SqliteDBHelper";

    public SqliteDBHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

        public static final String DATABASE_NAME = "chat.db";
        public static final int DATABASE_VERSION = 1;
    public static final String CREATE_QUERY = "CREATE TABLE INFO ( message TEXT, role TEXT, timestamp TEXT );";
    public static final String DROP_TABLE = "DROP TABLE INFO IF EXISTS";

        @Override
        public void onCreate(SQLiteDatabase db) {
            try{
                db.execSQL(CREATE_QUERY);                  
            }catch (SQLException e){
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int i, int i1) {
            try{
                db.execSQL(DROP_TABLE);
                onCreate(db);
            }catch (SQLException e){
                e.printStackTrace();
            }
        }

        public void insertData(String messageData, String roleData, String timestampData){
            SQLiteDatabase sqLiteDatabase =  this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put("message",messageData);
            cv.put("role",roleData);
            cv.put("timestamp",timestampData);
            long res = sqLiteDatabase.insert("INFO",null,cv);
        }
    }

空指针异常

 FATAL EXCEPTION: AsyncTask #1
 Process: com.poilkar.nehank.chatapplication, PID: 8054
 java.lang.RuntimeException: An error occurred while executing doInBackground()
 at android.os.AsyncTask$3.done(AsyncTask.java:318)
 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:243)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
 at java.lang.Thread.run(Thread.java:761)

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
 at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
 at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
 at com.poilkar.nehank.chatapplication.SqliteDBHelper.insertData(SqliteDBHelper.java:59)
 at com.poilkar.nehank.chatapplication.GetJsonData.doInBackground(GetJsonData.java:58)
 at com.poilkar.nehank.chatapplication.GetJsonData.doInBackground(GetJsonData.java:25)

 at android.os.AsyncTask$2.call(AsyncTask.java:304)
 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
 at java.lang.Thread.run(Thread.java:761)

1 个答案:

答案 0 :(得分:0)

 public class GetJsonData extends AsyncTask<String, Void, String > {

     Context context;
     SqliteDBHelper helper = new SqliteDBHelper(context);

此处传递给context构造函数的SqliteDBHelper为null。您需要传入有效的Context