0

我正在通过 c# JSON webservice 从我的 sql 数据库中获取数据,并在按下按钮时将其显示在 android 应用程序的表中。

android 应用程序和 c# webservice 之间的连接成功建立但是当我尝试单击按钮查看数据时,它通过异常“JSONArray 失败”。

我认为 json 数组存在一些问题,但由于我刚刚开始学习 JSON Web 服务,所以无法弄清楚它是什么。程序运行成功完全没有错误。

c# webservice 代码在这里:

  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活动代码在这里:

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




           }
           });




     }


}

我在 android manifest.xml 文件中使用它:

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

程序抛出此异常:

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

我没有收到任何与 NetworkOnMainThreadException 相关的错误。

我在 android 2.2 和 2.3 模拟器上运行我的程序,但面临同样的问题,我只想在姜饼上部署我的应用程序。

谢谢

4

2 回答 2

1

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

于 2013-08-24T13:17:43.110 回答
0

最好拿来(download)/upload data in a separate thread。在 UI 线程上执行耗时的任务使其无响应。对于此类任务,首选以下两个

  • 异步任务
  • 线程

异步任务:

这是一个类,它有一些方法可以帮助您在更新 UI 的同时完成耗时的工作。例如:如果您想在大型文档/网页中搜索特定单词,请在doInBackground()(AsyncTask 类的方法)中进行阅读和搜索,您可以显示进度条并通知用户您的进度onProgressUpdate()。这给您的应用程序带来更专业的感觉,同时帮助您在后台执行耗时的任务。

主题:

它们很简单runnable threads。您可以使用这些线程执行非 UI 内容,但不能在其中执行 UI 任务(因为 UI 不是线程安全的)。为了在这些线程中处理 UI,您将不得不使用 Handlers,这对于初学者来说很难掌握和理解它们

于 2013-08-24T14:10:33.203 回答