尝试使用 json parsingin android 将数据从服务器添加到 listView 时出现 NULL 指针异常

Getting NULL pointer exception when trying to add data from server to listView using json parsingin android

我正在尝试从 php 获取数据并希望将其放入简单的 listView 而不是 TextView。当我使用 TextView 数据显示时,但当我使用将数据放在 ListView 中时,我只是得到空指针异常。 请建议我并显示我的错误。 代码在这里:

    package cse.project.medical;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.annotation.TargetApi;
    import android.app.ActionBar;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.TextView;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public class Patient_biodata extends Activity {

    String pat_name, total_title;
    ListView listView;
    // TextView profile_show;
    Button update;
    ArrayAdapter<String > adapter;
    String[] arr;

    protected void onCreate(Bundle savedInstanceState) {
        Log.e("ni", "doc biodata has  started");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.patient_biodata);

        StrictMode.enableDefaults();
        ActionBar action_bar = getActionBar();

        Intent i = getIntent();
        // getting attached intent data
        pat_name = i.getStringExtra("person_name");
        total_title = "Hello...." + pat_name;
        action_bar.setTitle(total_title);

        // profile_show = (TextView) findViewById(R.id.show_profile);
        update = (Button) findViewById(R.id.update_btn);
        listView = (ListView) findViewById(R.id.listView2);
        get_all_information_of_a_user();
        update.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                alert_update_method();

            }
        });
    }

    protected void alert_update_method() {
        // TODO Auto-generated method stub

    }

    protected void get_all_information_of_a_user() {
        String result = "";
        InputStream isr = null;
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("pat_name", pat_name));

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://192.168.56.1/imp/JSON/json_pat_biodata.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
            Log.e("connection", "connection success");

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
            // profile_show.setText("Couldn't connect to database");
        }

        // convert response to string
        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    isr, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            isr.close();
            result = sb.toString();
            Log.e("connection", "convertion success");
            Log.e("result", result);
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        // parse json data
        try {
            //String s = "";
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {

                JSONObject json = jArray.getJSONObject(i);

                arr[0] = json.getString("p_name");
                arr[1] = json.getString("p_age");
                arr[2] = json.getString("p_gender");
                arr[3] = json.getString("p_address");
                arr[4] = json.getString("p_mobile");
                arr[5] = json.getString("p_email");
                arr[6] = json.getString("p_nationality");
                arr[7] = json.getString("p_username");

            }
            Log.e("before", "adapter");
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    Patient_biodata.this, android.R.layout.simple_list_item_1,
                    arr);
            listView.setAdapter(adapter);
            Log.e("after", "adapter");
            // profile_show.setText(s);
        } catch (Exception e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

    }

}

我的 XML 代码如下:

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

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp" >

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_weight="3"
                    android:text="Your Profile"
                    android:textSize="20sp"
                    android:textStyle="italic" />

                <Button
                    android:id="@+id/update_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                     android:layout_weight="1"
                    android:text="Update" />

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

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

</LinearLayout>

而php代码是:

<?php

    $host='localhost';
    $uname='root';
    $pwd='';
    $db="hospital";

    $con = mysql_connect($host,$uname,$pwd) or die("connection failed");
    mysql_select_db($db,$con) or die("db selection failed");
    $name = $_POST['pat_name'];

        $find_pat_id = "select p_name,p_age,p_gender,p_address,p_mobile,p_email,p_nationality,p_username from current_patient where p_username = '$name'";
    $p_id_run = mysql_query($find_pat_id);  

     if(mysql_num_rows($p_id_run)>0)
        {
            while($row=mysql_fetch_assoc($p_id_run))
                    {
                        $flag[]=$row;
                    }

             print(json_encode($flag));
        }

    mysql_close($con);

?>

看起来你的主要问题是你没有初始化你的 arr 数组,也就是说你从来没有 arr = new String[8]; 这可能是你的 NPE 的原因。

但是,您似乎只是从 JSON 结果中为您的适配器提供了一条记录。

您可能想要创建自定义适配器并为 simple_list_item_1.xml 中的每个项目创建一个 TextView。

但是,为了让您走上正轨,请先尝试以下操作:

// parse json data
        try {
            //String s = "";
            JSONArray jArray = new JSONArray(result);
            arr = new String[jArray.length()]; //initialize your array
            for (int i = 0; i < jArray.length(); i++) {

                JSONObject json = jArray.getJSONObject(i);

                StringBuffer buff = new StringBuffer();

                buff.append(json.getString("p_name") + " ");
                buff.append(json.getString("p_age") + " ");
                buff.append(json.getString("p_gender") + " ");
                buff.append(json.getString("p_address") + " ");
                buff.append(json.getString("p_mobile") + " ");
                buff.append(json.getString("p_email") + " ");
                buff.append(json.getString("p_nationality") + " ");
                buff.append(json.getString("p_username");

                arr[i] = buff.toString();

            }
            Log.e("before", "adapter");
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    Patient_biodata.this, android.R.layout.simple_list_item_1,
                    arr);
            listView.setAdapter(adapter);
            Log.e("after", "adapter");
            // profile_show.setText(s);
        } catch (Exception e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }