AsyncTask测试连接

时间:2017-01-30 19:37:11

标签: java android android-fragments android-asynctask

我试图使用AsyncTask它在设备有互联网连接的情况下工作,但是当我打开没有互联网的情况时出现此消息"不幸的是,已停止",按照代码,我是什么做错了?有人可以解释一下吗?

PS:我有一个Activity,我在Fragment中使用AsyncTask。

使用AsyncTask的片段。

public class MasonFragment extends Fragment {

private ListView lstMason;
private ProgressDialog dialog;

//private Fragment fragmentMain = new MainFragment();

public MasonFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_mason, container, false);

    lstMason = (ListView)view.findViewById(R.id.lstMason);

    // Create default options which will be used for every
    // displayImage(...) call if no options will be passed to this method
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
            .defaultDisplayImageOptions(defaultOptions).build();
    ImageLoader.getInstance().init(config); // Do it on Application start
    //To that class work need this: compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' in gradle module

    new JSONTask().execute("https://deliveryteste.000webhostapp.com/production_version_1/json_services_v1.txt");

    return view;

}

/*private View.OnClickListener requestJSON = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        new JSONTask().execute("My_URL");

    }
};*/

public class JSONTask extends AsyncTask<String, String, List<Services>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<Services> doInBackground(String... params) {

        if(new CheckNetwork(getActivity()).isNetworkAvailable()) {

            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();

                String line = "";
                while ((line = reader.readLine()) != null) {

                    buffer.append(line);

                }

                String finalJson = buffer.toString();

                JSONObject jsonObject = new JSONObject(finalJson);

                JSONArray jsonArray = jsonObject.getJSONArray("mason");

                List<Services> servicesList = new ArrayList<>();


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

                    JSONObject finalObject = jsonArray.getJSONObject(i);

                    Services services = new Services();

                    services.setName(finalObject.getString("name"));
                    services.setTelephone(finalObject.getString("telephone"));
                    services.setCity(finalObject.getString("city"));
                    services.setDescription(finalObject.getString("description"));
                    services.setRating((float) finalObject.getDouble("rate"));
                    services.setImage(finalObject.getString("image"));
                    services.setFacebook(finalObject.getString("facebook"));

                    servicesList.add(services);

                }


                return servicesList;

            } catch (MalformedURLException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            } catch (JSONException e) {

                e.printStackTrace();
                //backToMain();

            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {

                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {

            Toast.makeText(getActivity(), "Por favor esteja conectado com a rede!", Toast.LENGTH_LONG).show();

        }

        return null;
    }

    @Override
    protected void onPostExecute(List<Services> result) {
        super.onPostExecute(result);
        ServicesAdapter servicesAdapter = new ServicesAdapter(getActivity(), R.layout.custom_listview, result);
        lstMason.setAdapter(servicesAdapter);
    }
}

//Class to CustomArrayAdapter
public class ServicesAdapter extends ArrayAdapter {

    private List<Services> servicesList;
    private int resource;
    private LayoutInflater inflater;
    public ServicesAdapter(Context context, int resource, List<Services> objects) {
        super(context, resource, objects);
        servicesList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);

    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView == null){

            convertView = inflater.inflate(resource, null);

        }

        ImageView imgPerson;
        TextView lblName;
        TextView lblTelephone;
        TextView lblDescription;
        TextView lblFacebookResult;
        TextView lblCity;
        RatingBar rtgServiceRating;

        imgPerson = (ImageView)convertView.findViewById(R.id.imgPerson);
        lblName = (TextView)convertView.findViewById(R.id.lblName);
        lblTelephone = (TextView)convertView.findViewById(R.id.lblTelephone);
        lblCity = (TextView)convertView.findViewById(R.id.lblCity);
        lblDescription = (TextView)convertView.findViewById(R.id.lblDescription);
        lblFacebookResult = (TextView)convertView.findViewById(R.id.lblFacebookResult);
        rtgServiceRating = (RatingBar)convertView.findViewById(R.id.rtgSerciveRating);

        // Then later, when you want to display image
        ImageLoader.getInstance().displayImage(servicesList.get(position).getImage(), imgPerson); // Default options will be used

        lblName.setText(servicesList.get(position).getName());
        lblTelephone.setText(String.valueOf(servicesList.get(position).getTelephone()));
        lblDescription.setText(servicesList.get(position).getDescription());
        lblFacebookResult.setText(servicesList.get(position).getFacebook());
        lblCity.setText(servicesList.get(position).getCity());

        //Rating Bar
        rtgServiceRating.setRating(servicesList.get(position).getRating());

        StringBuffer stringBuffer = new StringBuffer();

        return convertView;
    }
}

/*private void backToMain(){

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.lnlContentMain, fragmentMain).commit();

}*/

检查网络连接的类:

public class CheckNetwork {

private Context context;

public CheckNetwork(Context context) {
    this.context = context;
}

public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

错误日志:

01-30 17:30:13.886 6868-7284/com.archtech.gabrielgomes.hirehere E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                              Process: com.archtech.gabrielgomes.hirehere, PID: 6868
                                                                              java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                  at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                                                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                                  at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                                  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                  at java.lang.Thread.run(Thread.java:841)
                                                                               Caused by: java.lang.SecurityException: ConnectivityService: Neither user 10204 nor current process has android.permission.ACCESS_NETWORK_STATE.
                                                                                  at android.os.Parcel.readException(Parcel.java:1472)
                                                                                  at android.os.Parcel.readException(Parcel.java:1426)
                                                                                  at android.net.IConnectivityManager$Stub$Proxy.getActiveNetworkInfo(IConnectivityManager.java:1139)
                                                                                  at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:690)
                                                                                  at com.archtech.gabrielgomes.hirehere.CheckNetwork.isNetworkAvailable(CheckNetwork.java:21)
                                                                                  at com.archtech.gabrielgomes.hirehere.fragments.MasonFragment$JSONTask.doInBackground(MasonFragment.java:100)
                                                                                  at com.archtech.gabrielgomes.hirehere.fragments.MasonFragment$JSONTask.doInBackground(MasonFragment.java:90)
                                                                                  at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                                                  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                                  at java.lang.Thread.run(Thread.java:841) 

谢谢你们。

1 个答案:

答案 0 :(得分:1)

如错误所述,public class Program { public static void checkIfEqualOption1(int[] arr){ int sumRight = 0; int sumLeft=0; int arrayLength=arr.length; for (int posFromLeft=0; posFromLeft < arrayLength; posFromLeft++){ int posFromRight=arrayLength-posFromLeft-1; if (posFromRight > posFromLeft){ sumRight+=arr[posFromRight]; sumLeft+=arr[posFromLeft]; } } System.out.println("right sum: "+sumRight); System.out.println("left sum: "+sumLeft); } public static void main(String[] args) { int[] numbers = {1,2,2,9,3}; System.out.println("Array numbers:"); for (int i=0; i < numbers.length; i++){ System.out.print(numbers[i] + " "); } checkIfEqualOption1(numbers); } }

要解决此问题,只需将java.lang.SecurityException: ConnectivityService: Neither user 10204 nor current process has android.permission.ACCESS_NETWORK_STATE添加到<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />文件

即可