简体   繁体   English

为什么在AsyncTask中抛出NetworkOnMainThreadException?

[英]Why NetworkOnMainThreadException is being thrown inside AsyncTask?

everyone. 大家。 I'm using drawer activity, changing content using fragments, so there's PerfilFragment , for example: 我正在使用抽屉活动,使用片段更改内容,因此有PerfilFragment ,例如:

public class PerfilFragment extends Fragment {

    final CurrentView currentView = new CurrentView();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_perfil, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (getActivity() != null) {
            getActivity().setTitle(R.string.menu_perfil);

            final CognitoCachingCredentialsProvider credentialsProvider;

            if (getContext() != null) {
                AWSConfiguration awsConfig = new AWSConfiguration(getContext());
                credentialsProvider = new CognitoCachingCredentialsProvider(
                        getContext(),
                        awsConfig
                );

                currentView.setCredentialsProvider(credentialsProvider);
                currentView.setView(view);

                final FloatingActionButton fab = view.findViewById(R.id.fab);
                fab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new Insert().doInBackground(currentView);
                    }
                });
            }
        }
    }
}

The type CurrentView is an internal class, as well as Insert class: CurrentView类型是一个内部类,以及Insert类:

class CurrentView {
    private CognitoCachingCredentialsProvider credentialsProvider;
    private View view;

    CognitoCachingCredentialsProvider getCredentialsProvider() {
        return credentialsProvider;
    }

    void setCredentialsProvider(CognitoCachingCredentialsProvider credentialsProvider) {
        this.credentialsProvider = credentialsProvider;
    }

    View getView() {
        return view;
    }

    void setView(View view) {
        this.view = view;
    }
}

class Insert extends AsyncTask<CurrentView, Void, Table> {

    private final static String TABLE = "perfil";

    @Override
    protected Table doInBackground(CurrentView... currentView) {
        AmazonDynamoDBClient dbClient;

        try {
            dbClient = new AmazonDynamoDBClient(currentView[0].getCredentialsProvider());
            Table perfilTable = Table.loadTable(dbClient, TABLE);

            Document perfilDocument = new Document();

            final EditText perfilNome = currentView[0].getView().findViewById(R.id.perfil_nome_txt);
            final EditText perfilDataNasc = currentView[0].getView().findViewById(R.id.perfil_datanasc_txt);
            final EditText perfilGenero = currentView[0].getView().findViewById(R.id.perfil_genero_txt);

            perfilDocument.put("userId", currentView[0].getCredentialsProvider().getCachedIdentityId());
            perfilDocument.put("nome", perfilNome.getText().toString());
            perfilDocument.put("datanasc", perfilDataNasc.getText().toString());
            perfilDocument.put("genero", perfilGenero.getText().toString());

            Document perfilInserido = perfilTable.putItem(perfilDocument);

            if (perfilInserido.containsKey("genero")) {
                DynamoDBEntry perfilInseridoGenero = perfilInserido.get("genero");

                if (perfilInseridoGenero != null) {
                    if (perfilInseridoGenero.asString().equals(perfilGenero.getText().toString())) {
                        Snackbar
                                .make(
                                        currentView[0].getView(),
                                        "Perfil atualizado!",
                                        Snackbar.LENGTH_LONG
                                )
                                .setAction("Atualizar", null)
                                .show();
                    }
                }
            }

            return perfilTable;
        } catch (Exception e) {
            Log.e("EXCEPTION", e.getMessage(), e);
            return null;
        }
    }
}

The exception is thrown inside doInBackground method, at the line: Table perfilTable = Table.loadTable(dbClient, TABLE); 在以下行中的doInBackground方法内引发了异常: Table perfilTable = Table.loadTable(dbClient, TABLE);

What am I missing? 我想念什么?

As AWS Developer Forums' user awsvbk answered to me: 当AWS开发人员论坛的用户awsvbk回答我时:

You need to invoke the execute() method as opposed to the doInBackground() method. 您需要调用execute()方法,而不是doInBackground()方法。 Calling execute() will internally call the doInBackground() method of AsyncTask in a background thread. 调用execute()将在内部线程中内部调用AsyncTask的doInBackground()方法。

 new Insert().execute(<PARAMS>) 

If you still face any other issue with the DynamoDB Document Model SDK, please cut us an issue on GitHub on https://github.com/aws/aws-sdk-android 如果您仍然遇到DynamoDB文档模型SDK的其他问题,请在https://github.com/aws/aws-sdk-android上的GitHub上解决我们的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javax.xml.stream.XMLStreamException 在调用 amazonSQS.deleteMessage(queueURL,receiptHandle) 时抛出异常 - javax.xml.stream.XMLStreamException exception being thrown while calling amazonSQS.deleteMessage(queueURL, receiptHandle) 为什么要执行其他路线代码? - Why other route code being executed? 为什么 https 在 AWS Elastic Beanstalk 上被阻止? - Why is https being blocked on AWS Elastic Beanstalk? 当Scala Spark应用程序引发异常时,为什么AWS EMR步骤不会失败 - Why AWS EMR step is not failed when exception from Scala Spark app thrown 为什么在AWS中没有触发setTransferListener? - Why isn't setTransferListener being triggered in AWS? 为什么在异步 promise 中计算变量两次? - Why is variable being calculated twice in an async promise? 为什么未在 CloudFormation Stack 中创建此安全组? - Why this Security Group is not being created in CloudFormation Stack? 为什么我的 AWS CloudWatch 警报没有被触发? - Why is my AWS CloudWatch alarm not being triggered? 将csv写入具有直接在存储桶中的信誉的s3 - write csv into s3 having creds for being directly inside bucket 为什么 lambda 更新“进行中”和“正在创建”而不是“成功”? - Why are lambda updates "in progress" and "being created" instead of "successful"?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM