2015-12-06 46 views
1

我正在創建這個android應用程序,它獲取一些數據,然後在特定時間間隔後顯示通知。但是每當我運行它時,它就會關閉。這裏是我使用的代碼。它從以前的活動中獲取一些數據。當獲取json數據時關閉活動

package com.example.boschcarservice; 



import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Random; 

import org.apache.http.NameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.AlarmManager; 
import android.app.ListActivity; 
import android.app.PendingIntent; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.telephony.SmsManager; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 
    private ProgressDialog pDialog; 
    JSONParser jParser = new JSONParser(); 
    ArrayList<HashMap<String, String>> productsList; 
    private static String url_all_products = "http://bosch-car-mohali.com/home/boschcar/android_connect/get_product_details.php"; 

    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_PRODUCTS = "products"; 
    private String TAG_PID = null; 
    JSONArray products = null; 
    TextView t1,t2,t3; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     t1= (TextView) findViewById(R.id.textView4); 
     t2= (TextView) findViewById(R.id.textView5); 
     t3= (TextView) findViewById(R.id.textView7); 
     Bundle extras = getIntent().getExtras(); 
     TAG_PID=extras.getString("pid"); 
     productsList = new ArrayList<HashMap<String, String>>(); 

     // Loading products in Background Thread 
     new LoadAllProducts().execute(); 

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
     Calendar calendar = Calendar.getInstance(); 
     String dt= t3.getText().toString(); 
     try { 
      calendar.setTime(sdf.parse(dt)); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Intent myIntent = new Intent(this, MyReciever.class); 
     PendingIntent pi= PendingIntent.getBroadcast(this, 0, myIntent,0); 

     AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),10*24*60*60*1000, pi); 
    } 

    class LoadAllProducts extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Loading products. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 
     /** 
     * getting All products from url 
     * */ 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      // getting JSON string from URL 
      JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); 

      // Check your log cat for JSON reponse 
      Log.d("All Products: ", json.toString()); 

      try { 
       // Checking for SUCCESS TAG 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // products found 
        // Getting Array of Products 
        products = json.getJSONArray(TAG_PRODUCTS); 

        // looping through All Products 
        for (int i = 0; i < products.length(); i++) { 
         JSONObject c = products.getJSONObject(i); 

         // Storing each json item in variable 
         String pid = c.getString(TAG_PID); 

         // creating new HashMap 
         HashMap<String, String> map = new HashMap<String, String>(); 

         // adding each child node to HashMap key => value 
         map.put(TAG_PID, pid); 

         // adding HashList to ArrayList 
         productsList.add(map); 
        } 
       } else { 

        Toast.makeText(getApplicationContext(), "Connection Error",Toast.LENGTH_LONG).show(); 


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

      return null; 
     } 

     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after getting all products 
      pDialog.dismiss(); 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        t1.setText(productsList.get(1).toString()); 
        t2.setText(productsList.get(3).toString()); 
        String dt = t1.getText().toString(); // Start date 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
        Calendar c = Calendar.getInstance(); 
        try { 

         c.setTime(sdf.parse(dt)); 

        } catch (ParseException e) { 
         e.printStackTrace(); 
        } 
        c.add(Calendar.DATE, 15); // number of days to add, can also use Calendar.DAY_OF_MONTH in place of Calendar.DATE 
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); 
        t3.setText(sdf1.format(c.getTime()).toString()); 

       } 
      }); 


     } 

    } 



    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 


} 

編輯: 這裏有日誌

12-06 16:30:57.947: E/AndroidRuntime(827): FATAL EXCEPTION: main 
12-06 16:30:57.947: E/AndroidRuntime(827): android.os.NetworkOnMainThreadException 
12-06 16:30:57.947: E/AndroidRuntime(827): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 
12-06 16:30:57.947: E/AndroidRuntime(827): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 
12-06 16:30:57.947: E/AndroidRuntime(827): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
12-06 16:30:57.947: E/AndroidRuntime(827): at java.net.InetAddress.getAllByName(InetAddress.java:214) 
12-06 16:30:57.947: E/AndroidRuntime(827): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 
12-06 16:30:57.947: E/AndroidRuntime(827): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
12-06 16:30:57.947: E/AndroidRuntime(827): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
12-06 16:30:57.947: E/AndroidRuntime(827): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
12-06 16:30:57.947: E/AndroidRuntime(827): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
12-06 16:30:57.947: E/AndroidRuntime(827): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
12-06 16:30:57.947: E/AndroidRuntime(827): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
12-06 16:30:57.947: E/AndroidRuntime(827): at com.example.boschcarservice.JSONParser.makeHttpRequest(JSONParser.java:61) 
12-06 16:30:57.947: E/AndroidRuntime(827): at com.example.boschcarservice.gpass$1.run(gpass.java:78) 
12-06 16:30:57.947: E/AndroidRuntime(827): at android.os.Handler.handleCallback(Handler.java:725) 
12-06 16:30:57.947: E/AndroidRuntime(827): at android.os.Handler.dispatchMessage(Handler.java:92) 
12-06 16:30:57.947: E/AndroidRuntime(827): at android.os.Looper.loop(Looper.java:137) 
12-06 16:30:57.947: E/AndroidRuntime(827): at android.app.ActivityThread.main(ActivityThread.java:5039) 
12-06 16:30:57.947: E/AndroidRuntime(827): at java.lang.reflect.Method.invokeNative(Native Method) 
12-06 16:30:57.947: E/AndroidRuntime(827): at java.lang.reflect.Method.invoke(Method.java:511) 
12-06 16:30:57.947: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
12-06 16:30:57.947: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
12-06 16:30:57.947: E/AndroidRuntime(827): at dalvik.system.NativeStart.main(Native Method) 
+1

它是否崩潰。如果是的話請粘貼日誌 –

+0

添加logcat文件 –

回答

0

該錯誤意味着您正在嘗試在主線程或UI線程中執行一些與網絡相關的內容。

試圖做到這一點的問題是,如果網絡需要很長時間才能響應,UI將被凍結,因此這將是一個糟糕的用戶體驗。

爲了避免這種情況,Android希望您在UI線程外執行任何與UI無關的操作。在這種情況下,您應該像創建另一個答案一樣創建一個AsyncTask,然後將所有與網絡相關的代碼放在那裏。

然後,您可以在UI線程中啓動此AsynTask,並且如果網絡發生超時或緩慢響應,UI將繼續工作。

基本上,AsyncTask將創建一個新的線程,通過doInBackground()方法執行您的代碼。然後as per the documentation

onPostExecute(結果),調用UI線程在後臺 計算完成後。背景計算的結果是 傳遞到這步作爲一個參數

就這樣你可以得到的信息從AyncTask回來,然後做在UI的東西。

+0

感謝解釋人。 –

0

使用Asynctask讓網絡通話。 excpetion顯然是明顯的。網絡調用是在UI線程上進行的,它不應該執行

+0

的副本,所以我需要做的工作我在後臺線程在主要?抱歉,我無法理解你。這是我第一次使用json。你能解釋一下使用函數的名字嗎? –

相關問題