1) Когда приложение запускается в ландшафтном режиме, после создания фрагмента A начинается формирование фрагмента B с помощью метода response () mainActivity. И после того, как он заканчивается и его видимость проверяется, вызывается changeData (index). Но ArrayList объектов во FragmentB является нулевым, когда вызывается метод changeData.
2) Также не работает переход из пейзажа в портрет или наоборот. Соответствующие макеты работают в репрезентативной ориентации, но во время перехода приложение закрывается.
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentA.Communicator{
FragmentB f2;
ArrayList<Book> b = new ArrayList<Book>();
FragmentManager manager;
static int flag = 0;
static String search="great";
SearchView sv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (SearchView) findViewById(R.id.searchView);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
flag = 1;
search = query;
getBooks();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
getBooks();
return false;
}
});
// TODO - add logic to auto-select first book in list to display in details fragment when running in landscape mode
// TODO - add logic to figure out whether app is displaying in landscape or poortrait mode to accomplish ^^
getBooks();
/*
manager = getSupportFragmentManager();
f1 = (FragmentA) manager.findFragmentById(R.id.fragment);
f1.setCommunicator(this);*/
}
@Override
public void respond(int index) {
/*Bundle args = new Bundle();
args.putSerializable("book_b_array", (ArrayList<Book>) b);
args.putInt("someInt",index);
*/
//f2.setArguments(args);
Bundle args = new Bundle();
args.putSerializable("book_b_array", (ArrayList<Book>) b);
args.putInt("someInt",index);
FragmentB f2 = (FragmentB) manager.findFragmentById(R.id.fragment2);
f2.setArguments(args);
/*FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment2,f2);
transaction.commit();*/
if(f2!=null && f2.isVisible())
{
f2.changeData(index);
}
else
{
Bundle bundle = new Bundle();
bundle.putInt("index", index);
bundle.putSerializable("bookarray",(ArrayList<Book>)b);
Fragment newFragment = new FragmentC();
newFragment.setArguments(bundle);
FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
transaction2.replace(R.id.fragment, newFragment);
transaction2.addToBackStack(null);
transaction2.commit();
}
}
public void afterGetBooks(ArrayList<Book> bks) {
b.clear();
for (Book h : bks) {
b.add(h);
}
manager = getSupportFragmentManager();
Bundle args = new Bundle();
args.putSerializable("bookarray",(ArrayList<Book>)bks);
FragmentA f1 = new FragmentA();
f1.setArguments(args);
FragmentTransaction transaction1 = manager.beginTransaction();
transaction1.replace(R.id.fragment,f1);
transaction1.addToBackStack(null);
transaction1.commit();
f1.setCommunicator(this);
}
private void getBooks(){
String url;
if(flag==0){
url = "https://kamorris.com/lab/audlib/booksearch.php/";}
else{
url = "https://kamorris.com/lab/audlib/booksearch.php?search=" + search;
flag=0;
}
//ArrayList<Book> boo;
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://kamorris.com/lab/audlib/booksearch.php/").addConverterFactory(GsonConverterFactory.create()).build();
Book.API api = retrofit.create(Book.API.class);
Call<ArrayList<Book>> call = api.getBooks(url);
call.enqueue(new Callback<ArrayList<Book>>() {
@Override
public void onResponse(Call<ArrayList<Book>> call, Response<ArrayList<Book>> response) {
ArrayList<Book> Books = response.body();
for(Book h: Books){
Log.d("Retro-Title",h.getTitle());
//b.add(h);
}
afterGetBooks(Books);
}
@Override
public void onFailure(Call<ArrayList<Book>> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
Fragmenta:
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{
ListView list;
Communicator communicator;
ArrayList<Book> book_a;
ArrayList<String> book_titles;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);
savedInstanceState = getArguments();
if (getArguments() != null) {
// savedInstanceState = getArguments();
book_a = (ArrayList<Book>) getArguments().getSerializable("bookarray");
book_titles = getList(book_a);
//Log.d("Frag_a:Title",book_a.get(5).getTitle());
list= (ListView) view.findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,book_titles);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
return view;
}
public ArrayList<String> getList(ArrayList<Book> book2){
ArrayList<String> list_titles = new ArrayList<String>();
int size = book2.size();
for(int i=0;i<size;i++){
Book object;
object = book2.get(i);
list_titles.add(object.title);
}
return list_titles;
}
public void setCommunicator(Communicator communicator)
{
this.communicator = communicator;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
communicator.respond(position);
}
public interface Communicator{
public void respond(int index);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof Communicator){
communicator = (Communicator) context;
} else {
throw new RuntimeException(context.toString()+"must implement Communicator");
}
}
@Override
public void onDetach() {
super.onDetach();
communicator = null;
}
}
FragmentB:
public class FragmentB extends Fragment {
private int page;
TextView text;
ArrayList<Book> book_b;
boolean fl=false;
public static FragmentB newInstance(ArrayList<Book> b,int page){
FragmentB f2 = new FragmentB();
Bundle args = new Bundle();
args.putSerializable("book_b_array",b);
args.putInt("someInt",page);
f2.setArguments(args);
return f2;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null){
book_b = (ArrayList<Book>) getArguments().getSerializable("book_b_array");
page = getArguments().getInt("someInt",0);
} else{ page = 0; fl=true;}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b,container,false);
text = (TextView) view.findViewById(R.id.textview);
changeData(page);
return view;
}
public void changeData(int index)
{
if(fl==false) {
String description = book_b.get(index).getTitle();
text.setText(description);
}
else{
text.setText("Select a Book to Display Data");
fl=false;
}
}
}