gpt4 book ai didi

android - 使用 AsyncTask 在 Android 4.2 中使用 JSON 填充 Spinner

转载 作者:行者123 更新时间:2023-11-29 18:00:52 24 4
gpt4 key购买 nike

我目前正在尝试将我在 API10 中创建的应用程序的 MainActivity 代码转换为 API 16。根据我所阅读的内容,我必须开始使用 ASyncTask 来访问 URI 并在我的应用程序上显示信息。我设法在 2.3 中做到了这一点,但在将其转换为 JSON 后,我现在面临一些障碍。

从本质上讲,该应用程序所做的是,它需要一个 list 代码,即 WAMF33000,然后单击一个按钮,Spinner 就会填充该 list 中包含的作业。由于我对 ASyncTask 的概念相当陌生,因此我想了解我的代码如何应用于 ASyncTask 背后的理论。

根据我的代码,我有一些问题:-i) 我在 ASyncTask 中的哪个代码是传递的参数?ii) 我的 AsyncTask 中的进度值是多少?iii) 最后,我的返回值是 ManifestItems 的 ArrayList 吗?

从 2.3 版本开始,我调用了 JSON 两次 - 一次是在 list 中加载 cargo ,第二次是加载在微调器中选择的 cargo 的详细信息。

以下是我的代码:

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

我期待通过您对我的代码提出的建设性意见进一步了解 ASyncTask。伙计们,在此先感谢您帮助我改进我的代码和我对 Android 的理解! :)

PS:如果您需要更多代码,请告诉我。我会根据需要更新我的帖子,提供更多信息。干杯!

最佳答案

AsyncTask 背后的要点是允许您在单独的线程上运行后台工作,例如网络内容,这样您就不会占用 UI,用户仍然可以在下载数据时做事。

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

您目前没有将任何params 传递给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?

据我所知,你没有。如果您愿意,您可以使用 publishProgress(value) 并将其发送到 onProgressUpdate() 以更新下载的文件、进度时间、剩余时间等内容。 ..

Finally, is my return value the ArrayList of ManifestItems?

您正在返回 jobList,因此它将被发送到 onPostExecute() 以执行您需要的操作

注意:了解AsyncTask 最重要的事情之一是您不能从doInBackground 更新UI () 因此您必须在其他 AsyncTask 方法之一中执行此操作或将值传回 UI 函数。此外,AsyncTask 在 2.3 中的工作方式与在 3.0 及更高版本中的不同。它们不再并行运行,而是放入队列中。因此,如果您希望它们在 4.2 中并行运行,您可能需要阅读有关 executeOnExecutor() 的内容。我希望这能回答你的问题

AsyncTask

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

我看到的其他一些事情是您需要将 @Override 注释添加到已实现的方法以及 super 调用中。

关于android - 使用 AsyncTask 在 Android 4.2 中使用 JSON 填充 Spinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16174065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com