Я работаю над разработкой приложения для Android.В Activity будет две вкладки.Каждая из вкладок представляет собой отдельные фрагменты.Я извлекаю некоторые данные JSON с сервера в задаче Async и устанавливаю эти данные в TextView макета фрагмента.
Пока я понимаю, что для достижения этой цели мне нужно заменить фрагмент в основной деятельности.Я получаю следующую ошибку при запуске приложения.
java.lang.IllegalStateException: Can't change container ID of fragment MutualFunds{ed3a1c0 #0 id=0x7f080096}: was 2131230870 now 2131230812
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:422)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:444)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:434)
at com.testappl.ivest.ICLProducts.changefrag(ICLProducts.java:234)
at com.testappl.ivest.ICLProducts$JsonTask.onPostExecute(ICLProducts.java:207)
at com.testappl.ivest.ICLProducts$JsonTask.onPostExecute(ICLProducts.java:101)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
Вот мой фрагмент Класс активности:
package com.testappl.ivest;
import android.app.FragmentManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.testappl.ivest.model.FundMaster;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link MutualFunds.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link MutualFunds#newInstance} factory method to
* create an instance of this fragment.
*/
public class MutualFunds extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String ARG_PARAM3 = "param3";
private static final String ARG_PARAM4 = "param4";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String mParam3;
private String mParam4;
private static View view;
private OnFragmentInteractionListener mListener;
TextView mBFLabel;
TextView mBFDefintion;
TextView mBFCurrentNAV;
TextView mBFCurrentReturn;
TextView mGFLabel;
TextView mGFDefinition;
TextView mGFCurrentNAV;
TextView mGFCurrentReturn;
public MutualFunds() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MutualFunds.
*/
// TODO: Rename and change types and number of parameters
public static MutualFunds newInstance(String param1, String param2,String param3,String param4) {
MutualFunds fragment = new MutualFunds();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
args.putString(ARG_PARAM3, param3);
args.putString(ARG_PARAM4, param4);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
mParam3=getArguments().getString(ARG_PARAM3);
mParam4=getArguments().getString(ARG_PARAM4);
}
if(savedInstanceState==null){
Fragment MutualFundFragment=new Fragment();
getFragmentManager().beginTransaction().
add(R.id.fragment_mutual_funds,MutualFundFragment,
"mutual_fund_tag").commit();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_mutual_funds, container, false);
mBFLabel=view.findViewById(R.id.fund_name_bf);
mBFDefintion=view.findViewById(R.id.fund_definition_bf);
mBFCurrentNAV=view.findViewById(R.id.current_nav_bf);
mBFCurrentReturn=view.findViewById(R.id.current_return_bf);
mBFLabel.setText(mParam1);
mBFDefintion.setText(mParam2);
mGFLabel=view.findViewById(R.id.fund_name_gf);
mGFDefinition=view.findViewById(R.id.fund_definition_gf);
mGFCurrentNAV=view.findViewById(R.id.current_nav_gf);
mGFCurrentReturn=view.findViewById(R.id.current_return_gf);
mGFLabel.setText(mParam3);
mGFDefinition.setText(mParam4);
return inflater.inflate(R.layout.fragment_mutual_funds, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
//Change the texts of Balanced Fund
public void changeBFTexts(FundMaster fm){
mBFLabel.setText(fm.getFundName());
mBFDefintion.setText(fm.getFundDefinition());
}
//Change the texts of Growth Fund
public void changeGFTexts(FundMaster fm){
mGFLabel.setText(fm.getFundName());
mGFDefinition.setText(fm.getFundDefinition());
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Вот мой макет фрагмента
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MutualFunds"
android:id="@+id/fragment_mutual_funds">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fund_name_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="28dp"
android:text="@string/mutualfundfrag_iclbf_title"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/fund_definition_bf"
android:layout_width="319dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:text="@string/mutualfundfrag_iclbf_definition"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fund_name_bf" />
<TextView
android:id="@+id/current_nav_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="@string/mutualfundfrag_iclbf_current_nav"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fund_definition_bf" />
<TextView
android:id="@+id/current_return_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="@string/mutualfundfrag_iclbf_current_return"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/current_nav_bf" />
<TextView
android:id="@+id/fund_performance_bf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="@string/mutualfundfrag_iclbf_fund_performance"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/current_return_bf" />
<TextView
android:id="@+id/fund_name_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="28dp"
android:text="@string/mutualfundfrag_bcbiclgf_title"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fund_performance_bf" />
<TextView
android:id="@+id/fund_definition_gf"
android:layout_width="315dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="@string/mutualfundfrag_bcbiclgf_definition"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fund_name_gf" />
<TextView
android:id="@+id/current_nav_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="@string/mutualfundfrag_iclbf_current_nav"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fund_definition_gf" />
<TextView
android:id="@+id/current_return_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="@string/mutualfundfrag_iclbf_current_return"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/current_nav_gf" />
<TextView
android:id="@+id/fund_performance_gf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:text="@string/mutualfundfrag_iclbf_fund_performance"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/current_return_gf" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
Вот родительское действие, где есть асинхронная задача и фрагмент будет заменен:
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
try {
JSONArray resultJsonArray = new JSONArray(result);
ArrayList<FundMaster> fundsData=new ArrayList<FundMaster>();
for(int i=0;i<resultJsonArray.length();i++){
JSONObject jsonObject= (JSONObject) resultJsonArray.get(i);
fundsData.add(new FundMaster(Integer.valueOf(jsonObject.get("f_id").toString()),
Integer.valueOf(jsonObject.get("fund_id").toString()),
jsonObject.get("fund_name").toString(),
jsonObject.get("fund_definition").toString(),
jsonObject.get("fund_date").toString()));
}
for(FundMaster fm:fundsData){
Log.d("Fund Name",fm.getFundName());
Log.d("Fund Launch Date",fm.getFundLaunchDate());
//MutualFunds mf=new MutualFunds();
//View view=fragment.getView();
if(mutualFundFragment!=null) {
if (fm.getFundId() == 1) {
mutualFundFragment.changeBFTexts(fm);
} else if (fm.getFundId() == 2) {
mutualFundFragment.changeGFTexts(fm);
}
} else{
Log.e("Message Error","Error");
}
changefrag(mutualFundFragment);
}
} catch (JSONException e){
Log.e("JSON Error","JSON problem");
}
}
}
public void changefrag(android.support.v4.app.Fragment frag) {
FragmentManager manager = getSupportFragmentManager();
if (!manager.beginTransaction().isEmpty()) {
manager.beginTransaction().detach(frag);
}
manager.beginTransaction()
.replace(R.id.fragment_mutual_funds, frag).commit();
}
Насколько я понимаю, статический фрагмент не может быть заменен.Кто-нибудь может подсказать мне, что мне делать в этом случае?Заранее спасибо.