在将数据填充到listview时获取空指针异常

时间:2015-09-03 12:11:13

标签: android

请仔细阅读以下代码并帮助我。来自url的数据正在被解析,但我无法填入列表视图。

public class HomeFragment extends Fragment {
View rootView = null;
private ListView myListView;
private String[] strListView;
private String[] categ;
private TextView catName;
private CustomAdapter myAdapter;
private  DownloadJson downloadJson;

private  int i;
private AsyncTask task;
private Thread thread;
public HomeFragment()
{

}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
     rootView = inflater.inflate(R.layout.fragment_home, container, false);
    myListView = (ListView) rootView.findViewById(R.id.listview);

   new DownloadJson().execute();


    // Inflate the layout for this fragment
    return rootView;
}

这是callCustomAdapter功能:

public void callCustomAdaper( Context context)
{
    myAdapter = new CustomAdapter(context);
    myListView.setAdapter(myAdapter);
    myListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.v("Module Item Trigger", "Module item was triggerted");


          /*  Fragment customMapFragmentMapFragment = new MessagesFragment();

            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            fragmentManager.beginTransaction()

                    .replace(R.id.container, customMapFragmentMapFragment)
                    .addToBackStack(null)
                    .commit();*/
        }
    });
}

这个类是json解析器:

 class DownloadJson extends AsyncTask {

    Activity context;
    ListView myListView;

    private  ProgressDialog dialog = new ProgressDialog(getActivity());
    public DownloadJson(Activity context, ListView myListView) {
        this.myListView = myListView;
        this.context = context;

    }

    public DownloadJson() {

    }


    @Override
    protected void onPreExecute() {

        this.dialog.setMessage("Please wait");
        this.dialog.show();
    }


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

    @Override
    protected Object doInBackground(Object[] params) {
        String result = null;
        InputStream isr = null;
        String imageId = null;
        String ip = "http://ganarajsshetti.tk/mobileapp/selectjson.php/";
        try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(ip);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            isr = httpEntity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http Connection" + e.toString());

        }
        // converting response to string
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(isr));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            isr.close();
            result = sb.toString();

        } catch (Exception e) {
            Log.e("log_tag", "Error in Converting Data" + e.toString());
        }

        // parse JSON data

        try {

            JSONArray jsonArray = new JSONArray(result);
            strListView = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
               JSONArray json_data = jsonArray.getJSONArray(i);
                for (int j =0; j< json_data.length();j++) {

                    strListView[i] = json_data.getString(j);

                    System.out.println("--------------" + json_data.getString(0));

                }
                Log.e("ACK_tag", "DATA" + strListView[i]);
            }

        } catch (Exception e) {
            Log.e("log_tag", "Error in parsing Data" + e.toString());
        }

        return null;

    }

    @Override
    protected void onPostExecute(Object o) {
    // ArrayAdapter objAdapter = new ArrayAdapter<String>(context,R.layout.list_item,R.id.Category,strListView);
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        callCustomAdaper(context);
    }
}

这是扩展基本适配器的customAdapter

public class CustomAdapter extends BaseAdapter {
    private Context context;


    public CustomAdapter(Context context) {
        this.context = context;

    }

    @Override
    public int getCount() {
        return strListView.length;
    }

    @Override
    public Object getItem(int i) {
        return strListView[i];
    }

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

    @Override
    public View getView(int i, View convertview, ViewGroup viewGroup) {
        View row= null;

        if(convertview == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.list_item, viewGroup, false);
        }
        else{
            row= convertview;

        }
        catName=(TextView) row.findViewById(R.id.Category);
        catName.setText(categ[i]);
        return row;
    }
    public  String[] getValues()
    {
        return strListView;
    }
}

这些是我的Xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="info.androidhive.materialdesign.activity.HomeFragment">

<ListView
    android:id="@+id/listview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
   </ListView>

</RelativeLayout>

这是其他xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">

    <TextView
        android:id="@+id/Category"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:gravity="center_horizontal"

        android:textStyle="bold"/>



</LinearLayout>

这就是我得到的错误:

  

java.lang.NullPointerException:尝试调用虚方法&#39; java.lang.Object android.content.Context.getSystemService(java.lang.String)&#39;在null对象引用上               在info.androidhive.materialdesign.activity.HomeFragment $ CustomAdapter.getView(HomeFragment.java:248)

2 个答案:

答案 0 :(得分:0)

您正在使用错误的构造函数(空的)创建DownloadJson

答案 1 :(得分:0)

您的上下文传递给适配器时出现问题。在您的片段中,您正在调用new DownloadJson().execute();因此您不会向AsyncTask发送上下文,因此无法将其发送到适配器。您应该使用另一个构造函数new DownloadJson(getActivity(), myListView).execute();

还有一件事你不应该将Activity保存为上下文。当您不需要时,您正在泄漏活动将其保留在内存中。在AsyncTask中使用private Context context;,并将此上下文设为getActivity().getApplicationContext();