У меня есть еще один фрагмент, где эта функция работает. Но когда я получаю ответ от сервера, программа падает и возвращает это исключение. Я новичок в Android, поэтому я не очень понимаю смысл и функции инструментов навигации. Я не знаю, нужен ли другой файл для решения, кстати, вы можете попросить опубликовать другие подробности.
Обновлено: я обнаружил, что проблема в том, что я пытался изменить фрагмент другим потоком. Я обычно получаю эту ошибку при работе с javaFX. есть ли какая-нибудь функция, похожая на "Platform.runlater()"???
РЕШЕНО:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.action_LoginFragment_to_FirstFragment);
}
});
на Фрагменте:
@Override
public void onResponse(Call call, Response response) throws IOException {
String sessione = "";
String email = "";
try {
String msg = response.body().string();
JSONObject obj = new JSONObject(msg);
sessione = obj.getString("message");
if (sessione.equals("sessione esistente")) {
email = obj.getString("email");
NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.action_LoginFragment_to_FirstFragment);
//intent.putExtra("user", email);
//startActivity(intent);
}
Looper.prepare();
Toast.makeText(getContext(), sessione, Toast.LENGTH_SHORT).show();
Looper.loop();
} catch (JSONException e) {
System.out.println("Errore onResponse ----> " + e.getMessage());
Toast.makeText(getContext(), sessione, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}});
nav_graph.xml:
<?xml version = "1.0" encoding = "utf-8"?>
<navigation xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/nav_graph"
app:startDestination = "@id/FirstFragment">
<fragment
android:id = "@+id/FirstFragment"
android:name = "com.example.progetto.FirstFragment"
android:label = "@string/first_fragment_label"
tools:layout = "@layout/fragment_first">
<action
android:id = "@+id/action_FirstFragment_to_SecondFragment"
app:destination = "@id/SecondFragment"/>
</fragment>
<fragment
android:id = "@+id/SecondFragment"
android:name = "com.example.progetto.SecondFragment"
android:label = "@string/second_fragment_label"
tools:layout = "@layout/fragment_second">
<action
android:id = "@+id/action_SecondFragment_to_FirstFragment"
app:destination = "@id/FirstFragment"/>
</fragment>
<fragment
android:id = "@+id/nav_home"
android:name = "com.example.progetto.FirstFragment"
android:label = "@string/menu_home"
tools:layout = "@layout/fragment_first">
</fragment>
<fragment
android:id = "@+id/nav_login"
android:name = "com.example.progetto.LoginFragment"
android:label = "@string/login"
tools:layout = "@layout/activity_login_page">
<action
android:id = "@+id/action_LoginFragment_to_FirstFragment"
app:destination = "@id/FirstFragment"/>
</fragment>
<fragment
android:id = "@+id/nav_myLesson"
android:name = "com.example.progetto.myLesson.myLessonFragment"
android:label = "@string/menu_myLesson"
tools:layout = "@layout/fragment_my_lesson">
</fragment>
</navigation>
В Android, если вы хотите, чтобы часть кода выполнялась в основном потоке, вы можете использовать область сопрограммы с контекстом диспетчера как MAIN. например -
CoroutineScope(Dispatchers.Main).launch {
stuffYouWantOnTheMainThread()
}
Это запустит код в основном потоке независимо от того, находится ли этот код в другом потоке.