2016-01-23 231 views
1

嗨,我需要保存json數據在sqlite中。但Iam得到以下錯誤。將json數據保存到sqlite中

無法在未調用的線程內創建處理程序 Looper.prepare()。

這是我的代碼。據shwoing數據庫打開/數據庫中創建...

/** 
    * Async task class to get json by making HTTP call 
    * */ 
    private class GetDetails extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

    @SuppressLint("NewApi") 
    @Override 
    protected Void doInBackground(Void... arg0) { 
     // Creating service handler class instance 
     ServiceHandler sh = new ServiceHandler(); 

     // Create an array to populate the spinner 
     branchlist = new ArrayList<String>(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

//  System.out.println("response"+jsonStr); 

     if (jsonStr != null) { 

      try { 
       // jsonString is a string variable that holds the JSON 
       JSONArray itemArray=new JSONArray(jsonStr); 
       for (int i = 0; i < itemArray.length(); i++) { 
        value=itemArray.getString(i); 
        Log.e("json", i+"="+value); 

        dbhelper=new DataBaseHepler(getApplicationContext()); 
        sqLiteDatabase=dbhelper.getWritableDatabase(); 
        dbhelper.addinnformation(value,sqLiteDatabase); 
        Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show(); 
        dbhelper.close(); 

        branchlist.add(itemArray.getString(i)); 

       } 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 

     ArrayAdapter<String> stringadapter = new ArrayAdapter<String>(MainActivity.this, 
       android.R.layout.simple_spinner_dropdown_item, 
       branchlist); 

     spinner1.setAdapter(stringadapter); 

//  spinner1 
//  .setAdapter(new ArrayAdapter<String>(MainActivity.this, 
//    android.R.layout.simple_spinner_dropdown_item, 
//    branchlist)); 
    } 

} 
+0

在後臺直接發送Toast消息是不可能的。應該使用runonuithread。這是因爲doinbackground在後臺線程 – Stallion

回答

0

這個錯誤是由於ToastdoInBackground(Void... arg0)方法:

Toast.makeText(getBaseContext(),"Data saved",Toast.LENGTH_LONG).show(); 

顯然,Android操作系統不會讓比主線程改變UI元素的其他線程。請點擊以下鏈接瞭解更多詳情:https://dzone.com/articles/android-%E2%80%93-multithreading-ui

+0

謝謝。我已經做到了這一點.... –