如何读取try-catch块之外的变量

时间:2018-03-13 10:36:42

标签: java android

我需要读取JsonArray的第二个值,但我无法读取它。

  public void onViewBind(View view, Cursor cursor, ODataRow row) {
    OControls.setText(view, R.id.name, row.getString("name"));
    OControls.setText(view, R.id.email, row.getString("message"));
    JSONArray partner_id = null;
    try {
        partner_id = new JSONArray(row.getString("student_id"));
        String name = partner_id.getString(1);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    OControls.setText(view, R.id.company_name,name);
  }

如何从try块外部访问变量name

3 个答案:

答案 0 :(得分:0)

String name块之外声明您的 try-catch 变量,如下面的代码

示例代码

 public void onViewBind(View view, Cursor cursor, ODataRow row) {
    OControls.setText(view, R.id.name, row.getString("name"));
    OControls.setText(view, R.id.email, row.getString("message"));
    JSONArray partner_id = null;
    String name ="";
    try {
        partner_id = new JSONArray(row.getString("student_id"));
        name = partner_id.getString(1);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    OControls.setText(view, R.id.company_name,name);
  }

或者这个

 public void onViewBind(View view, Cursor cursor, ODataRow row) {
        OControls.setText(view, R.id.name, row.getString("name"));
        OControls.setText(view, R.id.email, row.getString("message"));
        JSONArray partner_id = null;
        String name ="";
        try {
            partner_id = new JSONArray(row.getString("student_id"));
            String name = partner_id.getString(1);
            OControls.setText(view, R.id.company_name,name);
        } catch (JSONException e) {
            e.printStackTrace();
        }

      }

答案 1 :(得分:0)

在try catch block之外声明名称

        public void onViewBind(View view, Cursor cursor, ODataRow row) {
        OControls.setText(view, R.id.name, row.getString("name"));
        OControls.setText(view, R.id.email, row.getString("message"));
                JSONArray partner_id = null;
                String name=""; 
          try {


                partner_id = new JSONArray(
                        row.getString("student_id"));
               name = partner_id.getString(1);

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


        OControls.setText(view, R.id.company_name,name);

希望有帮助

答案 2 :(得分:0)

将引发以下错误:

W/System.err: org.json.JSONException: Value 6 of type java.lang.Integer cannot be converted to JSONArray

6将替换为示例中的另一个整数

不要使用JSonArray try-catch使用student_id来获取学生记录,而是使用它来获取您需要的任何属性:

// Check first if "student_id" is available
if(!row.getString("student_id").equals("false")) {
    Student student_obj = new Student(getContext(), null);
    ODataRow student = student_obj.browse(row.getInt("student_id"));

    // Here you can get any student attribute from student record.
}

当你可以使用编程来避免try-catch这样做,因为它更好。