用于OnClick http请求的JSON解析器不起作用? Android的

时间:2014-03-04 09:08:56

标签: java android json

我不确定我需要在此问题上包含多少信息。我在下面复制了我的JSON编码,但是如果需要任何其他编码我可以提供它。此外,在出错时提供LogCat错误日志。

{
                super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            refresh = (Button) findViewById(R.id.button1);


            refresh.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view) 
              {
                 String result = null;
                InputStream is = null;

                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://www.jamiepaleschi.co.uk/android_login/selectall.php");
                        HttpResponse response = httpclient.execute(httppost); 
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
                     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                }
                catch(Exception e)
                {
                        Log.e("log_tag", "Error in http connection "+e.toString());
                        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                }
                //convert response to string
                try
                {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) 
                        {
                                sb.append(line + "\n");
                              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
                        }
                        is.close();

                        result=sb.toString();
                }
                catch(Exception e)
                {
                       Log.e("log_tag", "Error converting result "+e.toString());
                    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();

                }    
//parse json data
                    try
                {

                JSONArray jArray = new JSONArray(result);


                String re=jArray.getString(jArray.length()-1);


                TableLayout tv=(TableLayout) findViewById(R.id.table);
                tv.removeAllViewsInLayout();




                   int flag=1;

                for(int i=-1;i<jArray.length()-1;i++)

                        {




                                TableRow tr=new TableRow(Main.this);

                                tr.setLayoutParams(new LayoutParams(
                                           LayoutParams.WRAP_CONTENT,
                                           LayoutParams.WRAP_CONTENT));




                                if(flag==1)
                                {

                                    TextView b1=new TextView(Main.this);
                                     b1.setText("Mon");
                                     b1.setTextColor(Color.BLUE);
                                     b1.setTextSize(15);
                                     tr.addView(b1);


                                    TextView b19=new TextView(Main.this);
                                     b19.setPadding(10, 0, 0, 0);
                                     b19.setTextSize(15);
                                     b19.setText("Tue");
                                     b19.setTextColor(Color.BLUE);
                                     tr.addView(b19);

                                   TextView b29=new TextView(Main.this);
                                 b29.setPadding(10, 0, 0, 0);
                                     b29.setText("Wed");
                                     b29.setTextColor(Color.BLUE);
                                     b29.setTextSize(15);
                                     tr.addView(b29);

                                     TextView b39=new TextView(Main.this);
                                     b39.setPadding(10, 0, 0, 0);
                                         b39.setText("Thur");
                                         b39.setTextColor(Color.BLUE);
                                         b39.setTextSize(15);
                                         tr.addView(b39);

                                      TextView b49=new TextView(Main.this);
                                         b49.setPadding(10, 0, 0, 0);
                                             b49.setText("Fri");
                                             b49.setTextColor(Color.BLUE);
                                             b49.setTextSize(15);
                                             tr.addView(b49);


                                 tv.addView(tr);

                                     final View vline = new View(Main.this);
                                          vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, 2));
                                          vline.setBackgroundColor(Color.BLUE);



                                tv.addView(vline);
                                flag=0;


                                }

                                else
                                {



                                    JSONObject json_data = jArray.getJSONObject(i);

                                    Log.i("log_tag","Mon: "+json_data.getString("f1")+
                                              ", Tue: "+json_data.getString("f2")+
                                              ", Wed: "+json_data.getString("f3")+
                                              ", Thur: "+json_data.getString("f4")+
                                              ", Fri: "+json_data.getString("f5"));




                            TextView b=new TextView(Main.this);
                                String stime=String.valueOf(json_data.getString("f1"));
                                  b.setText(stime);
                                b.setTextColor(Color.RED);
                                b.setTextSize(10);
                                b.setWidth(60);
                                tr.addView(b);


                               TextView b1=new TextView(Main.this);
                                b1.setPadding(10, 0, 0, 0);
                                b1.setTextSize(10);
                                b1.setWidth(60);
                                String stime1=json_data.getString("f2");
                                 b1.setText(stime1);
                                b1.setTextColor(Color.WHITE);
                                tr.addView(b1);

                              TextView b2=new TextView(Main.this);
                             b2.setPadding(10, 0, 0, 0);
                                String stime2=String.valueOf(json_data.getString("f3"));
                                b2.setText(stime2);
                                b2.setTextColor(Color.RED);
                                b2.setTextSize(10);
                                b2.setWidth(60);
                                tr.addView(b2);

                                TextView b3=new TextView(Main.this);
                                b3.setPadding(10, 0, 0, 0);
                                   String stime3=String.valueOf(json_data.getString("f4"));
                                   b3.setText(stime3);
                                   b3.setTextColor(Color.WHITE);
                                   b3.setTextSize(10);
                                   b3.setWidth(60);
                                   tr.addView(b3);

                                 TextView b4=new TextView(Main.this);
                                   b4.setPadding(10, 0, 0, 0);
                                      String stime4=String.valueOf(json_data.getString("f5"));
                                      b4.setText(stime4);
                                      b4.setTextColor(Color.RED);
                                      b4.setTextSize(10);
                                      b4.setWidth(60);
                                      tr.addView(b4);

                                  tv.addView(tr);


                        final View vline1 = new View(Main.this);
                      vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, 1));
                      vline1.setBackgroundColor(Color.WHITE);
                      tv.addView(vline1);       


                                }

                       }



                }
                catch(JSONException e)
                {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }




           }
           });








    /**
     * Change Password Activity Started
     **/
    changepas.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0){

            Intent chgpass = new Intent(getApplicationContext(), ChangePassword.class);

            startActivity(chgpass);
        }

    });

   /**
    *Logout from the User Panel which clears the data in Sqlite database
    **/
    btnLogout.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {

            UserFunctions logout = new UserFunctions();
            logout.logoutUser(getApplicationContext());
            Intent login = new Intent(getApplicationContext(), Login.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            finish();
        }
    });

LogCat错误日志

    03-04 04:03:13.509: W/dalvikvm(797): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
03-04 04:03:13.530: E/AndroidRuntime(797): FATAL EXCEPTION: main
03-04 04:03:13.530: E/AndroidRuntime(797): java.lang.NullPointerException
03-04 04:03:13.530: E/AndroidRuntime(797):  at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
03-04 04:03:13.530: E/AndroidRuntime(797):  at org.json.JSONTokener.nextValue(JSONTokener.java:94)
03-04 04:03:13.530: E/AndroidRuntime(797):  at org.json.JSONArray.<init>(JSONArray.java:87)
03-04 04:03:13.530: E/AndroidRuntime(797):  at org.json.JSONArray.<init>(JSONArray.java:103)
03-04 04:03:13.530: E/AndroidRuntime(797):  at com.learn2crack.Main$1.onClick(Main.java:129)
03-04 04:03:13.530: E/AndroidRuntime(797):  at android.view.View.performClick(View.java:4240)
03-04 04:03:13.530: E/AndroidRuntime(797):  at android.view.View$PerformClick.run(View.java:17721)
03-04 04:03:13.530: E/AndroidRuntime(797):  at android.os.Handler.handleCallback(Handler.java:730)
03-04 04:03:13.530: E/AndroidRuntime(797):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-04 04:03:13.530: E/AndroidRuntime(797):  at android.os.Looper.loop(Looper.java:137)
03-04 04:03:13.530: E/AndroidRuntime(797):  at android.app.ActivityThread.main(ActivityThread.java:5103)
03-04 04:03:13.530: E/AndroidRuntime(797):  at java.lang.reflect.Method.invokeNative(Native Method)
03-04 04:03:13.530: E/AndroidRuntime(797):  at java.lang.reflect.Method.invoke(Method.java:525)
03-04 04:03:13.530: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-04 04:03:13.530: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-04 04:03:13.530: E/AndroidRuntime(797):  at dalvik.system.NativeStart.main(Native Method)

最新代码版本 main.java

public class Main extends Activity{
Button btnLogout;
Button changepas;
Button refresh;




/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    changepas = (Button) findViewById(R.id.btchangepass);
    btnLogout = (Button) findViewById(R.id.logout);
    refresh = (Button) findViewById(R.id.button1);

    DatabaseHandler db = new DatabaseHandler(getApplicationContext());

    /**
     * Hashmap to load data from the Sqlite database
     **/
     HashMap<String,String> user = new HashMap<String, String>();
     user = db.getUserDetails();

/**
 * TimeTable Refresh
 */



            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            refresh = (Button) findViewById(R.id.button1);


            refresh.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view) 
              {
                 String result = null;
                InputStream is = null;

                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://www.jamiepaleschi.co.uk/android_login/selectall.php");
                        HttpResponse response = httpclient.execute(httppost); 
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
                     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                }
                catch(Exception e)
                {
                        Log.e("log_tag", "Error in http connection "+e.toString());
                        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                }
                //convert response to string
                try
                {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) 
                        {
                                sb.append(line + "\n");
                              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
                        }
                        is.close();

                        result=sb.toString();
                }
                catch(Exception e)
                {
                       Log.e("log_tag", "Error converting result "+e.toString());
                    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();

                }

                //parse json data
                try
                {

                JSONArray jArray = new JSONArray(result);


                String re=jArray.getString(jArray.length());


                TableLayout tv=(TableLayout) findViewById(R.id.table);
                tv.removeAllViewsInLayout();




                   int flag=1;

                   for(int i=0;i<jArray.length();i++){
                       Object obj = jArray.get(i);
                       if (obj instanceof JSONObject) {
                       // is JSONObject
                        JSONObject json_data = (JSONObject)obj;

                       }else{




                                TableRow tr=new TableRow(Main.this);

                                tr.setLayoutParams(new LayoutParams(
                                           LayoutParams.WRAP_CONTENT,
                                           LayoutParams.WRAP_CONTENT));




                                if(flag==1)
                                {

                                    TextView b1=new TextView(Main.this);
                                     b1.setText("Mon");
                                     b1.setTextColor(Color.BLUE);
                                     b1.setTextSize(15);
                                     tr.addView(b1);


                                    TextView b19=new TextView(Main.this);
                                     b19.setPadding(10, 0, 0, 0);
                                     b19.setTextSize(15);
                                     b19.setText("Tue");
                                     b19.setTextColor(Color.BLUE);
                                     tr.addView(b19);

                                   TextView b29=new TextView(Main.this);
                                 b29.setPadding(10, 0, 0, 0);
                                     b29.setText("Wed");
                                     b29.setTextColor(Color.BLUE);
                                     b29.setTextSize(15);
                                     tr.addView(b29);

                                     TextView b39=new TextView(Main.this);
                                     b39.setPadding(10, 0, 0, 0);
                                         b39.setText("Thur");
                                         b39.setTextColor(Color.BLUE);
                                         b39.setTextSize(15);
                                         tr.addView(b39);

                                      TextView b49=new TextView(Main.this);
                                         b49.setPadding(10, 0, 0, 0);
                                             b49.setText("Fri");
                                             b49.setTextColor(Color.BLUE);
                                             b49.setTextSize(15);
                                             tr.addView(b49);


                                 tv.addView(tr);

                                     final View vline = new View(Main.this);
                                          vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, 2));
                                          vline.setBackgroundColor(Color.BLUE);



                                tv.addView(vline);
                                flag=0;


                                }

                                else
                                {



                                    JSONObject json_data = jArray.getJSONObject(i);

                                    Log.i("log_tag","Mon: "+json_data.getString("f1")+
                                              ", Tue: "+json_data.getString("f2")+
                                              ", Wed: "+json_data.getString("f3")+
                                              ", Thur: "+json_data.getString("f4")+
                                              ", Fri: "+json_data.getString("f5"));




                            TextView b=new TextView(Main.this);
                                String stime=String.valueOf(json_data.getString("f1"));
                                  b.setText(stime);
                                b.setTextColor(Color.RED);
                                b.setTextSize(10);
                                b.setWidth(60);
                                tr.addView(b);


                               TextView b1=new TextView(Main.this);
                                b1.setPadding(10, 0, 0, 0);
                                b1.setTextSize(10);
                                b1.setWidth(60);
                                String stime1=json_data.getString("f2");
                                 b1.setText(stime1);
                                b1.setTextColor(Color.WHITE);
                                tr.addView(b1);

                              TextView b2=new TextView(Main.this);
                             b2.setPadding(10, 0, 0, 0);
                                String stime2=String.valueOf(json_data.getString("f3"));
                                b2.setText(stime2);
                                b2.setTextColor(Color.RED);
                                b2.setTextSize(10);
                                b2.setWidth(60);
                                tr.addView(b2);

                                TextView b3=new TextView(Main.this);
                                b3.setPadding(10, 0, 0, 0);
                                   String stime3=String.valueOf(json_data.getString("f4"));
                                   b3.setText(stime3);
                                   b3.setTextColor(Color.WHITE);
                                   b3.setTextSize(10);
                                   b3.setWidth(60);
                                   tr.addView(b3);

                                 TextView b4=new TextView(Main.this);
                                   b4.setPadding(10, 0, 0, 0);
                                      String stime4=String.valueOf(json_data.getString("f5"));
                                      b4.setText(stime4);
                                      b4.setTextColor(Color.RED);
                                      b4.setTextSize(10);
                                      b4.setWidth(60);
                                      tr.addView(b4);

                                  tv.addView(tr);


                        final View vline1 = new View(Main.this);
                      vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, 1));
                      vline1.setBackgroundColor(Color.WHITE);
                      tv.addView(vline1);       


                                }

                       } }}




                catch(JSONException e)
                {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }




           }
           });

LOGCAT错误

03-04 05:04:58.727: E/AndroidRuntime(1005): FATAL EXCEPTION: main
03-04 05:04:58.727: E/AndroidRuntime(1005): java.lang.NullPointerException
03-04 05:04:58.727: E/AndroidRuntime(1005):     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at org.json.JSONArray.<init>(JSONArray.java:87)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at org.json.JSONArray.<init>(JSONArray.java:103)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at com.learn2crack.Main$1.onClick(Main.java:129)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at android.view.View.performClick(View.java:4240)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at android.view.View$PerformClick.run(View.java:17721)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at android.os.Handler.handleCallback(Handler.java:730)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at android.os.Looper.loop(Looper.java:137)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at android.app.ActivityThread.main(ActivityThread.java:5103)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at java.lang.reflect.Method.invokeNative(Native Method)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at java.lang.reflect.Method.invoke(Method.java:525)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-04 05:04:58.727: E/AndroidRuntime(1005):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:2)

这里:

JSONObject json_data = jArray.getJSONObject(i);

i==-1然后getJSONObject返回null,因为JSONArray中的索引-1中没有对象可用。因此将迭代条件更改为:

for(int i=0;i<jArray.length();i++){
  Object obj = jArray.get(i);
  if (obj instanceof JSONObject) {
  // is JSONObject
   JSONObject json_data = (JSONObject)obj;

  }else{
          //String....
   }
}

答案 1 :(得分:0)

更改以下行。如果json结果为null,它们将抛出Null指针异常。

    String re=jArray.getString(jArray.length()-1);

    String re= null;
    if(jArray.length!=0)jArray.getString(jArray.length()-1);

    for(int i=-1;i<jArray.length()-1;i++)

    for(int i=0;i<jArray.length();i++)