从Android应用程序在SQL Server中创建新条目

时间:2013-05-31 05:12:02

标签: android sql-server json wcf

我目前正在开发一个将信息输入我的JobStatus表的应用程序。实际上,当单击mSign按钮时,此ASyncTask应该运行。但是,我一直得到同样的错误。我猜它可能与我在调用AsyncTask时作为参数使用的内容有关。

根据经验,是否有人使用AsyncTask将Android应用程序中的信息输入SQL Server数据库?什么被认为是像这样的HTTPPost实例中的ASyncTask使用的“可接受”参数?

这里有什么我想念的吗?我之前已经实现了HttpGet,但我对整个HttpPost和AsyncTask都很陌生,所以任何帮助都会受到赞赏。

再次感谢大家。 :)

05-31 14:11:51.029: E/WindowManager(9545): Activity com.signonglass.CaptureSignature has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4178f590 that was originally added here
05-31 14:11:51.029: E/WindowManager(9545): android.view.WindowLeaked: Activity com.signonglass.CaptureSignature has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4178f590 that was originally added here
05-31 14:11:51.029: E/WindowManager(9545):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
05-31 14:11:51.029: E/WindowManager(9545):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:268)
05-31 14:11:51.029: E/WindowManager(9545):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:216)
05-31 14:11:51.029: E/WindowManager(9545):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:141)
05-31 14:11:51.029: E/WindowManager(9545):  at android.view.Window$LocalWindowManager.addView(Window.java:537)
05-31 14:11:51.029: E/WindowManager(9545):  at android.app.Dialog.show(Dialog.java:278)
05-31 14:11:51.029: E/WindowManager(9545):  at com.signonglass.CaptureSignature$updateJobStatus.onPreExecute(CaptureSignature.java:210)
05-31 14:11:51.029: E/WindowManager(9545):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
05-31 14:11:51.029: E/WindowManager(9545):  at android.os.AsyncTask.execute(AsyncTask.java:511)
05-31 14:11:51.029: E/WindowManager(9545):  at com.signonglass.CaptureSignature$2.onClick(CaptureSignature.java:169)
05-31 14:11:51.029: E/WindowManager(9545):  at android.view.View.performClick(View.java:3517)
05-31 14:11:51.029: E/WindowManager(9545):  at android.view.View$PerformClick.run(View.java:14155)
05-31 14:11:51.029: E/WindowManager(9545):  at android.os.Handler.handleCallback(Handler.java:605)
05-31 14:11:51.029: E/WindowManager(9545):  at android.os.Handler.dispatchMessage(Handler.java:92)
05-31 14:11:51.029: E/WindowManager(9545):  at android.os.Looper.loop(Looper.java:154)
05-31 14:11:51.029: E/WindowManager(9545):  at android.app.ActivityThread.main(ActivityThread.java:4624)
05-31 14:11:51.029: E/WindowManager(9545):  at java.lang.reflect.Method.invokeNative(Native Method)
05-31 14:11:51.029: E/WindowManager(9545):  at java.lang.reflect.Method.invoke(Method.java:511)
05-31 14:11:51.029: E/WindowManager(9545):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
05-31 14:11:51.029: E/WindowManager(9545):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
05-31 14:11:51.029: E/WindowManager(9545):  at dalvik.system.NativeStart.main(Native Method)

以下是关于我的AsyncTask的一些关键事项: -

private final static String jobURI = "http://192.168.0.105:8095/CentralMonitoring/CentralMonitor.svc/addJobStatus/";

WCF接口:

 [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "addJobStatus")]
        wsSQLResult AddJobStatus(Stream JSONdataStream);

WCF服务:(我已经使用Fiddler对其进行了测试,并且工作正常)。

public wsSQLResult AddJobStatus(Stream JSONdataStream)
        {
            wsSQLResult result = new wsSQLResult();
            try
            {
                // Read in our Stream into a string...
                StreamReader reader = new StreamReader(JSONdataStream);
                string JSONdata = reader.ReadToEnd();

                // ..then convert the string into a single "wsCustomer" record.
                JavaScriptSerializer jss = new JavaScriptSerializer();
                JobStatusObj jso = jss.Deserialize<JobStatusObj>(JSONdata);

                if (jso == null)
                {
                    result.WasSuccessful = 0;
                    result.Exception = "Unable to deserialize the JSON data.";
                }
                else
                {
                    CentralMonitoringDataContext cdc = new CentralMonitoringDataContext();
                    JobStatus js = new JobStatus()
                    {
                        JobStatusID = jso.JobStatusID,
                        JobType = jso.jobType,
                        QLSJobID = jso.qlsJobID,
                        DateComplete = DateTime.Parse(jso.dateComplete),
                        TimeComplete = DateTime.Parse(jso.timeComplete),
                        Latitude = Convert.ToDecimal(jso.latitude),
                        Longitude = Convert.ToDecimal(jso.longitude),
                        RecipientName = jso.recipientName
                    };

                    if (!cdc.JobStatus.Any(cj => cj.QLSJobID == jso.qlsJobID))
                    {
                        cdc.JobStatus.InsertOnSubmit(js);
                        cdc.SubmitChanges();

                        result.WasSuccessful = 1;
                        result.Exception = "";
                    }

                }
            }
            catch (Exception ex)
            {
                result.WasSuccessful = 0;
                result.Exception = ex.Message;
            }
            return result;
        }  
    }

最后,这是AsyncTask的代码:

public class addJobStatus extends AsyncTask<JobStatus, Void, Void>
    {
        private ProgressDialog progressDialog = new ProgressDialog(CaptureSignature.this);
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        InputStream inputStream = null;
        StringBuilder builder;


        protected void onPreExecute()
        {
            progressDialog.setMessage("Updating " + uniqueId +"...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new OnCancelListener()
            {
                public void onCancel(DialogInterface arg0)
                {
                    addJobStatus.this.cancel(true);

                }
            });     
        }

        @Override
        protected Void doInBackground(JobStatus... arg0)
        {
            try
            {
                JSONObject js = new JSONObject();
                js.put("jobType", cObj.getJobType());
                js.put("qlsJobID", cObj.getConsignmentID());
                js.put("dateComplete", sdf.format(currentTime));
                js.put("timeComplete", sdf.format(currentTime));
                js.put("latitude", location.getLatitude());
                js.put("longitude", location.getLongitude());
                js.put("recipientName", yourName.getText().toString());

                JSONArray jsArray = new JSONArray();
                jsArray.put(js);

                nameValuePairs.add(new BasicNameValuePair("addJobStatus", jsArray.toString()));
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost request = new HttpPost(jobURI);
                request.addHeader("Content-Type", "application/x-www-form-urlencoded");

                //StringEntity se = new StringEntity(jsArray.toString(), "UTF-8");

                request.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
                HttpResponse response = httpClient.execute(request);
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void unused)
        {
            progressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
        }



    }

我打算在这里调用AsyncTask: -

mGetSign.setOnClickListener(new OnClickListener() 
        {        
            public void onClick(View v) 
            {
                Log.v("log_tag", "Panel Saved");
                boolean error = captureSignature();
                if(!error)
                {
                    //initialise new jobStatus object here.
                    new addJobStatus().execute(js);
                    mView.setDrawingCacheEnabled(true);
                    mSignature.save(mView);
                    Bundle b = new Bundle();
                    b.putString("status", "done");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK,intent);
                    finish(); 
                }
            }
        });

2 个答案:

答案 0 :(得分:1)

这不是引起问题的参数。它根本与HTTP无关: - )

问题是,在您启动异步任务后,您正在通过finish()电话完成活动。

这导致Async任务progressDialog.show()调用失败,因为它没有Activity来显示对话框!

如果必须在Async任务之后完成活动,则在解除对话框后,在Async任务的onPostExecute()方法中执行此操作。这将确保没有像您现在获得的那样的Window泄漏错误。

答案 1 :(得分:0)

在@ Anup的帮助下,我解决了这个问题。我相信这是问题,首先是: -

  1. WCF服务中没有数组声明。所以我在AsyncTask中取出了JSONArray。

  2. 我从URI中取出了“/”。

  3. 正如我所建议的那样,@ Anup提到的“finish()”方法。

  4. 现在进入数据库就像没有明天一样。 :)

    即使已经排序,我仍然首先给@Anup提供头部。 :)