SetListAdapter仅在调试模式

时间:2015-08-06 19:49:47

标签: android listview android-asynctask

我正在开发一个应用程序,它(在AsyncTask中)执行查询到远程服务器获取JSON字符串。 为了在我的ListView上显示数据,我扩展了一个ArrayAdapter。

当我执行我的应用程序时,从LogCat我可以看到数据被正确检索但未在ListView中显示。

我必须使一切正常(并且数据显示在ListView上)的唯一方法是在调试模式下运行应用程序,在行上设置断点

myListView setAdapter myAdapter );

等待几秒钟然后恢复申请。 完成此过程后,一切正常。

为什么会这样?

AsyncTask是否适合进行如此长时间的操作,或者我应该使用其他方法(但我不知道哪一种方法!)。

这是MainActivity代码

public class MainActivityFragment extends Fragment {

private List<Station> stationList = new ArrayList<Station>();
private StationAdapter stationsAdapter;
private ProgressDialog pd;
private String LOG_TAG = "ProvaAsyncTask";

public MainActivityFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    mioAsync mioTask = new mioAsync();
    mioTask.execute();


    stationsAdapter = new StationAdapter(stationList, getActivity());

    ListView stationsListView = (ListView) rootView.findViewById(R.id.miaListView);

    stationsListView.setAdapter(stationsAdapter);

    return rootView;
}


public class mioAsync extends AsyncTask<Void, Void, Void> {

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

        // Creo la ProgressDialog che precede il caricamento dei dati
        pd = new ProgressDialog(getActivity());
        pd.setMessage(MainActivityFragment.this.getString(R.string.preloader_stations_list));
        pd.show();
    }


    @Override
    protected Void doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        String forecastJsonStr = null;

        try {

            URL url = new URL("*remoteserver*");

            // Create the request to the server, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {                    
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();

        } catch (IOException e) {
            Log.e(LOG_TAG, "Error ", e);                
            return null;
        } finally{
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }

        try{
            getStationsListFromJson(forecastJsonStr);

        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            e.printStackTrace();
        }

        return null;

    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        pd.dismiss();
    }


    private void getStationsListFromJson(String stationsJsonStr) throws JSONException {

        JSONArray stationsArray = new JSONArray(stationsJsonStr);

        String nomeStaz;
        String numSat;

        stationList.clear();
        for (int i = 0; i < stationsArray.length(); i++) {
            JSONObject j = stationsArray.optJSONObject(i);
            Iterator it = j.keys();

            while (it.hasNext()) {
                String n = it.next().toString();
                numSat = j.getString(n) + " stazioni";
                n = it.next().toString();
                nomeStaz = j.getString(n);
                stationList.add(new Station(nomeStaz, numSat));
            }
        }

    }

}
}

我得到的JSON字符串就像这样

[{"nome":"Station1","satelliti":"11"},{"nome":"Station2","satelliti":"9"},{"nome":"Station3","satelliti":"8"}]

这是我扩展ArrayList

的地方
public class StationAdapter extends ArrayAdapter<Station> {

private List<Station> stationsList;
private Context context;

public StationAdapter(List<Station> lista, Context cont){
    super(cont, R.layout.listitems, lista);
    this.stationsList = lista;
    this.context = cont;
}

public int getCount() {
    return stationsList.size();
}

public Station getItem(int position) {
    return stationsList.get(position);
}

public long getItemId(int position) {
    return stationsList.get(position).hashCode();
}

public View getView(int position, View convertView, ViewGroup parent){
    View v = convertView;

    StationHolder holder = new StationHolder();

    // controllo che il convertview non sia null
    if (convertView == null){

        // This a new view we inflate the new layout
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.listitems, null);

        // Now we can fill the layout with the right values
        TextView stationName = (TextView) v.findViewById(R.id.testataUno);
        TextView satellitesNumber = (TextView) v.findViewById(R.id.testataDue);

        holder.stationNameView = stationName;
        holder.satellitesNumberView = satellitesNumber;

        v.setTag(holder);



    } else {
        holder = (StationHolder) v.getTag();
    }

    Station p = stationsList.get(position);
    holder.stationNameView.setText(p.getName());
    holder.satellitesNumberView.setText("" + p.getSatellites());

    return v;
}


/* *********************************
 * We use the holder pattern
 * It makes the view faster and avoid finding the component
 * **********************************/

private static class StationHolder {
    public TextView stationNameView;
    public TextView satellitesNumberView;
}

}

这是电台代码

public class Station {

private String name;
private String satellites;

public Station(String nome, String satelliti){
    this.name = nome;
    this.satellites = satelliti;
}

public String getName(){
    return this.name;
}

public String getSatellites(){
    return this.satellites;
}

public void setName(String nome){
    this.name = nome;
}

public void setSatellites(String satelliti){
    this.satellites = satelliti;
}

}

1 个答案:

答案 0 :(得分:2)

你的流量被打破了。它只能在调试模式下工作,因为你在断点上停止执行UI线程,但在你的断点之前排除了你的AsyncTask,并且由于没有停止,它会在你喜欢你的断点时下载数据。你很可能认为AsyncTask(它是异步任务的缩写)是......好......同步。不是。你的主要代码不会等待asynctask,它会启动并继续。您需要重新编写代码,并在asynctask的onPostExecute()方法中根据下载的内容更新数据集,然后在列表的适配器上调用notifyDatasetChanged()。这应该触发列表刷新。