【问题标题】:How to add Async threads to connect to http server in Android studio如何在 Android Studio 中添加异步线程以连接到 http 服务器
【发布时间】:2017-03-24 22:24:10
【问题描述】:

我想为此代码创建异步线程,从 SQLite 中提取数据并将其显示为电话联系人应用程序。该应用程序目前运行良好,因为我使用的是 StrictMode 方式。但是我真的很想学习使用异步线程,我不知道如何将它添加到这个例子中。

代码如下:

 public class MainActivity extends AppCompatActivity {

ListView employeeList;
ArrayList<Employee> allEmployee = null;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    setContentView(R.layout.activity_main);
    try {
        employeeList = (ListView) findViewById(R.id.EmployeeList);
        allEmployee = new ArrayList<Employee>();
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        HttpURLConnection urlConnection;
        InputStream in = null;

        URL url = new URL("http://10.0.2.2:8005/get");
        urlConnection = (HttpURLConnection) url.openConnection();
        in = new BufferedInputStream(urlConnection.getInputStream());

        String response = convertStreamToString(in);
        System.out.println("Server response = " + response);

        JSONArray jsonArray = new JSONArray(response);
        String[] employeeNames = new String[jsonArray.length()];
        String[] employeeEmail= new String[jsonArray.length()];
        String[] employeeGender= new String[jsonArray.length()];
        String[] employeeNatins= new String[jsonArray.length()];
        String[] employeeDob= new String[jsonArray.length()];
        String[] employeeAddress= new String[jsonArray.length()];
        String[] employeePostcode= new String[jsonArray.length()];
        String[] employeeSalary= new String[jsonArray.length()];
        String[] employeeStartDate= new String[jsonArray.length()];
        String[] employeeTitle= new String[jsonArray.length()];
        for (int i=0; i < jsonArray.length(); i++)
        {
            String name = jsonArray.getJSONObject(i).get("name").toString();
            String email = jsonArray.getJSONObject(i).get("email").toString();
            String gender = jsonArray.getJSONObject(i).get("gender").toString();
            String natins = jsonArray.getJSONObject(i).get("natins").toString();
            String dob = jsonArray.getJSONObject(i).get("dob").toString();
            String address = jsonArray.getJSONObject(i).get("address").toString();
            String postcode = jsonArray.getJSONObject(i).get("postcode").toString();
            String salary = jsonArray.getJSONObject(i).get("salary").toString();
            String startdate = jsonArray.getJSONObject(i).get("startdate").toString();
            String title = jsonArray.getJSONObject(i).get("title").toString();



            System.out.println("name = " + name);
            System.out.println("email = " + email);
            employeeNames [i] = name;
            employeeEmail [i] = email;
            employeeGender [i] = gender;
            employeeNatins [i] = natins;
            employeeDob [i] = dob;
            employeeAddress [i] = address;
            employeePostcode [i] = postcode;
            employeeSalary [i] = salary;
            employeeStartDate [i] = startdate;
            employeeTitle [i] = title;


            Employee employee = new Employee(name, email, gender, natins, dob, address, postcode, salary, startdate, title);
            allEmployee.add(employee);

            Map<String, String> datum = new HashMap<String, String>(2);
            datum.put("name", allEmployee.get(i).getName());
            datum.put("email", allEmployee.get(i).getEmail());
            data.add(datum);


        }

        SimpleAdapter arrayAdapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"name", "email"}, new int[] {android.R.id.text1, android.R.id.text2});


        employeeList.setAdapter(arrayAdapter);
        employeeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long
                    l) {
                Toast.makeText(MainActivity.this, "you pressed " +
                        allEmployee.get(i).getName(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(), DetailsActivity.class);
                intent.putExtra("employee", allEmployee.get(i));

                startActivity(intent);
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }

}

public String convertStreamToString(InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}}

这是我想要做的:

 private class GetData extends AsyncTask<Void, Void, ArrayList<Employee>> {
      @Override
      protected ArrayList<Employee> doInBackground(Void... v) {
           //Make http call
           return null;
      }

      @Override
      protected void onPostExecute(ArrayList<Employee> {
           super.onPostExecute(ArrayList<Employee);
           //Process the employees ArrayList and set up ListView
      }
 }

我什至不确定我是否完全理解需要格式化的方式。一些帮助将不胜感激。

【问题讨论】:

  • 将所有网络请求代码放入 doInBackground() 并在 onPostExecute() 方法中创建适配器并在 listview 中设置。

标签: java android asynchronous android-asynctask


【解决方案1】:

去过那里。有很多方法可以做你想做的事。但是通过阅读您的代码,您似乎希望从服务器获得异步响应,该响应以 JSON 格式输出(您从字符串中解析),因此我将在我使用 @987654321 开发的应用程序的注释部分下方发布@lib(该链接有 Android Studio 的安装说明)

//This creates the Volley instance that will work your async requests.
RequestQueue myVolleyQueue = Volley.newRequestQueue(getApplicationContext());


//Now we create the actual request that you make on your server.
StringRequest myStringRequest = new StringRequest("http://myadress.com/xyz", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
            //This will run once you get your response from the server.    
            myResponseParsingFunction(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //This runs when/if you get an error. Like server offline.
            }
        });

//Last but not least you add your newly created request to the Volley request queue you created
myVolleyQueue.add(myStringRequest);

您也可以直接发出 JSON 请求。但只会更改对象类型...检查 lib 链接示例。

【讨论】:

    【解决方案2】:

    你可以参考这个,

    https://developer.android.com/reference/android/os/AsyncTask.html

    将 http 调用放入 doInBackground。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多