In my application I'm using pageviewer with two tabs. In each tab I populate view with some data after calling aysnctask. Also the fragment which contains these tab and viewpager have filter in it which filter the content of my view accordingly. Also I'm using Recycleview for populating data. On click of item of recycleview I open new fragment. The problem I'm facing is that when app is open first time , after data when I open my fragment on click events using getsupportFragmentmanager it working fine But when I change my data content using filter, when I click on item to open fragment using getsupportFragmentmanager it gives me following error.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
ParentFragment code is here :
public class TabB extends Fragment {
ViewPager viewPager;
TabLayout tabLayout;
Clubs clubs = new Clubs();
Events events = new Events();
private static RecyclerView Genre;
private RecyclerView.LayoutManager mLayoutManager;
public static JSONArray jsonArrayResult = new JSONArray();
public static final String[] IMAGE_NAME = {"allevent", "rock", "jazz", "house", "bass", "chill","bollywood","commerial", "karaoke","sufi"};
ArrayList<Integer> arrayList = new ArrayList<>();
public static String Genrename = IMAGE_NAME[0];
public static GenreAdapter genreAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.tabb, container, false);
viewPager = (ViewPager) RootView.findViewById(R.id.viewpager);
tabLayout = (TabLayout) RootView.findViewById(R.id.tabs);
Genre = (RecyclerView)RootView.findViewById(R.id.rvImages);
for (int i=0;i< IMAGE_NAME.length;i++){
String imageFileName = IMAGE_NAME[i];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "in.catalystapp.catalyst");
arrayList.add(imgResId);
}
mLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL, false);
Genre.setLayoutManager(mLayoutManager);
genreAdapter = new GenreAdapter(arrayList, getActivity());
Genre.setAdapter(genreAdapter);
TabBviewPagerAdapter tabBviewPagerAdapter = new TabBviewPagerAdapter(getChildFragmentManager(),"allevent");
viewPager.setAdapter(tabBviewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
genreAdapter.SetOnItemClickListener(new GenreAdapter.OnItemClickListener() {
#Override
public void OnItemClick(View view, int position) {
FilterGenres( IMAGE_NAME[position], new PageviewCaller() {
#Override
public void PopulatePageViewer(String key) {
Log.d("key", key);
clubs.PopulateClubList(key);
events.FilterEvents(key);
}
});
}
});
return RootView;
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void FilterGenres(String key,PageviewCaller pageviewCaller){
pageviewCaller.PopulatePageViewer(key);
}
one of child frgament code is here :
public class Clubs extends Fragment {
static ArrayList<ClubItem> mClubItems = new ArrayList<>();
static RecyclerView Clubcards;
static RecyclerView.LayoutManager layoutManager;
static ClubsAdapter clubsAdapter;
static Context context;
public String mKey;
Parcelable liststate;
static JSONArray jsonClubs = new JSONArray();
public Clubs(){}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.clubs, container, false);
Log.d("clubs-life-cycle","oncreate");
Clubcards = (RecyclerView)RootView.findViewById(R.id.clubcard);
context = getActivity();
Bundle args = getArguments();
mKey = args.getString("key");
new GetClubDetails().execute();
return RootView;
}
#Override
public void onPause() {
Log.d("liststate", "saving listview state # onPause");
liststate = layoutManager.onSaveInstanceState();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
if (liststate != null){
layoutManager.onRestoreInstanceState(liststate);
} else {
}
}
public class GetClubDetails extends AsyncTask<String,Void,Void> {
JSONObject jsonresult = new JSONObject();
ProgressDialog progressDialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Fetching Feeds....");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
RESTfulAPI resTfulAPI = new RESTfulAPI();
jsonresult = resTfulAPI.getJSONfromurl("api/clubs/","GET","");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
super.onPostExecute(aVoid);
if (jsonresult!=null){
Log.d("json", jsonresult.toString());
try {
jsonClubs = jsonresult.getJSONArray("datasets");
PopulateClubList("allevent");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void PopulateClubList(String key){
mClubItems = new ArrayList<>();
clubsAdapter = null;
for (int i=0;i < jsonClubs.length();i++){
try {
if (key.equals("allevent") || key.equals(jsonClubs.getJSONObject(i).getString("genre")) ){
mClubItems.add(new ClubItem(jsonClubs.getJSONObject(i).getString("clubName"),jsonClubs.getJSONObject(i).getString("address")));
clubsAdapter = new ClubsAdapter(mClubItems,context);
layoutManager = new LinearLayoutManager(context);
Clubcards.setLayoutManager(layoutManager);
Clubcards.setAdapter(clubsAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
clubsAdapter.SetOnItemClickListener(new ClubsAdapter.OnItemClickListener() {
#Override
public void OnItemClick(View view, int position) {
getActivity().getSupportFragmentManager().beginTransaction().setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out).add(R.id.main_content, new Clubdetails()).addToBackStack(null).commit();
}
});
}
What I'm Doing Wrong?
This May cause Because You are Importing different version of Fragment.
Because there are two types of Fragment.
1 android.support.v4.app.Fragment
and
2 android.app.Fragment;
Make sure you're importing the same Fragment in each Fragmnet class or Activities.
Could you try to use getFragmentManager() instead of getSupportFragmentManager() ?
Maybe it due to your version of appcompat library
Related
Please find me to solve this issue , i have a list of image url in a json api ,list url api is calling from background task and after compliting called notify method its not showing
but the Recyclerview doesn't refresh - only if I go back and reopen the activity - the new data is shown.
So how can I notify the adapter that there's new data to display?
1.WallpaperFragmentAdapter.java
public class WallpaperFragmentAdapter extends Fragment {
List<WallpaperMain> wallpaperList = new ArrayList<WallpaperMain>();
WallPaperAdapter wallPaperAdapter;
#Bind(R.id.recyclerView)
RecyclerView recyclerView;
private int tabId ;
public void settabId(int tabId){
this.tabId=tabId;
}
public static Fragment newInstance(Context context) {
WallpaperFragmentAdapter f = new WallpaperFragmentAdapter();
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.content_main, null);
setUpView(root);
return root;
}
void setUpView(ViewGroup root){
ButterKnife.bind(this, root);
setUPList();
}
void setUPList(){
new WallPaperListDownlaoderTask().execute("http://localhost:8080/api/motivation/wallpaper/wallpaper");
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),3);
wallPaperAdapter = new WallPaperAdapter(wallpaperList,getActivity());
recyclerView.setAdapter(wallPaperAdapter);
recyclerView.setLayoutManager(gridLayoutManager);
System.out.println(wallPaperAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent;
intent = new Intent(getActivity(), WallpaperDeatilsActivity.class);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
class WallPaperListDownlaoderTask extends AsyncTask<String,Integer,JSONArray> {
OkHttpClient client = new OkHttpClient();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... params) {
String url =params[0];
Request request = new Request.Builder()
.url(url)
.build();
try{
Response response = client.newCall(request).execute();
String apiResponseString=response.body().string();
System.out.println("response.body().toString() ---- "+apiResponseString );
JSONArray jsonArray = new JSONArray(apiResponseString);
List<WallpaperMain> wallpaperMains = new ArrayList<>();
for(int index =0;index<jsonArray.length();index++){
try {
JSONObject wallpaperMainsJsonObj = jsonArray.getJSONObject(index);
WallpaperMain wallpaperMain = new WallpaperMain();
wallpaperMain.setId(wallpaperMainsJsonObj.getInt("id"));
Wallpaper wallpaper = new Wallpaper();
JSONObject wallpaperJsonObj = wallpaperMainsJsonObj.getJSONObject("wallpaper");
wallpaper.setLarge(wallpaperJsonObj.getString("large"));
wallpaperMain.setWallpaper(wallpaper);
wallpaperMains.add(wallpaperMain);
} catch (JSONException e) {
e.printStackTrace();
}
}
wallpaperList =wallpaperMains;
return null;
}catch (IOException e){
Log.v("",e.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
System.out.println(wallPaperAdapter);
wallPaperAdapter.notifyDataSetChanged();
recyclerView.setAdapter(wallPaperAdapter);
System.out.println(wallpaperList.size());
}
}
}
2.WallPaperAdapter.java
public class WallPaperAdapter extends RecyclerView.Adapter<WallPaperAdapter.MyViewHolder>{
private List<WallpaperMain> wallpaperMains;
private Context context;
public WallPaperAdapter(List<WallpaperMain> wallpaperMains,Context context){
this.wallpaperMains =wallpaperMains;
this.context=context;
}
#Override
public WallPaperAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.wallpaper_item, null);
WallPaperAdapter.MyViewHolder viewHolder = new WallPaperAdapter.MyViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Glide.with(context)
.load("http://localhost:8080/api/motivation/wallpaper/large/37l")
.into(holder.waIlpapermageView);
// holder.waIlpapermageView.setImageResource(R.drawable.name);
}
#Override
public int getItemCount() {
return wallpaperMains.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView waIlpapermageView;
public MyViewHolder(View itemView) {
super(itemView);
waIlpapermageView =(ImageView) itemView.findViewById(R.id.wallpaperItem_imageView);
}
}
}
OUTPUT I am getting bellow
In your doInBackground method , instead of
wallpaperList = wallpaperMains;
use
wallpaperList.clear();
wallpaperList.addAll(wallpaperMains);
In onPostExecute()
#Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
System.out.println(wallPaperAdapter);
wallPaperAdapter.notifyDataSetChanged();
System.out.println(wallpaperList.size());
}
Try this...
Please clear your Arraylist before adding the values wallpaperList.clear(); On onPreExecute() method.
recyclerView.setAdapter(wallPaperAdapter);
wallPaperAdapter.notifyDataSetChanged();
Whenever your ArrayList value is changing usenotifyDataSetChanged(); it will refresh your Recylierview
I display pictures from moviesdb using volley in a gridview. The next step is have that gridview in the landscape mode too. So my logic behind this,is to store the list that contains the data as key value pair inside the onSaveInstantState method as:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("movies", moviesList);
outState.putStringArrayList("images", images);
Log.v("TAG","list size:" + moviesList.size());
}
The log output gives me a size of 20 which is correct. However when I am using the debugger, the line
outState.putParcelableArrayList("movies", moviesList);
gives me an empty bundle. That's very strange! The images list works fine,and can see what's in there. Any ideas what is wrong?
Here is my code.
public class MainFragment extends Fragment {
String BASE_URL = "http://api.themoviedb.org/3/discover/movie?api_key=my_key";
static public ArrayList<Movie> moviesList;
static public ArrayList<String> images;
static public MovieAdapter movieAdapter;
public static String imageIcon;
ImageView imageView;
static public String lastSortOrder;
static GridView gridview;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null) {
moviesList = savedInstanceState.getParcelableArrayList("movies");
images = savedInstanceState.getStringArrayList("images");
}else{
moviesList = new ArrayList<>();
images = new ArrayList<>();
movieAdapter = new MovieAdapter(getActivity());
updateMovies();
}
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
moviesList = new ArrayList<>();
images = new ArrayList<>();
gridview = (GridView) rootView.findViewById(R.id.gridview);
int ot = getResources().getConfiguration().orientation;
gridview.setNumColumns(ot == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2);
gridview.setAdapter(movieAdapter);
return rootView;
}
private void updateMovies(){
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
BASE_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray moviesArray = response.getJSONArray("results");
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject movie = moviesArray.getJSONObject(i);
Movie movieItem = new Movie();
movieItem.setTitle(movie.getString("title"));
movieItem.setId(movie.getInt("id"));
movieItem.setBackdrop_path(movie.getString("backdrop_path"));
movieItem.setOriginal_title(movie.getString("original_title"));
movieItem.setOriginal_language(movie.getString("original_language"));
if (movie.getString("overview") == "null") {
movieItem.setOverview("No Overview was Found");
} else {
movieItem.setOverview(movie.getString("overview"));
}
if (movie.getString("release_date") == "null") {
movieItem.setRelease_date("Unknown Release Date");
} else {
movieItem.setRelease_date(movie.getString("release_date"));
}
movieItem.setPopularity(movie.getString("popularity"));
movieItem.setVote_average(movie.getString("vote_average"));
movieItem.setPoster_path(movie.getString("poster_path"));
if (movie.getString("poster_path") == "null") {
movieItem.setPoster_path(API.IMAGE_NOT_FOUND);
} else {
images.add(API.IMAGE_URL + API.IMAGE_SIZE_185 + movie.getString("poster_path"));
}
moviesList.add(movieItem);
Log.v("TAG","list size:" + moviesList.size());
movieAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("movies", moviesList);
outState.putStringArrayList("images", images);
//Log.v("TAG","list size:" + moviesList.size());
}
}
Thanks,
Theo.
I have a Fragment that is used to retrieve some data from my CMS with the help of the Volley lib. I am using RecyclerViews to do that. It works. However when I am rotating the screen,the webservice is run again. How can I stop that? I tried to use **setRetainInstance(true); but at no vail. From what I have read,this method bypasses the onDestroy() fragment's method,and hence the onCreate() fragment's method is not called when you rotate the screen. If I am wrong with that please correct me. Here is my code.
FeaturesActivity
public class FeaturesActivity extends AppCompatActivity {
private static final String FEATURES_FRAGMENT = "Features_fragment";
FeaturesFragment ff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_features);
FragmentManager fragmentManager = getSupportFragmentManager();
ff = (FeaturesFragment) fragmentManager.findFragmentByTag(FEATURES_FRAGMENT);
if(ff == null) {
ff = new FeaturesFragment();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(android.R.id.content, ff);
fragmentTransaction.commit();
}
}
}
And the actual fragment itself.
public class FeaturesFragment extends Fragment {
public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "http://xxx/xxx/features_images/" ;
private List<FeaturesObject> listItemsList;
private RecyclerView mRecyclerView;
private FeaturesAdapter adapter;
public FeaturesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Log.v("retained","oncreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_features, container, false);
// Inflate the layout for this fragment
listItemsList = new ArrayList<>();
mRecyclerView = (RecyclerView)v.findViewById(R.id.features_recycler_view);
//mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateFeaturesList();
}
public void updateFeaturesList() {
//declare the adapter and attach it to the recyclerview
adapter = new FeaturesAdapter(getActivity(), listItemsList);
mRecyclerView.setAdapter(adapter);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Request a string response from the provided URL.
JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FEATURES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
//hidePD();
// Parse json data.
// Declare the json objects that we need and then for loop through the children array.
// Do the json parse in a try catch block to catch the exceptions
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = response.getJSONObject(i);
FeaturesObject item = new FeaturesObject();
item.setTitle(post.getString("title"));
item.setImage(IMAGE_URL + post.getString("features_image"));
item.setArticle(post.getString("article"));
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Update list by notifying the adapter of changes
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//hidePD();
}
});
queue.add(jsObjRequest);
}
}
I logged out a message inside the onCreate(...),but it is called even if I rotate the screen. How can I fix that?
Thanks.
I fixed it using the following code inside the manifest.xml file
android:configChanges="screenSize|orientation"
Google though states that we should use that as a resourse.
I am trying to set a string to a textview but everytime i click the button Quiz the activity is just refreshing instead going to fragment activity.
This summarize the situation.
I have dynamic viewPager inside activity called Quiz_Container
Use only one fragment(Module_Topics_Content_Quiz) in public Fragment getItem(int position) or FragmentStatePagerAdapter.
I want to change text of a textview in the fragment from activity everytime i swipe.
I am passing the string using newInstance with parameter from activity to fragment
The string came from quizQuestion.get(position)
I'm getting the right value with the Log.d but when setting it to textview the activity is just refreshing.
this is my code.
Quiz_Container.java
public class Quiz_Container extends AppCompatActivity implements Module_Topics_Content_Quiz.OnFragmentInteractionListener {
android.support.v7.app.ActionBar actionBar;
ViewPager quizPager;
private int topicID;
private int moduleID;
private int subModuleID;
private ArrayList<Integer> quizID;
private ArrayList<String> quizQuestion;
private ArrayList<String> choiceA;
private ArrayList<String> choiceB;
private ArrayList<String> choiceC;
private ArrayList<String> choiceD;
private ArrayList<String> quizAnswer;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz__container);
actionBar = getSupportActionBar();
actionBar.setTitle("Quiz");
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f1ad1e")));
Bundle extras = getIntent().getExtras();
topicID = extras.getInt("topicID");
moduleID = extras.getInt("moduleID");
subModuleID = extras.getInt("subModuleID");
Log.d("quizTopicID", "" + topicID);
Log.d("quizModuleID", "" + moduleID);
Log.d("quizSubModuleID", "" + subModuleID);
new quizTask().execute();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
} // Check Internet Connection
class quizTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
try {
URL quizURL = new URL("http://192.168.1.110/science/index.php/users/get_quiz_items/" + topicID + "/" + moduleID + "/" + subModuleID + "" );
HttpURLConnection con = (HttpURLConnection)quizURL.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String quizResponse;
while ((quizResponse = reader.readLine()) != null) {
return quizResponse;
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#Override
protected void onPostExecute(String quizResponses) {
Log.d("quizResponse", "" + quizResponses);
try {
JSONObject quizObject = new JSONObject(quizResponses);
boolean result = quizObject.getBoolean("success");
if (result) {
JSONArray quizArray = quizObject.getJSONArray("data");
quizID = new ArrayList<>();
quizQuestion = new ArrayList<>();
choiceA = new ArrayList<>();
choiceB = new ArrayList<>();
choiceC = new ArrayList<>();
choiceD = new ArrayList<>();
quizAnswer = new ArrayList<>();
for (int i = 0; i < quizArray.length(); i ++) {
JSONObject dataQuiz = quizArray.getJSONObject(i);
quizID.add(dataQuiz.getInt("id"));
quizQuestion.add(dataQuiz.getString("question"));
choiceA.add(dataQuiz.getString("a"));
choiceB.add(dataQuiz.getString("b"));
choiceC.add(dataQuiz.getString("c"));
choiceD.add(dataQuiz.getString("d"));
quizAnswer.add(dataQuiz.getString("answer"));
}
Log.d("quizSize", "" + quizID.size());
quizPager = (ViewPager) findViewById(R.id.quizPager);
fragmentManager = Quiz_Container.this.getSupportFragmentManager();
quizPager.setAdapter(new quizAdapter(getSupportFragmentManager()));
quizPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
else {
Toast.makeText(getApplication(), "no quiz yet", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} // end of quizTask
class quizAdapter extends FragmentStatePagerAdapter {
public quizAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
for (int i = 0; i < quizID.size; i++) {
if (i == position) {
fragment = Module_Topics_Content_Quiz.newInstance(quizQuestion.get(position));
Log.d("testQuestion", "" + quizQuestion.get(position)); // this code is working
}
}
return fragment;
}
#Override
public int getCount() {
return quizID.size();
}
}
}
Module_Topics_Content_Quiz.java
public class Module_Topics_Content_Quiz extends Fragment {
TextView textQuizQuestion;
private String qQuestion;
public Module_Topics_Content_Quiz() {
// Required empty public constructor
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public static Module_Topics_Content_Quiz newInstance(String question) {
Module_Topics_Content_Quiz fragment = new Module_Topics_Content_Quiz();
Bundle args = new Bundle();
args.putString("question", question);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
qQuestion = getArguments().getString("question");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
textQuizQuestion = (TextView) getActivity().findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
// textQuizQuestion.setText(qQuestion); // error if enable
return rootView;
}
}
Please help. Thank you.
In your fragment, try inflating the TextView using the View returned rather than using getActivity()
You need to inflate the Fragment's view and call findViewById() on the View it returns.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
// inflate the View inside Fragment using the View returned
textQuizQuestion = (TextView) rootView.findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
textQuizQuestion.setText(qQuestion);
return rootView;
}
You can also use getView() from within the Fragment to get the root view.
If you wanna call from the enclosing Activity, use
getFragmentManager().findFragmentById(R.id.your_fragment_id).getView().findViewById(R.id.your_view);
In my app there is a fragment class (TabFragmentComerTiposRestaurante). It has also two tab fragments in it (Case 0: PrimaryFragmentComerTiposRestaurante, Case 1: SocialFragmentComerTiposRestaurante).
On both fragment classes there is a listview. When clicking on an item from this list, another fragment class is shown (PrimaryFragmentComer.
Shorty this the schema:
TabFragmentComerTiposRestaurante(#F1)
-[PrimaryFragmenComerTiposRestaurante](#F11)--[PrimaryFragmentComer](#F111)
-[SocialFragmentComerTiposRestaurante](#F12)--[SocialFragmentComer](#F121)
The issue I need to solve is the following:
If at (#F111) or at (#F121) the users click on the back button, then the listview items from #F11 and #F12 are loaded again. That means, if on the first #F11 call there is an item called "Cocina americana", then going back from #F111 to #F11 or going back from #F121 to #F12, there are now two equal items: First row=Cocina americana, Second row=Cocina americana. And that happens every time the user goes from #F11 or #F12 to #F111 or #F112.
Here you can find the code for
F1:
public class TabFragmentComerTiposRestaurante extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout_tipo_rte,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragmentComerTiposRestaurante();
case 1 : return new SocialFragmentComerTiposRestaurante();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "CIUDAD JUAREZ";
case 1 :
return "EL PASO";
}
return null;
}
}
}
Code for #F11
public class PrimaryFragmentComerTiposRestaurante extends Fragment implements AdapterView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "..hiddene here";
private ProgressDialog pDialog;
private List<TipoRestaurante> tipoRestauranteList = new ArrayList<TipoRestaurante>();
private ListView listView;
private CustomListAdapterTipoRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_tiporte, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterTipoRte (getActivity(), tipoRestauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando tipos..");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
Log.d("estoy aqui","estoy");
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
TipoRestaurante restaurante = new TipoRestaurante();
restaurante.setId_tipo(obj.getInt("id_tipo"));
restaurante.setNombre_tipo(obj.getString("nombre_tipo"));
restaurante.setFoto_tipo(obj.getString("foto_tipo"));
Log.d(TAG, response.toString());
// adding movie to movies array
tipoRestauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_tipo"));
// pDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Fragment newFragment = new PrimaryFragmentComer();
Bundle args = new Bundle();
args.putInt("myIntLabel", 2);
args.putString("myStringLabel", rteActual.getNombre_tipo());
//and you can add all you want to that bundle like this
newFragment.setArguments(args);
if (mListener != null) {
mListener.onFragmentInteraction(newFragment);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Fragment fragment);
}
}
And now code for #F111:
public class PrimaryFragmentComer extends Fragment implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "...hidden here";
private ProgressDialog pDialog;
private List<Restaurante> restauranteList = new ArrayList<Restaurante>();
private ListView listView;
private CustomListAdapterRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_comer, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
Bundle args = getArguments();
String hola = args.getString("myStringLabel");
Log.d("TIPO RTE", hola);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterRte (getActivity(), restauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando restaurantes...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url+hola,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Restaurante restaurante = new Restaurante();
restaurante.setId_rte(obj.getInt("id_rte"));
restaurante.setNombre(obj.getString("nombre_rte"));
restaurante.setDescripcion(obj.getString("descripcion_rte"));
restaurante.setLatitud(obj.getDouble("latitud_rte"));
restaurante.setLongitud(obj.getDouble("longitud_rte"));
restaurante.setDireccion(obj.getString("direccion_rte"));
restaurante.setWeb(obj.getString("web_rte"));
restaurante.setTel_rte(obj.getString("tel_rte"));
restaurante.setTel_reservas(obj.getString("tel_reservas"));
restaurante.setFoto(obj.getString("foto_rte"));
restaurante.setCalificacion(obj.getDouble("calificacion_rte"));
restaurante.setTipo_rte(obj.getString("tipo_rte"));
restaurante.setFacebook(obj.getString("facebook_rte"));
restaurante.setTwitter(obj.getString("google_rte"));
restaurante.setZona(obj.getString("zona_rte"));
restaurante.setCiudad(obj.getInt("ciudad"));
restaurante.setPoi(obj.getInt("poi"));
// adding movie to movies array
restauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_rte"));
// pDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Restaurante rteActual = (Restaurante) adapter.getItem(position);
String msg = "Elegiste el restaurante " + rteActual.getNombre();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), Detalle_Restaurante.class);
intent.putExtra("id_rte", rteActual.getId_rte());
intent.putExtra("nombre_rte", rteActual.getNombre());
intent.putExtra("descripcion_rte", rteActual.getDescripcion());
intent.putExtra("latitud_rte", rteActual.getLatitud());
intent.putExtra("longitud_rte", rteActual.getLongitud());
intent.putExtra("direccion_rte", rteActual.getDireccion());
intent.putExtra("web_rte", rteActual.getWeb());
intent.putExtra("tel_rte", rteActual.getTel_rte());
intent.putExtra("tel_reservas", rteActual.getTel_reservas());
intent.putExtra("foto_rte", rteActual.getFoto());
intent.putExtra("calificacion_rte", rteActual.getCalificacion());
intent.putExtra("tipo_rte", rteActual.getTipo_rte());
intent.putExtra("facebook_rte", rteActual.getFacebook());
intent.putExtra("google_rte", rteActual.getTwitter());
intent.putExtra("zona_rte", rteActual.getZona());
intent.putExtra("ciudad_rte", rteActual.getCiudad());
intent.putExtra("poi_rte", rteActual.getPoi());
startActivity(intent);
}
}
As mentioned in the comment,
Data is being readded to tipoRestauranteList in your onResponse() method so to avoid that write tipoRestauranteList.clear() after hidePDialog().
Same will be happening in your #F12. Doing this you can rectify the same. :)