【问题标题】:Set the JSON Data in TextView?在 TextView 中设置 JSON 数据?
【发布时间】:2017-03-16 10:22:18
【问题描述】:

我能够获取JSON 数据,但无法在TextView 中设置值。当我将数据设置为显示空指针异常

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

我的模型课

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,但无法解决问题?

【问题讨论】:

  • 你有没有正确初始化table_data1
  • 检查您的 table_data1 是否为空?
  • table_data1 = (TextView) view.findViewById(R.id.student_profile_fee_description); table_data2 = (TextView) view.findViewById(R.id.student_profile_fee_amount);
  • 我认为你没有初始化`table_data1`。你初始化了吗?
  • 是的先生。我已正确初始化它

标签: android json


【解决方案1】:

如果不这样做,你是否初始化了 table_data1

TextView table_data1 = (TextView ) findViewById(R.id.yourTextViewId);

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

【讨论】:

    【解决方案2】:
    • 你可以通过写日志来检查这个TextView table_data1是否为空。

      Log.e("TestTAG", "table_data1=="+table_data1)

    • 如果它正在打印 null 然后在调用 WebService 之前检查它是否已初始化,如果你做的一切都正确然后检查从哪里找到 table_data1 的 id 的视图是否包含这个TextView

    编辑

    检查你的布局 student_fees_listview 有这个 TextView student_profile_fee_description 如果不是,那么你就是inflating 布局错误。

    【讨论】:

    • student_profile_fee_description 在 Fragment_fee 布局上。 student_fees_listview 是 ListView 人
    • 这正是问题所在。你在这里膨胀了错误的布局View view = inflater.inflate(R.layout.student_fees_listview, container, false);如果使用的TextView不在膨胀的布局中,那么它肯定会抛出NullpointerException,因为android无法在给定的布局上找到这个TextView
    • 我有 listView ,它应该由 JSON 填充,在我使用 TableLayout 的 LIST Items 上。我该怎么做?
    • 这意味着将有 2 个类和 2 个布局,而这些布局彼此不匹配。
    【解决方案3】:

    使用http://www.jsonschema2pojo.org/ 创建一个响应类 之后创建类的对象,然后通过调用 get 方法,您可以分别获取每个值。然后你可以在任何你想要的地方使用它。希望它可以帮助你。只需访问上面的链接并粘贴您的 json,您就会知道如何继续。正确序列化您的响应数据。

    【讨论】:

      【解决方案4】:

      试试这个:

      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");
      }
      

      【讨论】:

      • @Suman 您在 for 循环中设置了值 .. 所以只有最后一个值设置为 textview ...如果上面的代码不起作用,那么将您的 findviewbyid 发布为 table_data1 代码
      • 它显示空值。这是执行 Log.d("TAG","table_data1 null");
      • 空值或空指针异常?
      • 空值。我已经添加了布局。请检查
      • 金额 = jsonObjectinner.getInt("金额");将字符串更改为 int ,检查日志中的 Amount.Set 值 table_data1.setText(Amount+"");
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      相关资源
      最近更新 更多