Я сейчас сражаюсь за 6 часов. Я следил за «учебниками» Dropbox (если их можно назвать так, потому что они ужасно бедны), играемый с примером DBRoulette, и сделал массу вещей, чтобы заставить мое приложение работать.Пытается загрузить в Dropbox: NetworkOnMainThreadException?
Мое приложение может аутентифицироваться без проблем. Но я ничего не могу загрузить несмотря делать именно то, что делает учебник:
Это маленький фрагмент кода, у меня есть (это, чтобы сохранить созданную записку на самом телефоне, а затем загрузить на 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. Что меня озадачивает об их фрагменте, так это то, что они даже не пытаются поймать исключение. Меня забрасывают ...
Любая помощь? Мне действительно нужно, чтобы это работало в следующую пятницу.
вы получаете 'NetworkOnMainThreadException', потому что вы делаете сетевые материалы в основной теме ... используйте AsyncTask – Selvin
** [Почему сэндвич с мороженым падает с вашего приложения] (http://www.androiddesignpatterns.com/2012/06/ приложение сила, близкая сотовая ics.html) **. Проверьте это ... это объясняет, почему это может произойти. –