【问题标题】:Listfragment and Asynctask errorListfragment 和 Asynctask 错误
【发布时间】:2014-01-07 22:00:37
【问题描述】:

我的 AsyncTask 类有问题,我无法在列表视图中打印 php 结果。谁能给我一个解决方案?为什么 OnPostExecute 出错?

FragmentTab1

public class FragmentTab1 extends ListFragment {
ArrayList<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
ListViewAdapter adapter;
private static final String TAG="nombre";
private Context context;
private ArrayAdapter<String> arrayAdapter;
static String imagen = "imagen";
static String nombre = "nombre";
static String total = "total";
static String empresa = "empresa";
static String precionuevo = "precionuevo";
static String precioantiguo = "precioantiguo";
static String direccion = "direccion";
static String telefono = "telefono";
static String unidades = "unidades";
static String codeqr = "codeqr";
static String longitud = "longitud";
static String latitud = "latitud";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // normally you should inflate a view here and save references
    // using ListFragment default layout for this example
    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onStart() {
    super.onStart();
    new FetchFactTask().execute();
}

private class FetchFactTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>>{

    @Override
    protected void onPreExecute() {
        // Any code to execute before fetching the data
    }

    @Override
    protected  ArrayList<HashMap<String, String>> doInBackground(String... params) {

        // Create an array
        ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://");

        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("productos");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("imagen", jsonobject.getString("imagen"));
                map.put("nombre", jsonobject.getString("nombre"));
                map.put("total", jsonobject.getString("total"));
                map.put("empresa", jsonobject.getString("empresa"));
                map.put("unidades", jsonobject.getString("unidades"));
                map.put("precionuevo", jsonobject.getString("precionuevo")+" €");
                map.put("precioantiguo", jsonobject.getString("precioantiguo")+" €");
                map.put("descripcion", jsonobject.getString("descripcion"));
                map.put("direccion", jsonobject.getString("direccion"));
                map.put("telefono", jsonobject.getString("telefono"));
                map.put("latitud", jsonobject.getString("latitud"));
                map.put("longitud", jsonobject.getString("longitud"));
                map.put("codeqr", jsonobject.getString("codeqr"));
                // Set the JSON Objects into the array

                arraylist.add(map);

            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            //e.printStackTrace();
        }
        return arraylist;
    }

    protected void onPostExecute(ArrayList<HashMap<String, String>> args) {
        //Use that args to populate the listview            
        for(int i=0;i<args.size();i++) {
            Log.i("onPostExecute ->", args.get(i).get("nombre"));
            Toast.makeText(getActivity(), args.get(i).get("nombre"), Toast.LENGTH_SHORT).show();
        }
        // Pass the results into ListViewAdapter.java
                    //adapter = new ListViewAdapter(getActivity(), arraylist);


            /*ListAdapter adapter=new SimpleAdapter(context, 
                            arraylist,
                            R.layout.fragmenttab1, new String[]{ TAG }, 
                            new int[]{R.id.list});

                    setListAdapter(adapter);    */
        ListView productList = (ListView) getActivity().findViewById(R.id.list);

        adapter = new ListViewAdapter(getActivity(), args);
        // Set the adapter to the ListView
        productList.setAdapter(adapter);




    }
}
}

** ListViewAdapter **

public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();

public ListViewAdapter(Context context,
        ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView nombre;
    TextView empresa;
    TextView precionuevo;
    TextView precioantiguo;
    ImageView imagen;
    TextView unidades;
    TextView codeqr;
    TextView latitud;
    TextView longitud;
    TextView telefono;
    TextView direccion;
    //TextView pcnt;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.listview_item, parent, false);
    // Get the position
    resultp = data.get(position);

    // Locate the TextViews in listview_item.xml
    precionuevo = (TextView) itemView.findViewById(R.id.precionuevo);
    empresa = (TextView) itemView.findViewById(R.id.empresa);
    nombre = (TextView) itemView.findViewById(R.id.nombre);
    unidades = (TextView) itemView.findViewById(R.id.unidades);
    precioantiguo = (TextView) itemView.findViewById(R.id.antiguo);
    codeqr = (TextView) itemView.findViewById(R.id.codeqr);
    latitud = (TextView) itemView.findViewById(R.id.latitud);
    longitud = (TextView) itemView.findViewById(R.id.longitud);
    telefono = (TextView) itemView.findViewById(R.id.telefono);
    direccion = (TextView) itemView.findViewById(R.id.direccion);
    // Locate the ImageView in listview_item.xml
    imagen = (ImageView) itemView.findViewById(R.id.dealimage);
    //pcnt = (TextView) itemView.findViewById(R.id.pcnt);

    // Capture position and set results to the TextViews
    nombre.setText(resultp.get(FragmentTab1.nombre));
    empresa.setText(resultp.get(FragmentTab1.empresa));
    precionuevo.setText(resultp.get(FragmentTab1.precionuevo));
    unidades.setText(resultp.get(FragmentTab1.unidades));
    precioantiguo.setText(resultp.get(FragmentTab1.precioantiguo));
    codeqr.setText(resultp.get(FragmentTab1.codeqr));
    latitud.setText(resultp.get(FragmentTab1.latitud));
    longitud.setText(resultp.get(FragmentTab1.longitud));
    telefono.setText(resultp.get(FragmentTab1.telefono));
    direccion.setText(resultp.get(FragmentTab1.direccion));
    //pcnt.setText(precioantiguo*100/precionuevo);
    //antiguo * 100 / precionuevo





    // Capture position and set results to the ImageView
    // Passes flag images URL into ImageLoader.class
    imageLoader.DisplayImage(resultp.get(FragmentTab1.imagen), imagen);
    // Capture ListView item click
    precioantiguo.setPaintFlags(precioantiguo.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Get the position
            resultp = data.get(position);
            Intent intent = new Intent(context, FragmentTab1.class);
            // Pass all data rank
            intent.putExtra("nombre", resultp.get(FragmentTab1.nombre));
            intent.putExtra("empresa", resultp.get(FragmentTab1.empresa));
            intent.putExtra("total", resultp.get(FragmentTab1.total));
            intent.putExtra("precionuevo", resultp.get(FragmentTab1.precionuevo));
            intent.putExtra("precioantiguo", resultp.get(FragmentTab1.precioantiguo));
            intent.putExtra("unidades", resultp.get(FragmentTab1.unidades));
            intent.putExtra("direccion", resultp.get(FragmentTab1.direccion));
            intent.putExtra("telefono", resultp.get(FragmentTab1.telefono));
            intent.putExtra("codeqr",resultp.get(FragmentTab1.codeqr));
            intent.putExtra("latitud",resultp.get(FragmentTab1.latitud));
            intent.putExtra("longitud",resultp.get(FragmentTab1.longitud));
            intent.putExtra("imagen", resultp.get(FragmentTab1.imagen));
            context.startActivity(intent);
        }
    });
    return itemView;
}
}

Logcat 展示:

https://www.dropbox.com/s/2kruons9xd5x2ib/errorrrr.png?m=

【问题讨论】:

  • FragmentTab1 的第 145 行是什么?
  • @NathanWalters 第 145 行 -> productList.setAdapter(adapter);

标签: php android android-asynctask


【解决方案1】:

因为您使用的是ListFragment,所以以下行不起作用:

ListView productList = (ListView) getActivity().findViewById(R.id.list);
adapter = new ListViewAdapter(getActivity(), args);
// Set the adapter to the ListView
productList.setAdapter(adapter);

第一行导致 NPE,因为 Activity 不包含 ID 为 R.id.list 的 ListView;该列表在您的ListFragment 中。您应该将代码更改为:

adapter = new ListViewAdapter(getActivity(), args)
getListView().setAdapter(adapter);

【讨论】:

  • 谢谢!已更改,不再显示任何错误,但不打印列表 :(
  • 这是您应用程序中的实际代码行吗?如果是,这将无济于事,因为它不是有效的网址jsonobject = JSONfunctions.getJSONfromURL("http://");
  • 在那一行中,我的网址正确,并祝酒 "Toast.makeText(getActivity(), args.get(i).get("nombre"), Toast.LENGTH_SHORT).show() ;"正确显示结果但不打印列表
  • 请发布托管此 Fragment 的 Activity 的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多