Using IMEI as a parameter for JSON Service

喜你入骨 提交于 2019-12-24 16:18:45

问题


after grasping AsyncTask, I have run into yet another road bump. Using JSON (which connects to my local SQLServer, I would like to retrieve an object using the IMEI as a string parameter. I have set a breakpoint to my AsyncTask call and it just crashes, without even walking through. The IMEI of each mobile is stored in my database.

I implementing the following AsyncTask with the hope of running it on my device, and not on an emulator.

I suspect that it may have to do with my device, as both my web services are running on my PC. I have also changed the proxy and port in my APN settings to coincide with the URI of my service but it still doesn't even respond.

TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        IMEI = telephonyManager.getDeviceId();
        new loadDevice().execute(IMEI);

This is the code snippet from my OnCreate method.

Here is the AsyncTask class:

//AsyncTask to load get ManifestID from Device
    public class loadDevice extends AsyncTask<String, String, Manifests>
    {
        private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        InputStream inputStream = null;
        String theString = "";
        StringBuilder builder;

        protected void onPreExecute()
        {
            progressDialog.setMessage("Getting your assigned Manifest...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new OnCancelListener()
            {
                public void onCancel(DialogInterface arg0)
                {
                    loadDevice.this.cancel(true);
                }
            });
        }

        @Override
        protected Manifests doInBackground(String... arg0)
        {
            try
            {
                //http get request
                HttpGet request = new HttpGet(CentralURI + "/loadDevice/" + IMEI);
                //set the hedear to get the data in JSON format
                request.setHeader("Accept", "application/json");
                request.setHeader("Content-type", "application/json");

                DefaultHttpClient client = new DefaultHttpClient();

                //get the response
                HttpResponse response = client.execute(request);
                HttpEntity entity = response.getEntity();

                //read content
                InputStream is = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null)
                {
                    builder.append(line);
                }
                is.close(); 
                theString = builder.toString();

                JSONObject manifestJSON = new JSONObject(theString);
                JSONArray manifest = manifestJSON.getJSONArray("loadDeviceResult");

                for(int i = 1; i < manifest.length(); i++)
                {
                    JSONObject manObj = manifest.getJSONObject(i);
                    man.ManifestID = manObj.getInt("OriginalSOGManifestID");
                    man.DeviceManifestID = manObj.getInt("DeviceManifestID");
                    man.IMEI = manObj.getString("IMEI");
                    man.JobType = manObj.getString("prefix");
                    man.RegNo = manObj.getString("RegNo");
                    man.Complete = manObj.getBoolean("Complete");
                    man.DateComplete = manObj.getString("DateComplete");
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return man;
        }

        protected void onPostExecute(Manifests manifest)
        {
            //Manifests manifestToGet = new Manifests();
            //String manifestCode = manifestToGet.getJobType() + Integer.toString(manifestToGet.getManifestID());
            //new getManifestItems().execute(manifestCode);
        }

    }

My other AsyncTasks were working fine. However, after I put this beast in as the first AsyncTask to run, the others were not getting hit.

Here is the AsyncTask that relies on a property that is in the object retrieved by the first AsyncTask:-

//ASyncTask to get ManifestItem from each manifest
    public class getManifestItems extends AsyncTask<String, String, ArrayList<ManifestItemObj>>
    {
        private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        InputStream inputStream = null;
        String theString = "";
        StringBuilder builder;

        protected void onPreExecute()
        {
            progressDialog.setMessage("Loading manifests...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new OnCancelListener()
            {
                public void onCancel(DialogInterface arg0)
                {
                    getManifestItems.this.cancel(true);
                }
            });
        }

        @Override
        protected ArrayList<ManifestItemObj> doInBackground(String... params)
        {
            Manifests assign = man;
            String manifestCode = assign.getJobType() + Integer.toString(assign.getManifestID());

            try
            {
                //http get request
                HttpGet request = new HttpGet(POD_URI + "/getJobs/" +  manifestCode);
                //set the hedear to get the data in JSON format
                request.setHeader("Accept", "application/json");
                request.setHeader("Content-type", "application/json");

                DefaultHttpClient client = new DefaultHttpClient();

                //get the response
                HttpResponse response = client.execute(request);
                HttpEntity entity = response.getEntity();

                //read content
                InputStream is = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                                builder.append(line);
                        }
                is.close(); 
                theString = builder.toString();

                JSONObject jobsJSON = new JSONObject(theString);

                JSONArray jobs = jobsJSON.getJSONArray("getJobsResult");

               ManifestItemObj miDumb = new ManifestItemObj();
                miDumb.ManifestItemID = -1;
                miDumb.FKID = -1;
                miDumb.JobType = "--Please Select--";

                for(int i = 1; i < jobs.length(); i++)
                {
                    JSONObject mit = jobs.getJSONObject(i);
                    ManifestItemObj mi = new ManifestItemObj();
                    mi.ManifestItemID = mit.getInt("ManifestItemID");
                    mi.JobType = mit.getString("JobType");
                    mi.FKID = mit.getInt("FKID");

                    //ShipTo object
                    JSONObject stObj = mit.getJSONObject("ShipTo");

                    ShipTo sto = new ShipTo();
                    sto.ShipToId = stObj.getInt("ShipToId");
                    sto.ShipToName = stObj.getString("ShipToName");
                    sto.ShipToAddress1 = stObj.getString("ShipToAddress1");
                    sto.ShipToAddress2 = stObj.getString("ShipToAddress2");
                    sto.ShipToCity = stObj.getString("ShipToCity");
                    sto.ShipToPostcode = stObj.getString("ShipToPCode");
                    sto.ShipToState = stObj.getString("ShipToState");
                    mi.shipTo = sto;

                    jobList.add(mi);
                }
                jobList.add(0, miDumb);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return jobList;
        }

        protected void onPostExecute(ArrayList<ManifestItemObj> mio)
        {
            ManifestItemAdapter mia = new ManifestItemAdapter(MainActivity.this, android.R.layout.simple_spinner_item, jobList);
            this.progressDialog.dismiss();
            list_job.setAdapter(mia);

        }
    }

EDIT: Here is the logcat. I'm suspecting that the Button is being cast to the Spinner. Definitely not my intention but that's what it's saying:-

05-03 14:20:20.603: E/Trace(797): error opening trace file: No such file or directory (2)
05-03 14:20:21.204: D/AndroidRuntime(797): Shutting down VM
05-03 14:20:21.204: W/dalvikvm(797): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
05-03 14:20:21.224: E/AndroidRuntime(797): FATAL EXCEPTION: main
05-03 14:20:21.224: E/AndroidRuntime(797): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.signonglass/com.signonglass.MainActivity}: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.Spinner
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.os.Looper.loop(Looper.java:137)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.ActivityThread.main(ActivityThread.java:4745)
05-03 14:20:21.224: E/AndroidRuntime(797):  at java.lang.reflect.Method.invokeNative(Native Method)
05-03 14:20:21.224: E/AndroidRuntime(797):  at java.lang.reflect.Method.invoke(Method.java:511)
05-03 14:20:21.224: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-03 14:20:21.224: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-03 14:20:21.224: E/AndroidRuntime(797):  at dalvik.system.NativeStart.main(Native Method)
05-03 14:20:21.224: E/AndroidRuntime(797): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.Spinner
05-03 14:20:21.224: E/AndroidRuntime(797):  at com.signonglass.MainActivity.onCreate(MainActivity.java:55)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.Activity.performCreate(Activity.java:5008)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-03 14:20:21.224: E/AndroidRuntime(797):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
05-03 14:20:21.224: E/AndroidRuntime(797):  ... 11 more

回答1:


Could be one of these 2 things:

  1. Add permission to manifest < uses-permission android:name="android.permission.READ_PHONE_STATE"> (remove space after '<')
  2. You could be declaring a Button in the layout file of the MainActivity but cast it as a Spinner while initiating the Button or vice-versa.



回答2:


If you didn't give permission to access read phone state then add this line to AndroidManifest.xml (<uses-permission android:name="android.permission.READ_PHONE_STATE" />).




回答3:


I've fixed the problem, after shuffling the code around. I have since removed the button since it was not necessary.



来源:https://stackoverflow.com/questions/16350477/using-imei-as-a-parameter-for-json-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!