使用AsyncTask的Andr​​oid 4.2版本JSON填充微调 [英] Populating Spinner with JSON in Android 4.2 using AsyncTask

查看:231
本文介绍了使用AsyncTask的Andr​​oid 4.2版本JSON填充微调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在翻译的code代表,我在API10创建成API 16.从我读的应用程序在MainActivity,我已经开始使用AsyncTask的访问URI和显示信息我的应用程序。我设法做,在2.3,但它翻译成JSON后,我现在面临的一些障碍。

从本质上讲,该应用程序确实是这样的,它需要一个清单code即WAMF33000并在点击按钮,微调填充了包含在清单中的作业。由于我是相当新的AsyncTask的概念,我想了解我的code适用于背后的AsyncTask理论。

根据我的code

,我有一些问题: -
Ⅰ)中的AsyncTask我的code的是正在传递的参数?
II)什么是我的AsyncTask进展值?
三)最后,是我的返回值ManifestItems的ArrayList的?

由于2.3版本,我调用JSON两次 - 一次到清单内装载货物,并第二次加载微调选择代销的详细信息。

以下是我的code:

 包com.signonglass;进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.util.ArrayList;
进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.DefaultHttpClient;导入org.json *。进口android.os.AsyncTask;
进口android.os.Build;
进口android.os.Bundle;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Context;
进口android.content.Intent;
进口android.telephony.TelephonyManager;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemSelectedListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Spinner;
进口android.widget.TextView;
进口android.widget.Toast;公共类MainActivity扩展活动
{
    私人最终静态字符串POD_URI =htt​​p://192.168.0.105:8092/PodCore.svc;
    私人的EditText evManifest code;
    私人微调list_job;
    私人按钮btnSubmit按钮;
    私人字符串作业名;
    私人按钮btnCons;
    ArrayList的< ManifestItemObj>招贤纳才=新的ArrayList< ManifestItemObj>();
    ArrayList的< ConsignmentItems> conItemList =新的ArrayList< ConsignmentItems>();
    托运retConsignment;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);        evManifest code =(EditText上)findViewById(R.id.manifest);
        btnSubmit按钮=(按钮)findViewById(R.id.btnSearchManifest);
        list_job =(微调)findViewById(R.id.jobSpinner);
        // tvView =(的TextView)findViewById(R.id.deviceIdt);        // TelephonyManager telephonyManager =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
        //串IMEI_Number = telephonyManager.getDeviceId();
        //tvView.setText(\"IMEI数:+ IMEI_Number);    }    公共类MyAsyncTask扩展的AsyncTask<弦乐,无效的ArrayList< ManifestItemObj>>
    {        在preExecute保护无效()
        {        }        保护无效onPostExecute(ArrayList的< ManifestItemObj>招贤纳才)
        {        }        @覆盖
        保护的ArrayList< ManifestItemObj> doInBackground(字符串... PARAMS)
        {
            // HTTP GET请求
            HTTPGET请求=新HTTPGET(POD_URI +/ getJobs /+ evManifest code.getText()的toString());
            //设置hedear得到JSON格式的数据
            request.setHeader(接受,应用/ JSON);
            request.setHeader(内容类型,应用/ JSON);            DefaultHttpClient客户端=新DefaultHttpClient();
            字符串theString =新的String();            尝试
            {
                //得到响应
                HTT presponse响应= client.execute(请求);
                HttpEntity实体= response.getEntity();
                InputStream为= entity.getContent();
                读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是));                StringBuilder的建设者=新的StringBuilder();
                串线;
                而((行= reader.readLine())!= NULL){
                                builder.append(线);
                        }
                is.close();
                theString = builder.toString();                JSONObject的jobsJSON =新的JSONObject(theString);
                JSONArray工作= jobsJSON.getJSONArray(getJobsResult);                的for(int i = 1; I< jobs.length();我++)
                {
                    麻省理工学院的JSONObject = jobs.getJSONObject(I)
                    ManifestItemObj MI =新ManifestItemObj();
                    mi.ManifestItemID = mit.getInt(ManifestItemID);
                    mi.JobType = mit.getString(JobType);
                    mi.FKID = mit.getInt(FKID);
                    jobList.add(MI);
                }
            }
            赶上(例外五)
            {
                e.printStackTrace();
            }
            返回招贤纳才;
        }
    }
    / *私人无效showToast(弦乐味精)
    {
        // TODO自动生成方法存根
        Toast.makeText(这一点,敬酒:+味精,Toast.LENGTH_LONG).show();
    } * /    公共无效onViewConsignment(查看视图)
    {
        ShowItemsOfManifest(retConsignment);
    }    公共托运getConsignmentManifest(字符串代销)
    {
        托运CON =新的货物();        尝试
        {
            DefaultHttpClient客户端=新DefaultHttpClient();
            字符串theString =新的String();
            // HTTP GET请求
            HTTPGET请求=新HTTPGET(POD_URI +/ getJobDetails /+代销);
            //设置hedear得到JSON格式的数据
            request.setHeader(接受,应用/ JSON);
            request.setHeader(内容类型,应用/ JSON);            //得到响应
            HTT presponse响应= client.execute(请求);
            HttpEntity实体= response.getEntity();
            InputStream为= entity.getContent();
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是));            StringBuilder的建设者=新的StringBuilder();
            串线;
            而((行= reader.readLine())!= NULL)
            {
                builder.append(线);
            }
            is.close();            theString = builder.toString();            JSONObject的conJSON =新的JSONObject(theString);
            JSONArray缺点= conJSON.getJSONArray(getJobDetailsResult);            的for(int i = 0; I< cons.length();我++)
            {
                JSONObject的cObj = cons.getJSONObject(I)
                con.ConsignmentID = cObj.getInt(ConsignmentID);
                con.ConsignmentCreationDate = cObj.getString(ConsignmentCreationDate);
                con.ConsignmentCustRef = cObj.getString(ConsignmentCustRef);
                con.OrderNo = cObj.getString(OrderNo);
                con.ConsignmentActive = cObj.getBoolean(ConsignmentActive);
                con.JobType = cObj.getString(JobType);                //客户端对象
                JSONObject的clObj = cObj.getJSONObject(客户);
                客户CL =新客户();
                cl.ClientId = clObj.getInt(客户端ID);
                cl.ClientName = clObj.getString(CLIENTNAME);
                con.Clients = CL;                // SHIPTO对象
                JSONObject的stObj = cObj.getJSONObject(SHIPTO);
                SHIPTO STO =新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.ShipToPost code = stObj.getString(ShipToP code);
                sto.ShipToState = stObj.getString(ShipToState);
                con.ShipTo = STO;                // FreightZone对象
                JSONObject的fzObj = cObj.getJSONObject(FreightZone);
                FreightZones FZ =新FreightZones();
                fz.FreightZoneID = fzObj.getInt(FreightZoneId);
                fz.FreightZone = fzObj.getString(FreightZone);
                con.FreightZone = FZ;                JSONArray conItems = cObj.getJSONArray(ConsignmentItems);                为(中间体m为0; M&下; conItems.length(); M +)
                {
                    CIT的JSONObject = conItems.getJSONObject(米);
                    ConsignmentItems CI =新ConsignmentItems();
                    ci.ConsignmentItemID = cit.getInt(ConsignmentItemsID);
                    ci.Quantity = cit.getInt(数量);                    //从ConsignmentItems产品
                    JSONObject的亲= cit.getJSONObject(产品);
                    产品PROD =新产品();
                    prod.ProductId = pro.getInt(产品ID);
                    prod.ProductModel = pro.getString(产品型号);
                    prod.ItemsPerCarton = pro.getInt(PerCarton);
                    prod.ProductDescription = pro.getString(描述);
                    prod.Height =(浮点)pro.getDouble(高度);
                    prod.Length =(浮点)pro.getDouble(长度);
                    prod.Width =(浮点)pro.getDouble(宽度);
                    prod.Cubic =(浮点)pro.getDouble(立方);
                    ci.Product = PROD;
                    conItemList.add(CI);
                    con.ConsignmentItems = conItemList;
                }
            }
        }
        赶上(例外五)
        {
            e.printStackTrace();
        }
        返回CON;
    }    公共无效ShowItemsOfManifest(托运货物)
    {
        束束=新包();
        意图newIntent =新意图(this.getApplicationContext(),ConActivity.class);
        newIntent.putExtras(包);
        newIntent.putExtra(代销,货物);        this.startActivity(newIntent);    }    公共无效onSearchClick(查看视图)
    {
        新MyAsyncTask()执行();
        ManifestItemAdapter MIA =新ManifestItemAdapter(MainActivity.this,android.R.layout.simple_spinner_item,作业表);
        list_job.setAdapter(MIA);
    }
}

我期待着了解通过你的建设性的意见,更多的AsyncTask我的code。提前感谢帮助我提高我的code和我的Andr​​oid的理解,伙计们! :)

PS:请让我知道如果你需要更多的code的工作。我会更新我的帖子有必要更多的信息。干杯!


解决方案

背后的点的AsyncTask 是让你运行一个单独的线程的后台工作,如联网的东西所以你不要撑起 UI 键,用户仍然可以做的事情,而数据被下载。


  

其中在AsyncTask的我的$ C $的c是正在传递的参数?


您目前没有传递任何 PARAMS 的AsyncTask

 新MyAsyncTask()执行(); //如果需要的话,如URL,字符串等你干脆把PARAMS在这里...


  

什么是我的AsyncTask进展值?


据我所知,你没有之一。如果你想你可以使用 publishProgress(值)键,将被发送到 onProgressUpdate()更新之类的东西下载的文件,进程的时间,留给时间等...


  

最后,是我的返回值ManifestItems的ArrayList的?


您正在返回招贤纳才所以这就是将被发送到 onPostExecute()做你需要什么它

注意:一,了解关于的AsyncTask 最重要的事情是,你可以不更新 UI doInBackground(),所以你必须在其他的AsyncTask 方法之一做到这一点或值传递回 UI 功能。此外,的AsyncTask 2.3的工作方式不同比它在3.0及以后呢。它们不平行运行任何以上,但投入一个队列。所以,你可能想阅读有关executeOnExecutor()如果您希望它们在并行运行4.2。我希望这回答了你的问题。

的AsyncTask

executeOnExecutor()(<一href=\"http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor\" rel=\"nofollow\">http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor,参数...)

一对夫妇的其他事情我看到的是,你将要在 @覆盖标注添加到实现的方法,以及超级来电。

I am currently trying to translate the code for the MainActivity of an app that I created in API10 into API 16. From what I have read, I have to start using ASyncTask to access a URI and display the information on my app. I managed to do that in 2.3, but after translating it to JSON, I am now facing some roadblocks.

Essentially, what the app does is that, it takes a manifest code i.e. WAMF33000 and at the click of a button, the Spinner is populated with the jobs contained in that manifest. As I am fairly new to the concept of ASyncTask, I would like to understand how my code applies to the theory behind ASyncTask.

Based on my code, I have some questions:- i) Which of my code in the ASyncTask is the parameter that is being passed? ii) What is the progress value in my AsyncTask? iii) Finally, is my return value the ArrayList of ManifestItems?

As of the 2.3 version, I invoke the JSON twice - once to load the consignments within the Manifest, and the second time to load details of a consignment selected in the spinner.

The following is my code:

package com.signonglass;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import org.json.*;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
    private final static String POD_URI = "http://192.168.0.105:8092/PodCore.svc";
    private EditText evManifestCode;
    private Spinner list_job;
    private Button btnSubmit;
    private String jobName;
    private Button btnCons;
    ArrayList<ManifestItemObj> jobList = new ArrayList<ManifestItemObj>();
    ArrayList<ConsignmentItems> conItemList = new ArrayList<ConsignmentItems>();
    Consignments retConsignment;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        evManifestCode = (EditText)findViewById(R.id.manifest);
        btnSubmit = (Button)findViewById(R.id.btnSearchManifest);
        list_job = (Spinner)findViewById(R.id.jobSpinner);
        //tvView = (TextView)findViewById(R.id.deviceIdt);



        //TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        //String IMEI_Number = telephonyManager.getDeviceId();
        //tvView.setText("IMEI Number: " + IMEI_Number);

    }

    public class MyAsyncTask extends AsyncTask<String, Void, ArrayList<ManifestItemObj>>
    {

        protected void onPreExecute()
        {

        }

        protected void onPostExecute(ArrayList<ManifestItemObj> jobList)
        {

        }

        @Override
        protected ArrayList<ManifestItemObj> doInBackground(String... params)
        {
            //http get request
            HttpGet request = new HttpGet(POD_URI + "/getJobs/" + evManifestCode.getText().toString());
            //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();
            String theString = new String("");

            try
            {
                //get the response
                HttpResponse response = client.execute(request);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                StringBuilder 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");

                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");
                    jobList.add(mi);
                }      
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return jobList;
        }
    }


    /*private void showToast(String msg)
    {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
    }*/

    public void onViewConsignment(View view)
    {
        ShowItemsOfManifest(retConsignment);
    }

    public Consignments getConsignmentManifest(String consignment)
    {
        Consignments con = new Consignments();

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

            //get the response
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

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

            theString = builder.toString();

            JSONObject conJSON = new JSONObject(theString);
            JSONArray cons = conJSON.getJSONArray("getJobDetailsResult");

            for(int i = 0; i < cons.length(); i++)
            {
                JSONObject cObj = cons.getJSONObject(i);
                con.ConsignmentID = cObj.getInt("ConsignmentID");
                con.ConsignmentCreationDate = cObj.getString("ConsignmentCreationDate");
                con.ConsignmentCustRef = cObj.getString("ConsignmentCustRef");
                con.OrderNo = cObj.getString("OrderNo");
                con.ConsignmentActive = cObj.getBoolean("ConsignmentActive");
                con.JobType = cObj.getString("JobType");

                //Client object
                JSONObject clObj = cObj.getJSONObject("Client");
                Clients cl = new Clients();
                cl.ClientId = clObj.getInt("ClientID");
                cl.ClientName = clObj.getString("ClientName");
                con.Clients = cl;

                //ShipTo object
                JSONObject stObj = cObj.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");
                con.ShipTo = sto;

                //FreightZone object
                JSONObject fzObj = cObj.getJSONObject("FreightZone");
                FreightZones fz = new FreightZones();
                fz.FreightZoneID = fzObj.getInt("FreightZoneId");
                fz.FreightZone = fzObj.getString("FreightZone");
                con.FreightZone = fz;

                JSONArray conItems = cObj.getJSONArray("ConsignmentItems");

                for(int m = 0; m < conItems.length(); m++)
                {
                    JSONObject cit = conItems.getJSONObject(m);
                    ConsignmentItems ci = new ConsignmentItems();
                    ci.ConsignmentItemID = cit.getInt("ConsignmentItemsID");
                    ci.Quantity = cit.getInt("QTY");

                    //get Product from ConsignmentItems
                    JSONObject pro = cit.getJSONObject("Products");
                    Products prod = new Products();
                    prod.ProductId = pro.getInt("ProductID");
                    prod.ProductModel = pro.getString("ProductModel");
                    prod.ItemsPerCarton = pro.getInt("PerCarton");
                    prod.ProductDescription = pro.getString("Description");
                    prod.Height = (float) pro.getDouble("Height");
                    prod.Length = (float) pro.getDouble("Length");
                    prod.Width = (float) pro.getDouble("Width");
                    prod.Cubic = (float) pro.getDouble("Cubic");
                    ci.Product = prod;
                    conItemList.add(ci);
                    con.ConsignmentItems = conItemList;
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return con;
    }

    public void ShowItemsOfManifest(Consignments consignments)
    {
        Bundle bundle = new Bundle();
        Intent newIntent = new Intent(this.getApplicationContext(), ConActivity.class);
        newIntent.putExtras(bundle);
        newIntent.putExtra("Consignment", consignments);

        this.startActivity(newIntent);

    }

    public void onSearchClick(View view)
    {
        new MyAsyncTask().execute();
        ManifestItemAdapter mia = new ManifestItemAdapter(MainActivity.this, android.R.layout.simple_spinner_item, jobList);
        list_job.setAdapter(mia); 
    }
}

I look forward to understanding more about ASyncTask through your constructive comments on my code. Thanks ahead for helping me improve my code and my understanding of Android, guys! :)

PS: Please let me know if you need any more code to work with. I will update my post with more information as necessary. Cheers!

解决方案

The point behind AsyncTask is to allow you to run background work on a separate thread such as networking stuff so you don't hold up the UI and users can still do things while data is being downloaded.

Which of my code in the ASyncTask is the parameter that is being passed?

You currently are not passing any params to the AsyncTask

new MyAsyncTask().execute(); // you would put params in here if needed such as a URL, String, etc...

What is the progress value in my AsyncTask?

As far as I can tell, you don't have one. If you wanted to you could use publishProgress(value) and that would be sent to onProgressUpdate() to update things like files downloaded, time of progression, time left, etc...

Finally, is my return value the ArrayList of ManifestItems?

you are returning jobList so that is what will get sent to onPostExecute() to do what you need with it

Note: One of the most important things to understand about AsyncTask is that you can't update the UI from doInBackground() so you must do this in one of the other AsyncTask methods or pass values back to a UI function. Also, AsyncTask works differently in 2.3 than it does in 3.0 and beyond. They don't run in parallel any more but put into a queue. So you may want to read about executeOnExecutor() if you want them to run in parallel in 4.2. I hope this answers your questions

AsyncTask

executeOnExecutor()(http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor, Params...)

A couple other things I see is that you will want to add the @Override annotation to the implemented methods as well as super calls.

这篇关于使用AsyncTask的Andr​​oid 4.2版本JSON填充微调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆