如果JSON为空,Android应用程序崩溃

时间:2018-04-04 04:32:46

标签: android json listview

我正在开发一个JSON对象的应用程序,它将数据返回到ListView中。 如果json有数据然后在listview中显示数据..如果没有日期则应用程序崩溃。当json为空时,我的应用程序崩溃。如何解决此问题。来自于advancce

这里是android代码..

public class EmployeePaymentHistory extends Fragment {
    HttpParse httpParse = new HttpParse();
    ProgressDialog pDialog;
    ListView CategoryListView;
    ProgressBar progressBar;

    List<String> IdList = new ArrayList<>();
    private String TAG = EmployeePaymentHistory.class.getSimpleName();
    // Http Url For Filter Student Data from Id Sent from previous activity.


    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    String ParseResult ;
    HashMap<String,String> ResultHash = new HashMap<>();
    String FinalJSonObject ;

    String TempItem;

    ProgressDialog progressDialog2;

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

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




        CategoryListView = (ListView)view.findViewById(R.id.listview1);

        progressBar = (ProgressBar)view.findViewById(R.id.progressBar);

        //Receiving the ListView Clicked item value send by previous activity.
        TempItem =  getActivity().getIntent().getExtras().getString("ListViewValue1");


        //Calling method to filter Student Record and open selected record.
        HttpWebCall(TempItem);



        // Add Click listener on Delete button.

        return  view;
    }

    // Method to Delete Student Record



    //Method to show current record Current Selected Record
    public void HttpWebCall(final String PreviousListViewClickedItem){

        class HttpWebCallFunction extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                pDialog.dismiss();

                //Storing Complete JSon Object into String Variable.
                FinalJSonObject = httpResponseMsg ;

                //Parsing the Stored JSOn String to GetHttpResponse Method.
                new EmployeePaymentHistory.GetHttpResponse(getActivity()).execute();


            }

            @Override
            protected String doInBackground(String... params) {

                ResultHash.put("CustomerID",params[0]);

                ParseResult = httpParse.postRequest(ResultHash, api.EmployeePayment);

                return ParseResult;
            }
        }

        HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

        httpWebCallFunction.execute(PreviousListViewClickedItem);
    }


    // Parsing Complete JSON Object.
    private class GetHttpResponse extends AsyncTask<Void, Void, Void>
    {
        public Context context;


        List<Customer> CategoryList;

        public GetHttpResponse(Context context)
        {
            this.context = context;
        }

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

        @Override
        protected Void doInBackground(Void... arg0)
        {
            try
            {
                if(FinalJSonObject != null)
                {
                    JSONArray jsonArray = null;

                    try {
                        jsonArray = new JSONArray(FinalJSonObject);
                        JSONObject jsonObject;
                        Customer category;
                        CategoryList = new ArrayList<Customer>();
                        for(int i=0; i<jsonArray.length(); i++)
                        {
                            category = new Customer();

                            jsonObject = jsonArray.getJSONObject(i);
                            category.CustomerName = jsonObject.getString("date").toString();
                            category.Customertotal = jsonObject.getString("account").toString();
                            category.CustomerPaid = jsonObject.getString("total").toString();
                            category.CustomerUnPaid = jsonObject.getString("status").toString();

                            CategoryList.add(category);

                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

 else
                    {
                        Toast.makeText(context, "abcc", Toast.LENGTH_SHORT).show();
                    }


            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            progressBar.setVisibility(View.GONE);

            CategoryListView.setVisibility(View.VISIBLE);

            CustomerListAdapterClass adapter = new CustomerListAdapterClass(CategoryList, context);

            CategoryListView.setAdapter(adapter);

        }
    }


}

这里是php Api代码:

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

include 'DatabaseConfig.php';

 $CustomerID= $_POST['CustomerID'];

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {

 die("Connection failed: " . $conn->connect_error);
}

$sql = "sELECT b.payerid,a.account as account,b.date as date,b.status as status,b.type as type,sum(b.amount) as total FROM crm_employees a left JOIN sys_transactions b ON a.id = b.payerid where payerid= '$CustomerID' group by b.date ORDER BY a.id desc" ;



$result = $conn->query($sql);

if ($result->num_rows >0) {


 while($row[] = $result->fetch_assoc()) {

 $tem = $row;

 $json = json_encode($tem);

 }

} else {
 echo "No Results Found.";
}

 echo $json;

$conn->close();
}
?>

1 个答案:

答案 0 :(得分:-1)

您需要提供与在android端解析相同的响应输出。如果你试图找到一个没有响应的密钥名称的Json对象,那么它将崩溃。

在这种情况下,您需要手动处理,您认为它将为null或为空的值,然后使用普通的if语句处理。

假设var sentence = "F"; var sentence2 = "F"; var sentence3 = "X"; var rules = []; rules[0] = { a: "F", b: "F[+F]F[-F]F" } var rulesB = []; rulesB[0] = { a: "F", b: "FF-[-F+F+F]+[+F-F-F]" } /* var rulesC = []; rulesC[0] = { a: "F", b: "FF" } rulesC[1] = { a: "X", b: "F-[[X]+X]+F[+FX]-X" } */ var x = 50; // starting x var y = 400; // starting y var y_stack = []; // save & restore don't handle coordinates var y_stack2 = [] draw(); function turtle(sentence, context){ for (var i = 0; i < sentence.length; i++) { var current = sentence.charAt(i); if (current == "F") { y -= 20; context.lineTo(x, y); context.stroke(); } else if (current == "+") { context.translate(x, y); context.rotate((20 * Math.PI) / 180); context.translate(-x, -y); } else if (current == "-") { context.translate(x, y); context.rotate((-20 * Math.PI) / 180); context.translate(-x, -y); } else if (current == "[") { context.save(); y_stack.push(y); } else if (current == "]") { context.restore(); y = y_stack.pop(); context.moveTo(x, y) } } } function generate(sentence){ var nextSentence = ""; for (var i = 0; i < sentence.length; i++) { var current = sentence.charAt(i); var found = false; for (var j = 0; j < rules.length; j++ ) { if (current == rules[j].a) { found = true; nextSentence += rules[j].b; break; } } if (!found) { nextSentence += current; } } return nextSentence; } function turtle2(sentence2, context){ for (var i = 0; i < sentence2.length; i++) { var current = sentence2.charAt(i); if (current == "F") { y -= 20; context.lineTo(x, y); context.stroke(); } else if (current == "+") { context.translate(x, y); context.rotate((22.5 * Math.PI) / 180); context.translate(-x, -y); } else if (current == "-") { context.translate(x, y); context.rotate((-22.5 * Math.PI) / 180); context.translate(-x, -y); } else if (current == "[") { context.save(); y_stack2.push(y); } else if (current == "]") { context.restore(); y = y_stack2.pop(); context.moveTo(x, y) } } } function generate2(sentence2){ var nextsentence2 = ""; for (var i = 0; i < sentence2.length; i++) { var current = sentence2.charAt(i); var found = false; for (var j = 0; j < rulesB.length; j++ ) { if (current == rulesB[j].a) { found = true; nextsentence2 += rulesB[j].b; break; } } if (!found) { nextsentence2 += current; } } return nextsentence2; } function draw() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext('2d'); // context.moveTo(x, y); for (i = 0; i < 2; i++) { sentence = generate(sentence); } console.log(sentence); turtle(sentence, context); //context.moveTo(100,400); for(i = 0; i < 2; i++) { sentence2 = generate2(sentence2); } console.log(sentence2); turtle2(sentence2, context); } /* function turtle3(){ //resetMatrix(); context.translate(width/6, height); for (var n = 0; n < sentence3.length; n++){ var current = sentence3.charAt(n); if (current == "F"){ context.stroke("#28b232"); context.lineTo(0, -len3); context.translate(0, -len3); }else if (current == "X"){ context.stroke("#024d08"); context.lineTo(-len3, 0); context.translate(0, -len3); }else if (current == "+"){ context.rotate(angle2); }else if (current == "-"){ context.rotate(-angle2); }else if (current == "["){ save(); }else if (current == "]"){ restore(); } } } */ /* function generate3(){ len2 *= .5; var nextSentence3 = ""; for (var i = 0; i < sentence3.length; i++){ var current3 = sentence3.charAt(i); var found3 = false; for (var j = 0; j < rulesC.length; j++ ){ if (current3 == rulesC[j].a){ found3 = true; nextSentence3 += rulesC[j].b; break; } } if (!found3){ nextSentence3 += current3; } } sentence3 = nextSentence3; turtle3(); }*/ 对象不是fount,那么使用你可以处理的if语句。

jsonObject.getString("date")