在TextView中设置JSON数据?

时间:2017-03-16 10:22:19

标签: android json

我可以获取JSON数据,但无法在TextView中设置值。我正在设置数据显示空指针异常。< / p>

getUsersListData()

public class Fee extends Fragment /*implements View.OnClickListener   */ {

    LinearLayout receipt1, receipt2, receipt3, receipt4;
    LinearLayout receipt1detail, receipt2detail, receipt3detail, receipt4detail;


    TextView statustextView;
    ListView listViewfees, listviewfeedetail;
    List<StudentFeeInformation> yourData = new ArrayList<StudentFeeInformation>();
    public static final String Navigation_URL = "http://192.168.100.5:84/Api/financeApi/getAllFees";

    String master_id;
    TableLayout tableLayout;
    TextView table_data1, table_data2;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.student_fees_listview, container, false);


        setHasOptionsMenu(true);
        receipt1 = (LinearLayout) view.findViewById(R.id.linear_receipt1_fee);

        //  receipt4 = (LinearLayout) view.findViewById(R.id.linear_receipt4_fee);

        //  receipt1detail = (LinearLayout) view.findViewById(R.id.receipt1_fee);
        //  receipt2detail = (LinearLayout) view.findViewById(R.id.receipt2_fee);
        //  receipt3detail = (LinearLayout) view.findViewById(R.id.receipt3_fee);
        //  receipt4detail = (LinearLayout) view.findViewById(R.id.receipt4_fee);

        //   receipt1.setOnClickListener(this);
        //   receipt2.setOnClickListener(this);
        //   receipt3.setOnClickListener(this);
        //   receipt4.setOnClickListener(this);


        //   receipt1detail.setVisibility(View.VISIBLE);
        //   receipt2detail.setVisibility(View.GONE);
        //   receipt3detail.setVisibility(View.GONE);
        //   receipt4detail.setVisibility(View.GONE);

        statustextView = (TextView) view.findViewById(R.id.student_profile_fee_status);
        SessionManagement sessionManagement = new SessionManagement(getContext());
        master_id = sessionManagement.getMasterId();
        listViewfees = (ListView) view.findViewById(R.id.list_student_fees);
        tableLayout = (TableLayout) view.findViewById(R.id.simpleTableLayout);

        table_data1 = (TextView) view.findViewById(R.id.student_profile_fee_description);
        table_data2 = (TextView) view.findViewById(R.id.student_profile_fee_amount);

        getUsersListData();

        return view;
    }


    private void getUsersListData() {


        String URL = Navigation_URL + "?id=" + master_id;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            String Descriptionlist;
                            String Amount = null;
                            ArrayList<StudentFeeInformation> student_list = new ArrayList<>();
                            ArrayList<StudentFeeInformation> student_list_description = new ArrayList<>();

                            JSONArray jArray = new JSONArray(response);
                            //  studentFeeInformation = new StudentFeeInformation(response);
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONObject jsonObject = jArray.getJSONObject(i);

                                String status = jsonObject.getString("Status");
                                String DateofReceiptIssued = jsonObject.getString("DateOfReciept").substring(0, 10);
                                String ReceiptNumber = jsonObject.getString("RecieptNo");
                                String FeeReceivedDate = jsonObject.getString("recivedDate").substring(0, 10);

                                String Description = jsonObject.getString("Description");
                                JSONArray jArray1 = new JSONArray(Description);

                                for (int j = 0; j < jArray1.length(); j++) {
                                    JSONObject jsonObjectinner = jArray1.getJSONObject(j);

                                    Descriptionlist = jsonObjectinner.getString("des");
                                    Amount = jsonObjectinner.getString("Amount");
                                    table_data1.setText(Amount); // its Showing the Null pointer exception


                                    System.out.println(Descriptionlist);
                                    System.out.println(Amount);


                                }
                                student_list.add(new StudentFeeInformation(status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate));

                            }
                            System.out.println("student_list size:" + student_list.size());
                            CustomFeeListStudentAdapter customFeeListStudentAdapter = new CustomFeeListStudentAdapter(getActivity(), student_list);

                            listViewfees.setAdapter(customFeeListStudentAdapter);


                        } catch (JSONException e) {

                            System.out.println("This is not good");

                            e.printStackTrace();

                        }

                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // Toast.makeText(view.Fee.this, error.toString(), Toast.LENGTH_LONG).show();

            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                return headers;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);


    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

我的MOdel课程

public class StudentFeeInformation implements Serializable {
    public String Status;
    public String ReceiptIssuedDate;
    public String ReceiptIssuedNumber;
    public String FeeReceivedDate;
    public String FeeDescription;
    public String Amount;


    public StudentFeeInformation(String status, String ReceiptissuedDate, String ReceiptissuedNumber, String FeereceivedDate, String amount) {
        Status = status;
        ReceiptIssuedDate = ReceiptissuedDate;
        ReceiptIssuedNumber = ReceiptissuedNumber;
        FeeReceivedDate = FeereceivedDate;
        Amount = amount;


    }

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }

    public String getReceiptIssuedDate() {
        return ReceiptIssuedDate;
    }

    public void setReceiptIssuedDate(String receiptIssuedDate) {
        ReceiptIssuedDate = receiptIssuedDate;
    }

    public String getReceiptIssuedNumber() {
        return ReceiptIssuedNumber;
    }

    public void setReceiptIssuedNumber(String receiptIssuedNumber) {
        ReceiptIssuedNumber = receiptIssuedNumber;
    }

    public String getFeeReceivedDate() {
        return FeeReceivedDate;
    }

    public void setFeeReceivedDate(String feeReceivedDate) {
        FeeReceivedDate = feeReceivedDate;
    }


    public String getFeeDescription() {
        return FeeDescription;
    }

    public void setFeeDescription(String feeDescription) {
        FeeDescription = feeDescription;
    }


    public String getAmount() {
        return Amount;
    }

    public void setAmount(String amount) {
        Amount = amount;
    }


}

我的JSON

[
  {
    "MasterID": "E0017",
    "StdID": 111,
    "Status": "U",
    "AmountPaid": 6645,
    "Class": 8,
    "DateOfReciept": "2017-01-01T00:00:00",
    "Description": "[{\"des\":\"Admission\",\"Amount\":300},{\"des\":\"Monthly Fee\",\"Amount\":5400},{\"des\":\"Exam Fee\",\"Amount\":200},{\"des\":\"Extra Charge\",\"Amount\":400},{\"des\":\"Late Charge\",\"Amount\":345}]",
    "RecieptNo": 1011,
    "NAME": "Uzumaki Naruto",
    "recivedDate": "2017-03-10T00:00:00",
    "reciever": "Cynthia Irwin"
  },
  {
    "MasterID": "E0017",
    "StdID": 111,
    "Status": "U",
    "AmountPaid": 5600,
    "Class": 8,
    "DateOfReciept": "2017-03-01T00:00:00",
    "Description": "[{\"des\":\"Exam Fee\",\"Amount\":200},{\"des\":\"Monthly Fee\",\"Amount\":5400}]",
    "RecieptNo": 1012,
    "NAME": "Uzumaki Naruto",
    "recivedDate": "2017-03-06T00:00:00",
    "reciever": "Cynthia Irwin"
  }
]

布局

 <TableLayout
                        android:id="@+id/simpleTableLayout"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:stretchColumns="1"> <!-- stretch the second column of the layout-->


                        <TableRow

                            android:id="@+id/firstRow"
                            android:layout_width="fill_parent"
                            android:layout_height="wrap_content">


                            <TextView

                                android:id="@+id/student_profile_fee_description"
                                android:layout_width="0dp"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:gravity="left|center"
                                android:paddingLeft="70dp"
                                android:paddingTop="5dp"
                                android:text="Sports"
                                android:textSize="12sp" />

                            <TextView

                                android:id="@+id/student_profile_fee_amount"
                                android:layout_width="0dp"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:gravity="left|center"
                                android:paddingLeft="70dp"
                                android:paddingTop="5dp"
                                android:text="Sports"
                                android:textSize="12sp" />

                        </TableRow>
                    </TableLayout>

logcat 设置外部循环

  3-16 16:31:01.037 9722-9722/com.example.user.mis W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: DescriptionlistAdmission
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: Amount300
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: table_data1 null
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: DescriptionlistMonthly Fee
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: Amount5400
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: table_data1 null
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: DescriptionlistExam Fee
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: Amount200
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: table_data1 null
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: DescriptionlistExtra Charge
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: Amount400
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: table_data1 null
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: DescriptionlistLate Charge
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: Amount345
03-16 16:31:03.032 9722-9722/com.example.user.mis D/TAG: table_data1 null
03-16 16:31:03.033 9722-9722/com.example.user.mis D/AndroidRuntime: Shutting down VM
03-16 16:31:03.033 9722-9722/com.example.user.mis E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.example.user.mis, PID: 9722
                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                        at com.example.user.mis.fragment.Fee$1.onResponse(Fee.java:175)
                                                                        at com.example.user.mis.fragment.Fee$1.onResponse(Fee.java:130)
                                                                        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                                                                        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                                                                        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
  

我知道Value为null,但无法解决问题?

4 个答案:

答案 0 :(得分:0)

如果不执行此操作,您是否初始化了table_data1

{{Item}}

如果这样做已经发布了您的完整代码:)

答案 1 :(得分:0)

  • 您可以通过编写日志来检查TextView table_data1是否为空。

    Log.e(&#34; TestTAG&#34;,&#34; table_data1 ==&#34; + table_data1)

  • 如果打印为null,则在调用 WebService 之前检查它是否已初始化,如果您正在执行所有操作,请检查您查找table_data1的id的视图是否包含此{{1是不是?

修改

检查您的布局TextView是否有此TextView student_fees_listview 如果没有,那么你student_profile_fee_description布局错误。

答案 2 :(得分:0)

试试这个:

int Amount = jsonObjectinner.getInt("Amount");
Log.d("TAG","Descriptionlist"+Descriptionlist);
Log.d("TAG","Amount"+Amount);

if(table_data1!=null)
{
    Log.d("TAG","table_data1 not null");
    table_data1.setText(Amount+""); 
}
else
{
    Log.d("TAG","table_data1 null");
}

答案 3 :(得分:0)

使用http://www.jsonschema2pojo.org/创建回复课程 之后,通过调用get方法创建类的对象,您可以单独获取每个值。然后您可以随时随地使用它。希望它能帮到你。只需访问上面的链接并粘贴您的json,您就会知道如何继续。正确序列化您的响应数据。