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

时间:2021-01-25 19:33:50

I am trying to fetch data from php & want to place it into a simple listView instead of TextView. When i use TextView data shows on but when I use to place data in ListView i simply get null pointer exception. please suggest me and show my error. code is here:

我试图从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());
        }

    }

}

And my XML code is like:

我的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>

And php code is:

而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);

?>

1 个解决方案

#1


0  

It looks like your main problem is that you're not initializing your arr array, i.e. you never do arr = new String[8]; That is probably the cause of your NPE.

看起来你的主要问题是你没有初始化你的arr数组,即你永远不会做arr = new String [8];这可能是您的NPE的原因。

However, it also looks like you're just giving your adapter one record from the JSON results.

但是,看起来您只是从JSON结果中为您的适配器提供一条记录。

You will probably want to create a custom adapter and create a TextView for each item in your simple_list_item_1.xml.

您可能希望创建自定义适配器并为simple_list_item_1.xml中的每个项创建TextView。

However, just to get you on the right track, try this first:

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

// 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());
        }

#1


0  

It looks like your main problem is that you're not initializing your arr array, i.e. you never do arr = new String[8]; That is probably the cause of your NPE.

看起来你的主要问题是你没有初始化你的arr数组,即你永远不会做arr = new String [8];这可能是您的NPE的原因。

However, it also looks like you're just giving your adapter one record from the JSON results.

但是,看起来您只是从JSON结果中为您的适配器提供一条记录。

You will probably want to create a custom adapter and create a TextView for each item in your simple_list_item_1.xml.

您可能希望创建自定义适配器并为simple_list_item_1.xml中的每个项创建TextView。

However, just to get you on the right track, try this first:

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

// 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());
        }