获取json数据时关闭活动

时间:2015-12-06 15:40:20

标签: android json

我正在创建这个Android应用程序,它获取一些数据,然后在特定间隔后显示通知。但每当我运行它,它就会关闭。这是我正在使用的代码。它从之前的活动中获取了一些数据。

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)

2 个答案:

答案 0 :(得分:0)

使用Asynctask进行网络通话。 excpetion显而易见。网络调用是在UI线程上进行的,不应该执行

答案 1 :(得分:0)

错误意味着您正在尝试在主线程或UI线程中执行一些与网络相关的操作。

尝试这样做的问题是,如果网络需要很长时间才能响应,那么UI将被冻结,因此用户体验会很糟糕。

为了避免这种情况,Android希望您在UI线程之外执行任何与UI无关的操作。在这种情况下,你应该创建一个像另一个答案中建议的AsyncTask,然后将所有与网络相关的代码放在那里。

然后你可以在UI线程中启动这个AsynTask,如果网络超时或响应缓慢,UI将继续工作。

基本上,AsyncTask将创建一个通过doInBackground()方法执行代码的新线程。然后是as per the documentation

  

onPostExecute(Result),在后台后的UI线程上调用   计算结束。背景计算的结果是   作为参数传递给此步骤

因此,您可以从AyncTask获取信息,然后在UI中执行某些操作。