gpt4 book ai didi

android - Android 应用程序中的线程

转载 作者:行者123 更新时间:2023-11-29 21:09:36 25 4
gpt4 key购买 nike

<分区>

我是 Android 开发的新手。当我创建我的第一个程序时,我只是在主线程上运行所有东西,因为它们是非常小的应用程序。我已经开始在我的应用程序中使用 Web API,并且知道任何处理网络的东西都应该有自己的线程。我尝试了多个使用 AsyncTasks 并使用 Thread 和 Handlers 的示例,但我无法将它应用到我自己的代码中,因此我将它带到这里以征求关于如何线程化我目前在下面的内容的想法和建议。

快速代码概述:我正在接收来自另一个 Activity 的输入,并根据该输入为 Web API 创建 HTTP 请求。我收到返回的 JSON 并提取一个 ID 号。然后我必须使用 ID 号向 Web API 发出另一个 HTTP 请求,然后我在其中解析 JSON 并创建一个数组适配器以在我的 Activity 中显示一个列表。

package com.example.myfirstapp;

imports ....


public class BREWERYMessageActivity extends ListActivity {
//Variable from another Activity
public final static String BREWERY_MESSAGE = "com.example.myfirstapp.BREWERY";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Intent intent = getIntent();
final String brewery = intent.getStringExtra(MainActivity.BREWERY_MESSAGE);


try {
URL breweryDBurl = new URL("web api url using brewery variable");

URLConnection conn = breweryDBurl.openConnection();

BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));


String inputLine;

while ((inputLine = in.readLine()) != null) {

JSONObject jsonobject = new JSONObject(inputLine);

JSONArray jArray = jsonobject.getJSONArray("data");


JSONObject obj1 = (JSONObject)jArray.getJSONObject(0);

String ID;

try{
ID = obj1.getString("id");
}catch(Exception e){
ID = "N/A";
}


try {
URL DBurl = new URL("Second web API call using the ID");

URLConnection con = DBurl.openConnection();

BufferedReader inpt = new BufferedReader(
new InputStreamReader(
con.getInputStream()));

String inputLn;

ArrayList<String> stringList = new ArrayList<String>();

while ((inputLn = inpt.readLine()) != null) {

JSONObject jsonobj = new JSONObject(inputLn);

JSONArray jArry = jsonobj.getJSONArray("data");

String name;

for(int i = 0; i < jArry.length(); i++){
JSONObject obj = (JSONObject)jArry.getJSONObject(i);


try{
name = obj.getString("name");
} catch(Exception e) {
name = "N/A";
}


if(!(name.equals("N/A")))
stringList.add(name);
}
name = "";
}
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(BREWERYMessageActivity.this,android.R.layout.simple_list_item_1, stringList);
setListAdapter(adapter);

}catch(Exception e){
// Create the text view
TextView textView = new TextView(BREWERYMessageActivity.this);
textView.setTextSize(20);
textView.setText("Not Available");
textView.setGravity(Gravity.CENTER_HORIZONTAL);

// Set the text view as the activity layout
setContentView(textView);


}




}



}catch(Exception e){
// Create the text view
TextView textView = new TextView(BREWERYMessageActivity.this);
textView.setTextSize(20);
textView.setText("Not Available");
textView.setGravity(Gravity.CENTER_HORIZONTAL);

// Set the text view as the activity layout
setContentView(textView);
}

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