【问题标题】:Trying To Upload To Dropbox: NetworkOnMainThreadException?尝试上传到 Dropbox:NetworkOnMainThreadException?
【发布时间】:2012-06-05 06:48:20
【问题描述】:

我已经为此奋斗了 6 个小时。 我遵循了 Dropbox 的“教程”(如果可以这样称呼的话,因为它们非常糟糕),玩过 DBRoulette 示例,并做了很多事情来让我的应用程序正常运行。

我的应用可以毫无问题地进行身份验证。但我无法上传任何内容,尽管完全按照教程的方式进行操作:

这是我的小sn-p代码(这是在手机上保存创建的笔记,然后上传到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();
            }
        }

    });

它给了我一个 NetworkOnMainThreadException,我不知道为什么。我正在尝试遵循标题为“上传文件”here 的部分。他们的 sn-p 让我感到困惑的是,他们甚至没有试图捕捉我被抛出的异常......

有什么帮助吗?我真的需要在下周五完成这项工作。

【问题讨论】:

  • 你得到NetworkOnMainThreadException,因为你在主线程上做网络工作......使用AsyncTask
  • Why Ice Cream Sandwich Crashes Your App。看看...它解释了为什么会发生这种情况。

标签: android dropbox dropbox-api


【解决方案1】:

在 Honeycomb SDK 之前,允许在主线程上执行网络操作。但是,对于 Honeycomb,如果在主/UI 线程中尝试网络操作,则不再允许这样做,并且会抛出 NetworkOnMainThreadException

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

【讨论】:

  • 谢谢。明天我会试试你的解决方案。我现在被打败了,但看起来这是正确的做法。
  • 抱歉拖了太久。我不得不寻找一个教程来做到这一点,但我做到了。非常感谢您的帮助。
【解决方案2】:

我的猜测是,由 StrictMode.ThreadPolicy 引起的错误。你不能在同一个 UI 线程中访问网络。

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

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

【讨论】:

  • 这个政策是有某些原因的......这个解决方案很糟糕,m'kay
  • 只是出于好奇,为什么这个答案被否决了?这不是正确的方法吗?换句话说,一个非常糟糕的选择?
  • 哈,Selvin 的评论直到现在才加载。我现在明白了。谢谢塞尔文!
  • @Sergio from Rajesh answer你可以去developer.android.com/guide/practices/design/… ...然后你就会知道如果主线程在5秒内没有响应你会得到ANR ...所以你可以获得ANR很容易当没有可用的网络(或信号很弱)时,这就是为什么你不应该在主线程上使用网络操作(即使它在 API
猜你喜欢
  • 1970-01-01
  • 2015-11-01
  • 2019-12-18
  • 2017-06-12
  • 2017-08-21
  • 1970-01-01
  • 2013-12-29
  • 2019-10-16
相关资源
最近更新 更多