试图上传到Dropbox:NetworkOnMainThreadException?

时间:2022-05-12 16:03:43

I have been fighting for like 6 hours with this now. I have followed Dropbox's "tutorials" (if they can be called that, because they are awfully poor), played with the DBRoulette example, and done tons of stuff to get my app working.

我现在已经和他一起战斗了6个小时。我已经关注了Dropbox的“教程”(如果它们可以被称为,因为它们非常差),使用DBRoulette示例,并完成了大量的工作以使我的应用程序正常工作。

My app can Authenticate with no problems. But I can't upload anything despite doing exactly what the tutorial is doing:

我的应用程序可以正确验证。但是,尽管完成了教程正在做的事情,但我无法上传任何内容:

This is the little snippet of code I have (this is to save a created note on the phone itself and then upload to Dropbox):

这是我的一小段代码(这是为了在手机上保存创建的笔记,然后上传到Dropbox):

        saveBtn.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            try
            {
                //Create the directory if it doesn't exist. If it does exist the next two line won't do anything.
                File dropNotesDir = new File(Environment.getExternalStorageDirectory() + "/documents/AppData/Dropnotes/");
                dropNotesDir.mkdirs();
                //-----------------------------------------------------------------------------------------------
                String wholeNoteString = noteBody.getText().toString();
                //Now we create the title of the txt file. It will be the first line of the whole note. The name will get truncated to 32 characters
                //if it's too long.
                String noteTitle;
                if(wholeNoteString.indexOf("\n") >= 0) //New line character found.
                {
                    noteTitle = wholeNoteString.substring(0, wholeNoteString.indexOf("\n"));
                    if(noteTitle.length() >= 32)
                    {
                        noteTitle = wholeNoteString.substring(0, 32);
                    }
                }
                else
                {
                    if(wholeNoteString.length() >= 32)
                    {
                        noteTitle = wholeNoteString.substring(0, 32);
                    }else
                    {
                        noteTitle = wholeNoteString;
                    }
                }
                if(extras.getString("file-mode").equals("modify"))
                {
                    //We will need to delete the existing file if it does exist to save the new one.
                    File existing = new File(Environment.getExternalStorageDirectory() + "/documents/AppData/Dropnotes/" + extras.getString("noteTitle"));
                    existing.delete();
                }
                File newNote = new File(Environment.getExternalStorageDirectory() + "/documents/AppData/Dropnotes/" + noteTitle + ".txt");
                PrintWriter newNoteWriter = new PrintWriter(new FileOutputStream(newNote));
                newNoteWriter.print(noteBody.getText().toString());
                newNoteWriter.close();

                //TRYING TO UPLOAD TO DROPBOX HERE
                File fileToUpload = new File(Environment.getExternalStorageDirectory() + "/documents/AppData/Dropnotes/" + noteTitle + ".txt");
                FileInputStream file2Uis = new FileInputStream(fileToUpload);
                Entry newEntry = mDBApi.putFile("/" + noteTitle + ".txt", file2Uis, fileToUpload.length(), null, null);
                //END OF TRYING TO UPLOAD TO DROPBOX HERE

                Toast.makeText(view.getContext(), "Saved successfully", Toast.LENGTH_SHORT).show();
                finish();
            } catch (FileNotFoundException e)
            {
                Toast.makeText(view.getContext(), "File not found: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            } catch(Exception e)
            {
                Toast.makeText(view.getContext(), "Some bizarre exception occured: " + e.getClass().toString(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }

    });

It's giving me a NetworkOnMainThreadException and I don't know why. I'm trying to follow the section titled "Uploading a File" here. What baffles me about their snippet is that they are not even trying to catch the exception I'm getting thrown at...

它给了我一个NetworkOnMainThreadException,我不知道为什么。我正在尝试按照标题为“上传文件”的部分进行操作。令他感到困惑的是他们的片段是他们甚至没有试图抓住我被抛出的例外......

Any help? I really need to get this working for next Friday.

有帮助吗?我真的需要在下周五开始工作。

2 个解决方案

#1


7  

Prior to Honeycomb SDK, it was allowed to perform network operation on the main thread. However, with Honeycomb, it is no longer allowed and a NetworkOnMainThreadException is thrown if a network operation is attempted in main/UI thread.

在Honeycomb SDK之前,允许在主线程上执行网络操作。但是,使用Honeycomb时,如果在main / UI线程中尝试进行网络操作,则不再允许它并抛出NetworkOnMainThreadException。

You need to perform network operations in a different thread. You can take a look at AsyncTask to achieve the same.

您需要在不同的线程中执行网络操作。你可以看看AsyncTask来实现同样的目的。

#2


-4  

My guess is, the error caused by StrictMode.ThreadPolicy. you can't access network in the same UI thread.

我的猜测是,StrictMode.ThreadPolicy引起的错误。您无法在同一UI线程中访问网络。

try adding these lines to your code in oncreate

尝试将这些行添加到oncreate中的代码中

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy);

#1


7  

Prior to Honeycomb SDK, it was allowed to perform network operation on the main thread. However, with Honeycomb, it is no longer allowed and a NetworkOnMainThreadException is thrown if a network operation is attempted in main/UI thread.

在Honeycomb SDK之前,允许在主线程上执行网络操作。但是,使用Honeycomb时,如果在main / UI线程中尝试进行网络操作,则不再允许它并抛出NetworkOnMainThreadException。

You need to perform network operations in a different thread. You can take a look at AsyncTask to achieve the same.

您需要在不同的线程中执行网络操作。你可以看看AsyncTask来实现同样的目的。

#2


-4  

My guess is, the error caused by StrictMode.ThreadPolicy. you can't access network in the same UI thread.

我的猜测是,StrictMode.ThreadPolicy引起的错误。您无法在同一UI线程中访问网络。

try adding these lines to your code in oncreate

尝试将这些行添加到oncreate中的代码中

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy);