0
    package com.example.hstnc_activity;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.JsonReader;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class DisplayServiceActivity extends ListActivity {
    private ListView listOfServices;

    //JSONArrays?
    JSONArray directory = null; 

    //JSON Node names
    private static String TAG_ID = "id";
    private static String TAG_NAME= "name";
    private static String TAG_DIRECTORY = "Categories";
    private final static String url;    
    JSONObject json;
    jsonParser jParser = new jsonParser();

    @SuppressLint("NewApi")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Request().onPostExecute(url);

        listOfServices =getListView(); //get builtin listView


        ArrayList<HashMap<String, String>> directoryList = new ArrayList<HashMap<String, String>>();

        // Intent intent = getIntent();
        //String url = intent.getStringExtra("SERVICES_DIRECTORY");


        try{
            //getting Array
            directory = json.getJSONArray(TAG_DIRECTORY);

            for(int i= 0; i<directory.length(); i++){
                JSONObject addItem =directory.getJSONObject(i);

                //store each item in variable 
                String id = addItem.getString(TAG_ID);
                String name= addItem.getString(TAG_NAME);

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

                //add each child node to HashMap key
                map.put(TAG_ID, id);
                map.put(TAG_NAME, name);

                //adding HashList to ArrarList
                directoryList.add(map);
            }

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

        ListAdapter adapter = new SimpleAdapter(this,
                directoryList, 
                R.layout.list_item, 
                new String[] { TAG_ID,TAG_NAME }, 
                new int[] { android.R.id.text1,android.R.id.text2 });

        setListAdapter(adapter);
        setContentView(R.layout.service);
        // Make sure we're running on Honeycomb or higher to use ActionBar APIs
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Show the Up button in the action bar.
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }// end of onCreate Method
    @SuppressWarnings("unused")
    public class Request extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... params) {
            json = jParser.getJSONfromURL(url);
            return null;
        }
         protected void onPostExecute(String url) {
             json = jParser.getJSONfromURL(url);
         }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

我很想在 Android 中执行 JSON 请求并获取信息并将其放入列表视图中。我在调试时不断收到“HTTP 连接 android.os.NetworkOnMainThreadException 错误”作为错误。运行 apk 时,它只是在我打开此活动时强制关闭。此活动通过另一个屏幕上的按钮启动。

4

2 回答 2

2

为什么在json = jParser.getJSONfromURL(url)这个onPostExecute()?我假设你只是忘了删除它,因为你也有它doInBackground()应该在的地方

把它移出那里,因为你正在onPostExecute()运行UI ThreadNetworkOnMainThreadException

我没有注意到在UI做网络的东西上运行的任何东西,但如果有的话,把它移到doInBackground()

此外,您不应该直接调用onPostExecute()或任何其他AsyncTask方法。你需要用类似的东西来做

Request = new Request();  // can send parameters to constructor if needed
request.execute();   // execute doInBackground()-- you can pass your url param in here for doInBackground to receive but you have to change the class declaration so that the first param takes a url

AsyncTask 文档

于 2013-05-12T02:57:13.010 回答
1

从您的代码中删除代码onPostExecute(),它会运行良好。

附加更正: -onPostExecute()永远不会收到调用的参数(String url),因为您正在返回 null doInBackground,其他原因是您将 AsyncTask 参数设置为<Void, Void, Void>这意味着 AsyncTask 不会接收任何参数,并且不会从 doInBackground 返回任何内容到 onPostExecute。

onPostExecute()应该看起来像这样: -

@Override
protected void onPostExecute(Void v) {          
    super.onPostExecute(v);
}

希望它会有所帮助。

于 2013-05-12T03:04:29.707 回答