简体   繁体   English

Android中的JSON数组错误

[英]JSON Array Error in Android

I am fetching data from my sql database through c# JSON webservice and display it in table in android app on button press. 我正在通过c#JSON webservice从我的sql数据库中获取数据,并在按下按钮时将其显示在android应用程序的表中。

The connection between android app and c# webservice successfulyy establish but when I try to click button to view data it throughs exception "JSONArray fail". android app和c#webservice之间的连接成功建立,但是当我尝试单击按钮查看数据时,它通过异常“ JSONArray fail”。

I think there is some problem in json array but as I have just started to learn JSON web service so unable to figure out what is it. 我认为json数组中存在一些问题,但是由于我刚刚开始学习JSON Web服务,因此无法弄清它是什么。 there is no error in program running success full. 程序完全成功运行没有错误。

c# webservice code is here : C#Web服务代码在这里:

  public string getData()
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand command = new SqlCommand("SELECT * FROM Student where CAST(Student.[date] AS DATE) = CAST(GETDATE() AS DATE)", con);
            SqlDataReader reader = command.ExecuteReader();

            if (reader.Read())
            {
                return "1";
            }
            else
            {
                return "0";
            }
        }

android activity code is here : android活动代码在这里:

public class StudentActivity extends Activity
{


     public void onCreate(Bundle savedInstanceState)

     {



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






            Button button2 = (Button) findViewById(R.id.button2);




            button2.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view)
              {
                 String rs = "";
                InputStream is = null;


                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2:51220/Service1.svc/getData?");
                        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();

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

                }

                //parse json data
                try
                {


                JSONArray jArray = new JSONArray(rs);


                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(StudentActivity.this);

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




                                if(flag==1)
                                {

                                    TextView b6=new TextView(StudentActivity.this);
                                     b6.setText("ID");
                                     b6.setTextColor(Color.BLUE);
                                     b6.setTextSize(15);
                                     tr.addView(b6);


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

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


                                     TextView b4=new TextView(StudentActivity.this);
                                 b4.setPadding(10, 0, 0, 0);
                                     b4.setText("Project");
                                     b4.setTextColor(Color.BLUE);
                                     b4.setTextSize(15);
                                     tr.addView(b4);


                                     TextView b5=new TextView(StudentActivity.this);
                                 b5.setPadding(10, 0, 0, 0);
                                     b5.setText("Date and Time");
                                     b5.setTextColor(Color.BLUE);
                                     b5.setTextSize(15);
                                     tr.addView(b5);





                                 tv.addView(tr);

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



                                tv.addView(vline);
                                flag=0;


                                }

                                else
                                {



                                    JSONObject json_data = jArray.getJSONObject(i);

                                    Log.i("log_tag","id: "+json_data.getInt("f1")+
                                              ", firstname: "+json_data.getString("f2")+
                                              ", lastname: "+json_data.getInt("f3") +
                                              ", project: "+json_data.getString("f4")+
                                              ", datetime: "+json_data.getString("f5"));




                            TextView b=new TextView(StudentActivity.this);
                                String stime=String.valueOf(json_data.getInt("f1"));
                                  b.setText(stime);
                                b.setTextColor(Color.RED);
                                b.setTextSize(15);
                                tr.addView(b);


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

                              TextView b2=new TextView(StudentActivity.this);
                             b2.setPadding(10, 0, 0, 0);
                                String stime2=String.valueOf(json_data.getInt("f3"));
                                b2.setText(stime2);
                                b2.setTextColor(Color.RED);
                                b2.setTextSize(15);
                                tr.addView(b2);


                                TextView b3=new TextView(StudentActivity.this);
                             b3.setPadding(10, 0, 0, 0);
                                String stime3=String.valueOf(json_data.getInt("f4"));
                                b3.setText(stime3);
                                b3.setTextColor(Color.WHITE);
                                b3.setTextSize(15);
                                tr.addView(b3);


                                TextView b4=new TextView(StudentActivity.this);
                             b4.setPadding(10, 0, 0, 0);
                                String stime4=String.valueOf(json_data.getInt("f5"));
                                b4.setText(stime4);
                                b4.setTextColor(Color.RED);
                                b4.setTextSize(15);
                                tr.addView(b4);

                                  tv.addView(tr);


                        final View vline1 = new View(StudentActivity.this);
                      vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 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();
                }




           }
           });




     }


}

I am using this in android manifest.xml file : 我在android manifest.xml文件中使用它:

 <uses-permission android:name="android.permission.INTERNET"/>

program is throwing this exception: 程序抛出此异常:

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

I am not getting any error related to NetworkOnMainThreadException. 我没有收到与NetworkOnMainThreadException相关的任何错误。

I run my program both on android 2.2 and 2.3 emulator but facing same problem and I want to deploy my app on gingerbread only. 我在android 2.2和2.3模拟器上都运行了程序,但是面临相同的问题,我只想将应用程序部署在姜饼上。

Thanks 谢谢

您应该在子线程中执行网络操作。

It's better to fetch (download)/upload data in a separate thread . 最好(download)/upload data in a separate thread获取(download)/upload data in a separate thread Doing time consuming tasks on UI thread make it un-responsive. 在UI线程上执行耗时的任务会使它无响应。 For such tasks, following two are prefered 对于此类任务,首选以下两个

  • Async Task 异步任务
  • Threads 线程数

AsyncTask: AsyncTask:

It's a class which have a few methods which help you to do time consuming work while updating the UI at the same time. 该类具有一些方法,可帮助您在更新UI的同时完成耗时的工作。 For Example: If you want to search a specific word in a big document/ webpage, do the reading and searching stuff in doInBackground() (a method of AsyncTask class) and you can display a progress bar and notify the user with your progress with onProgressUpdate() . 例如:如果要在大文档/网页中搜索特定单词,请在doInBackground() (AsyncTask类的一种方法doInBackground()进行阅读和搜索, doInBackground()可以显示进度条并向用户通知您的进度。 onProgressUpdate() This gives your app more professional feel and at the same time helps you executing time consuming task in background. 这为您的应用程序带来了更专业的感觉,同时帮助您在后台执行耗时的任务。

Threads: 线程数:

They are simple runnable threads . 它们是简单的runnable threads You can execute non UI stuff with these threads but you can't perform UI tasks in them (as UI is not thread safe). 您可以使用这些线程执行非UI内容,但不能在其中执行UI任务(因为UI不是线程安全的)。 For dealing with UI in these threads, you will have to use Handlers, which is quite cumbersome for beginners to get a grip and understanding of them 为了在这些线程中处理UI,您将不得不使用Handlers,这对于初学者来说很难掌握和理解它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM