java - Android 下载文件任务概念

标签 java android androidhttpclient android-handlerthread

在教程的帮助下尝试使用客户端服务器(获取 mysql 数据)时,我遇到了许多错误。我刚刚在这里阅读了一些帖子,我了解到我遇到的最大错误

Error in http connectionandroid.os.NetworkOnMainThreadException E/log_tag: Error converting result java.lang.NullPointerException

可能是因为我需要线程和处理程序之间的辅助任务。

我有以下代码,我理解这个概念,通常它应该可以工作。

    package de.irgendwas;

import android.app.Activity;
import android.net.ParseException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class MainActivity extends Activity {
    private GoogleApiClient client;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /** Called when the activity is first created. */

        String result = null;
        InputStream is = null;
        StringBuilder sb = null;

        //http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://localhost/connect_db.php");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("log_tag", "connection established");
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
        }

        //convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        //paring data
        int fd_id = 0;
        String fd_name = "";
        try {
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data = null;
            Toast.makeText(getBaseContext(), "1. try Block", Toast.LENGTH_LONG).show();
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                fd_id = json_data.getInt("artist");
                fd_name = json_data.getString("title");
            }
        } catch (JSONException e1) {
            Toast.makeText(getBaseContext(), "No Data Found", Toast.LENGTH_LONG).show();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

        //print received data
        TextView t = (TextView) findViewById(R.id.text);
        t.setText("ID: " + fd_id + " Name: " + fd_name);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

}

我不会在服务器上发布 php 脚本,因为如果我通过浏览器调用 URL,它会正确传递我的测试数据,所以应该没问题。

现在,在执行应用程序时,我收到上述错误。在网上搜索时,我发现了 DownloadFilesTask 概念,听起来它应该是解决方案。但我不会明白,我无法在我的代码中实现它。有人可以帮忙吗?除了developer.android 上的教程之外,还有其他地方有好的教程吗?

最佳答案

发生错误是因为您想在 UI 线程中执行与网络相关的过程。您需要将其从 UI 线程中移开。对于您的情况,您可以使用 AsyncTask .

AsyncTask 是一种在后台线程中执行操作的机制,无需手动处理线程创建或执行。 AsyncTasks 被设计用于短时间操作(最多几秒),您可能希望使用服务和/或执行器来执行非常长时间运行的任务。

AsyncTask 通常用于无法在 UI 线程上完成的长时间运行的任务,例如从 API 下载网络数据或从设备上的其他位置索引数据。

请阅读Creating and Executing Async Tasks .

这里有一个example for using AsyncTask在网络相关过程中:

public class MainActivity extends Activity {
    private ImageView ivBasicImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ivBasicImage = (ImageView) findViewById(R.id.ivBasicImage);
        String url = "https://i.imgur.com/tGbaZCY.jpg";
        // Download image from URL and display within ImageView
        new ImageDownloadTask(ivBasicImage).execute(url);
    }

    // Defines the background task to download and then load the image within the ImageView
    private class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
        ImageView imageView;

        public ImageDownloadTask(ImageView imageView) {
            this.imageView = imageView;
        }

        protected Bitmap doInBackground(String... addresses) {
            Bitmap bitmap = null;
            InputStream in;
            try {
                // 1. Declare a URL Connection
                URL url = new URL(addresses[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 2. Open InputStream to connection
                conn.connect();
                in = conn.getInputStream();
                // 3. Download and decode the bitmap using BitmapFactory
                bitmap = BitmapFactory.decodeStream(in);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
              if(in != null)
                 in.close();
            }
            return bitmap;
        }

        // Fires after the task is completed, displaying the bitmap into the ImageView
        @Override
        protected void onPostExecute(Bitmap result) {
            // Set bitmap image for the result
            imageView.setImageBitmap(result);
        }
    }
}

关于java - Android 下载文件任务概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41349428/

相关文章:

java - 如何使用 Maven 插件部署具有多个名称的 Azure Function?

java - 为什么 AudioManager 在 RingerMode 改变时崩溃?

android - 如何使用请求体(application/json)和请求头进行API调用?

android - 无法连接到 localhost/127.0.0.1 android

java - 需要在 Tomcat 中将两个应用程序映射到相同的基本 URL 下

java - 在 System.out.close() 之后重新创建 System.out 以在 CONSOLE 中再次打印

java - 无法解析原始文件夹 - android

android - 删除 inputType 为 numberDecimal 的 EditText 文本

Android - AQuery 在回调方法上获取图像

java - 为什么使用 AspectJ 的 google 缓存很慢,而 SpringCaching 却更快