Different ways of instantiating a fragment - android

In the below code, I would like to know the difference between instantiating a static fragment as shown in code_1 below.
I posted the code of the fragment as shown in code_2 section below.
please let me know the difference between the two types of instantiaition, and when to use each of them.
code_1:
StudentMVCView mStudentMVCViewInitializedInstance = (StudentMVCView) this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
Fragment mStudentMVCViewFragmentInitializedInstance = this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
code_2:
public class StudentMVCView extends Fragment implements View.OnClickListener{
private final static String TAG_LOG = StudentMVCView.class.getSimpleName();
private View mMainView = null;
private TextView mTextViewValue = null;
private EditText mEditTextValue = null;
private Button mBtn = null;
private TextView mTextViewBtnValue = null;
private StudentMVCModel mStudentMVCModel = null;
private int counter = 1;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG_LOG, "onCreateView");
this.mMainView = inflater.inflate(R.layout.mvc_view_layout, null);
this.mTextViewValue = this.mMainView.findViewById(R.id.mvc_view_textView_value);
this.mEditTextValue = this.mMainView.findViewById(R.id.mvc_view_editText_value);
this.mBtn = this.mMainView.findViewById(R.id.mvc_view_button);
this.mBtn.setOnClickListener(this);
this.mTextViewBtnValue = this.mMainView.findViewById(R.id.mvc_view_textView_btnValue);
return this.mMainView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.v(TAG_LOG, "onViewCreated");
view.findViewById(R.id.mvc_view_textView_value);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v(TAG_LOG, "onActivityCreated");
Bundle bundledArgs = this.getArguments();
StudentMVCModel studentMVCModel = (StudentMVCModel) this.getSerializedfromBundle(bundledArgs, "p");
Log.v(TAG_LOG, "studentMVCModel.getStudentId()" + studentMVCModel.getStudentId());
this.setStudentMVCModelObject(studentMVCModel);
}
private void setStudentMVCModelObject(StudentMVCModel studentMVCModel) {
this.mStudentMVCModel = studentMVCModel;
}
private StudentMVCModel getStudentMVCModelObject() {
return this.mStudentMVCModel;
}
private Bundle getBundledArguments() {
Log.d(TAG_LOG, "getBundledArguments");
if (this.getArguments() !=null) {
return this.getArguments();
} else {
Log.e(TAG_LOG, "this.getArguments() is NULL.");
throw new NullPointerException("getArguments is NULL");
}
}
private Object getSerializedfromBundle(Bundle bundle, String key) {
Log.d(TAG_LOG, "getSerializedfromBundle");
if (bundle != null) {
return bundle.get(key);
} else {
Log.e(TAG_LOG, "bundle is NULL.");
throw new NullPointerException("bundle is null");
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v(TAG_LOG, "onDestroy");
}
public void setStudentIdToView(int id) {
if (this.mMainView != null) {
TextView textView = this.mMainView.findViewById(R.id.mvc_view_textView_value);
Log.v(TAG_LOG, "TextView contains: " + textView.getText().toString());
}
}
public void setTextViewValueFor(int id) {
if (this.mTextViewValue != null) {
this.mTextViewValue.setText("" + id);
} else {
Log.e(TAG_LOG, "setTextViewValueFor is NULL.");
}
}
public void setEditTextValueFor(String str) {
if (this.mEditTextValue != null) {
this.mEditTextValue.setText(str);
} else {
Log.e(TAG_LOG, "mEditTextValue is NULL.");
}
}
public void clearEditText() {
if (this.mEditTextValue != null) {
this.mEditTextValue.setText("");
} else {
Log.e(TAG_LOG, "mEditTextValue is NULL.");
}
}
#Override
public void onClick(View v) {
int id = this.getStudentMVCModelObject().getStudentId();
Log.i(TAG_LOG, "onClick: id: " + id + " counter: " + counter++);
}
}

In the first line You're casting the fragment to StudentMVCView type, so you're able to access extra members added to it like setTextViewValueFor(int id), setEditTextValueFor(String str), ..etc
StudentMVCView mStudentMVCViewInitializedInstance = (StudentMVCView) this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
In the second line you're getting the fragment as it's super type which is the Android framework's Fragment type, in this case you can't access these extra members in StudentMVCView type
Fragment mStudentMVCViewFragmentInitializedInstance = this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);

Related

IndexOutOfBoundException while reading from Cursor

I'm trying to use a CursorLoader but keep getting an IndexOutOfBounds error when reading from the Cursor. Relevant error lines from Logcat:
at com.codephillip.app.busticket.SelectRouteFragment.onLoadFinished(SelectRouteFragment.java:96)
at com.codephillip.app.busticket.SelectRouteFragment.onLoadFinished(SelectRouteFragment.java:28)
This is the fragment class:
public class SelectRouteFragment extends Fragment implements MaterialSpinner.OnItemSelectedListener, LoaderManager.LoaderCallbacks {
private static final String TAG = SelectRouteFragment.class.getSimpleName();
private MaterialSpinner destSpinner;
private MaterialSpinner sourceSpinner;
private Button selectButton;
private String destination;
private String source;
public SelectRouteFragment() {
}
public static SelectRouteFragment newInstance() {
return new SelectRouteFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_select_route, container, false);
destSpinner = rootView.findViewById(R.id.dest_spinner);
sourceSpinner = rootView.findViewById(R.id.source_spinner);
destSpinner.setOnItemSelectedListener(this);
sourceSpinner.setOnItemSelectedListener(this);
selectButton = rootView.findViewById(R.id.select_button);
selectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (source.equals(destination)) {
Toast.makeText(getContext(), "Choose a different Destination", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getContext(), BookActivity.class);
intent.putExtra(Utils.SOURCE, source);
intent.putExtra(Utils.DESTINATION, destination);
getActivity().startActivity(intent);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(2, null, this);
}
#Override
public Loader onCreateLoader(int id, Bundle args) {
return new CursorLoader(getContext(), LocationsColumns.CONTENT_URI, null, null, null, null);
}
#Override
public void onLoadFinished(Loader loader, Cursor data) {
Log.d(TAG, "onLoadFinished: started");
LocationsCursor cursor = new LocationsCursor(data);
List locations = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
locations.add(cursor.getName());
} while (cursor.moveToNext());
}
// Set default route values
source = locations.get(0);
destination = locations.get(0);
ArrayAdapter dataAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_expandable_list_item_1, locations);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sourceSpinner.setAdapter(dataAdapter);
destSpinner.setAdapter(dataAdapter);
}
#Override
public void onLoaderReset(Loader loader) {
}
#Override
public void onItemSelected(MaterialSpinner view, int position, long id, Object itemObject) {
Snackbar.make(view, "Clicked " + itemObject.toString(), Snackbar.LENGTH_LONG).show();
String item = itemObject.toString();
Log.d(TAG, "onItemSelected: " + item);
if (view.getId() == destSpinner.getId()) {
Log.d(TAG, "onItemSelected: clicked dest");
destination = item;
} else {
Log.d(TAG, "onItemSelected: clicked source");
source = item;
}
}
}
Any help understanding the issue would be greatly appreciated.
I guess the issue is happening here:
source = locations.get(0);
destination = locations.get(0);
If cursor is empty, locations will also be empty and then, locations.get(0) will throw an exception.
You should check if location is not empty.
if(locations.size() > 0) {
...
}

Problem with detail activity screen loading. It keeps on loading without stopping

I have a problem with my detail activity layout screen. The details in the screen are showing but the screen loading does not stop after that. I need help to stop my screen loading after the details in the screen has been shown.
The main layout activity loads for a certain amount of time and it works fine but the detail activity layout keeps on loading without stopping.
DetailsFragment.java
public class DetailsFragment extends Fragment {
private static final String LOG_TAG = DetailsFragment.class.getSimpleName();
private static final String ARG_NEWS = "arg_news";
private static final String SAVE_NEWS = "save_news";
private static final String SAVE_FAVORITE_NEWS = "save_favorite_news";
private static final String SAVE_FAVORITE_SORT = "save_favorite_sort";
private static final String SAVE_FULLY_LOADED = "save_fully_loaded";
private static final String SAVE_SHARE_MENU_VISIBILITY = "save_share_menu_visibility";
private final ResponseReceiver mReceiver = new ResponseReceiver();
private Context mContext;
private News mNews;
private ShareActionProvider mShareActionProvider;
private MenuItem mShareMenuItem;
private ImageView mPosterImageView;
private OnLoadingFragmentListener mLoadingListener;
private boolean mIsFavoriteNews;
private boolean mIsFavoriteSort;
private boolean mIsFullyLoaded;
private boolean mIsShareMenuItemVisible;
public DetailsFragment() {
// Required empty public constructor
}
// Create new Fragment instance
public static DetailsFragment newInstance(News newsSelected) {
DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_NEWS, newsSelected);
fragment.setArguments(args);
return fragment;
}
public static DetailsFragment newInstance() {
DetailsFragment fragment = new DetailsFragment();
return fragment;
}
// Listener to handle star button clicks. This button adds and remove news from
// content provider
private final View.OnClickListener mStarButtonOnClickListener = new View.OnClickListener() {
public void onClick(View view) {
// Can't save it to favorites db if news poster is not ready yet
if (mPosterImageView != null && !Utils.hasImage(mPosterImageView)) {
Toast.makeText(mContext, R.string.please_wait_poster_download,
Toast.LENGTH_SHORT).show();
return;
}
if (mIsFavoriteNews) {
if (removeFavoriteNews(mNews) > 0) {
Toast.makeText(mContext, R.string.success_remove_favorites, Toast
.LENGTH_SHORT)
.show();
((ImageButton) view).setImageResource(R.drawable.ic_star_border);
// Delete poster image stored in internal storage
Utils.deleteFileFromInternalStorage(mContext, mNews.getTitle());
mIsFavoriteNews = false;
} else {
Toast.makeText(mContext, R.string.fail_remove_favorites,
Toast.LENGTH_SHORT).show();
}
} else {
if (addFavoriteNews(mNews) != null) {
Toast.makeText(mContext, R.string.success_add_favorites, Toast
.LENGTH_SHORT).show();
((ImageButton) view).setImageResource(R.drawable.ic_star);
// Save poster image to internal storage
Bitmap posterBitmap = Utils.getBitmapFromImageView(mPosterImageView);
Utils.saveBitmapToInternalStorage(mContext, posterBitmap, mNews.getTitle());
mIsFavoriteNews = true;
} else {
Toast.makeText(mContext, R.string.fail_add_favorites, Toast
.LENGTH_SHORT).show();
}
}
}
};
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnLoadingFragmentListener) {
mLoadingListener = (OnLoadingFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnLoadingInteractionListener");
}
mContext = context;
}
#Override
public void onDetach() {
super.onDetach();
mLoadingListener = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mNews = getArguments().getParcelable(ARG_NEWS);
mIsFavoriteNews = isFavoriteNews(mContext, mNews);
mIsFavoriteSort = Utils.isFavoriteSort(mContext);
}
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.details_menu, menu);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
mShareMenuItem = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider
(mShareMenuItem);
setShareMenuItemAction();
super.onPrepareOptionsMenu(menu);
}
private void setShareMenuItemAction() {
if (mNews != null ) {
//String videoKey = mNews.getVideos()[0].getKey();
if (mShareActionProvider != null
&& mShareMenuItem != null) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
mShareActionProvider.setShareIntent(shareIntent);
mShareMenuItem.setVisible(true);
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(SAVE_NEWS, mNews);
outState.putBoolean(SAVE_FAVORITE_NEWS, mIsFavoriteNews);
outState.putBoolean(SAVE_FAVORITE_SORT, mIsFavoriteSort);
outState.putBoolean(SAVE_FULLY_LOADED, mIsFullyLoaded);
outState.putBoolean(SAVE_SHARE_MENU_VISIBILITY, mIsShareMenuItemVisible);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (mNews == null) {
return null;
}
// Restore objects value
if (savedInstanceState != null) {
mNews = savedInstanceState.getParcelable(SAVE_NEWS);
mIsFavoriteNews = savedInstanceState.getBoolean(SAVE_FAVORITE_NEWS);
mIsFavoriteSort = savedInstanceState.getBoolean(SAVE_FAVORITE_SORT);
mIsFullyLoaded = savedInstanceState.getBoolean(SAVE_FULLY_LOADED);
mIsShareMenuItemVisible = savedInstanceState.getBoolean(SAVE_SHARE_MENU_VISIBILITY);
}
View view = inflater.inflate(R.layout.fragment_details, container, false);
mPosterImageView = (ImageView) view.findViewById(R.id.news_img);
Glide.with(mContext).load(mNews.getImageUri())
.dontAnimate().into(mPosterImageView);
TextView titleView = (TextView) view.findViewById(R.id.title_content);
titleView.setText(mNews.getTitle());
TextView publishDateView = (TextView) view.findViewById(R.id.publish_date_content);
String date = Utils.formatDateForLocale(mNews.getPublishedDate());
publishDateView.setText(date);
TextView author = (TextView) view.findViewById(R.id.author_name);
author.setText(mNews.getAuthor());
TextView descriptionView = (TextView) view.findViewById(R.id.description_content);
TextView fullNewsUrl = (TextView) view.findViewById(R.id.news_full);
fullNewsUrl.setText(mNews.getFullNewsUrl());
// In portuguese, some news does not contain overview data. In that case, displays
// default text: #string/overview_not_available
if (!TextUtils.isEmpty(mNews.getDescription())) {
descriptionView.setText(mNews.getDescription());
}
ImageButton starButton = (ImageButton) view.findViewById(R.id.star_button);
starButton.setOnClickListener(mStarButtonOnClickListener);
if (mIsFavoriteNews) {
starButton.setImageResource(R.drawable.ic_star);
} else {
starButton.setImageResource(R.drawable.ic_star_border);
}
starButton.setVisibility(View.VISIBLE);
FrameLayout detailFrame = (FrameLayout) view.findViewById(R.id.detail_frame);
detailFrame.setVisibility(View.VISIBLE);
return view;
}
// Method that adds a News to content provider
private Uri addFavoriteNews(News news) {
Uri newsReturnUri = null;
try {
ContentValues newsContentValues = createNewsValues(news);
newsReturnUri = mContext.getContentResolver().insert(FavoriteNewsContract
.NewsEntry
.CONTENT_URI, newsContentValues);
} catch (SQLException e) {
Log.d(LOG_TAG, "SQLException while adding news to Favorite db");
e.printStackTrace();
}
return newsReturnUri;
}
// Method that removes a News from content provider
private int removeFavoriteNews(News news) {
int newsRemoved = mContext.getContentResolver().delete(FavoriteNewsContract
.NewsEntry.CONTENT_URI,
FavoriteNewsContract
.NewsEntry._ID + " = ?", new String[]{news.getTitle()});
return newsRemoved;
}
// Create news content values
private ContentValues createNewsValues(News news) {
ContentValues newsContentValues = new ContentValues();
// newsContentValues.put(FavoriteNewsContract.NewsEntry._ID, Integer.parseInt(news
// .getId()));
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_TITLE, news.getTitle());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_PUBLISH_DATE, news
.getPublishedDate());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_AUTHOR, news
.getAuthor());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_DESCRIPTION, news
.getDescription());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_FULL_NEWS_URL, news
.getFullNewsUrl());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_IMG_URL, news
.getImageUri()
.toString());
return newsContentValues;
}
// Method that query content provider and checks whether is a Favorite news or not
private boolean isFavoriteNews(Context ctx, News news) {
String newsID = news.getTitle();
Cursor cursor = ctx.getContentResolver().query(FavoriteNewsContract.NewsEntry
.CONTENT_URI, null,
FavoriteNewsContract.NewsEntry._ID + " = " + newsID, null, null);
if (cursor != null && cursor.moveToNext()) {
int newsIdColumnIndex = cursor.getColumnIndex(FavoriteNewsContract.NewsEntry._ID);
if (TextUtils.equals(newsID, cursor.getString(newsIdColumnIndex))) {
return true;
}
}
if (cursor != null) {
cursor.close();
}
return false;
}
#Override
public void onResume() {
super.onResume();
if (mNews != null) {
if (mReceiver != null) {
LocalBroadcastManager.getInstance(mContext)
.registerReceiver(mReceiver, new IntentFilter(Constants
.ACTION_EXTRA_INFO_RESULT));
}
if (!mIsFullyLoaded && !mIsFavoriteSort) {
Intent intent = new Intent(mContext, NewsIntentService.class);
intent.setAction(Constants.ACTION_EXTRA_INFO_REQUEST);
intent.putExtra(NewsIntentService.EXTRA_INFO_NEWS_ID, mNews.getTitle());
mContext.startService(intent);
if (mLoadingListener != null) {
mLoadingListener.onLoadingDisplay(true, true);
}
}
}
}
#Override
public void onPause() {
super.onPause();
if (mReceiver != null) {
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
}
}
// BroadcastReceiver for network call
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getAction() == null) {
return;
}
if (intent.getAction().equals(Constants.ACTION_EXTRA_INFO_RESULT)) {
setShareMenuItemAction();
} else {
Toast.makeText(mContext, R.string.toast_failed_to_retrieve_data,
Toast.LENGTH_SHORT).show();
}
if (mLoadingListener != null) {
mLoadingListener.onLoadingDisplay(true, false);
}
mIsFullyLoaded = true;
}
}
}
DetailsActivity.java
public class DetailsActivity extends AppCompatActivity implements OnLoadingFragmentListener {
private static final String LOG_TAG = DetailsActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
if (savedInstanceState == null) {
Intent intent = getIntent();
if (intent != null && intent.hasExtra(Constants.EXTRA_NEWS)) {
News news = intent
.getParcelableExtra(Constants.EXTRA_NEWS);
DetailsFragment detailsFragment = DetailsFragment.newInstance(news);
getSupportFragmentManager().beginTransaction()
.add(R.id.details_fragment_container, detailsFragment).commit();
} else {
Log.d(LOG_TAG, "Something went wrong. Intent doesn't have Constants.EXTRA_NEWS" +
" extra. Finishing DetailsActivity.");
finish();
}
}
}
#Override
public void onLoadingDisplay(boolean fromDetails, boolean display) {
Fragment loadingFragment = getSupportFragmentManager()
.findFragmentByTag(LoadingFragment.FRAGMENT_TAG);
if (display && loadingFragment == null) {
loadingFragment = LoadingFragment.newInstance();
if (fromDetails) {
getSupportFragmentManager().beginTransaction()
.add(R.id.details_fragment_container,
loadingFragment, LoadingFragment.FRAGMENT_TAG).commit();
} else {
getSupportFragmentManager().beginTransaction()
.add(R.id.news_fragment_container,
loadingFragment, LoadingFragment.FRAGMENT_TAG).commit();
}
} else if (!display && loadingFragment != null) {
getSupportFragmentManager().beginTransaction()
.remove(loadingFragment).commit();
}
}
}
LoadingFragment.xml
public class LoadingFragment extends Fragment {
public static final String FRAGMENT_TAG = LoadingFragment.class.getSimpleName();
private static final String LOG_TAG = LoadingFragment.class.getSimpleName();
public LoadingFragment() {
// Required empty public constructor
}
public static LoadingFragment newInstance() {
LoadingFragment fragment = new LoadingFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_loading, container, false);
return view;
}
}
fragment_loading.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/semiTransparentBlack"
android:clickable="true"
tools:context=".ui.LoadingFragment">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center" />
</FrameLayout>
Most likely you need to change the loading View (ProgressBar?) visibility to INVISIBLE or GONE at the appropriate time, probably when loading is complete.
If the loading View is contained in some kind of dialog, then you would need to dismiss it at the appropriate time.
use onDestroy
#Override
public void onDestroy() {
super.onDestroy();
mLoadingListener = null;
}
and also you should remove ResponseReceiver
if (mLoadingListener != null) {
mLoadingListener.onLoadingDisplay(true, false);
}

set text value from fragment.newInstance String

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);

Android getActivity().setTitle() gets String field from wrong object in ArrayList

I wish to set the titlebar in this fragment's activity to the HelpItem's description field.
On line 10, I set the title of the activity with a String representing a HelpItem's description.
Instead of getting the description of the retrieved HelpItem on line 9 I get the description of the next HelpItem.
I.E. in an ArrayList of five HelpItem objects with the helpDescriptions "aaa", "bbb", "ccc", "ddd", "eee" clicking on "bbb" in the
list displays "bbb" and the information text associated with it. The title is set to "ccc".
On line 19 the same call to helpItem.getHelpDescription() returns the description field of the "bbb" object.
When moving through the list via a ViewPager the next object in the list has the same issue until I reach the end of the list,
where the correct helpDescription field is displayed. I can also move back to the start of the list and it will display the correct
helpDescription, but this is then lost when I move forward and backward through the list again.
Any ideas why this is happening? Thanks.
public class HelpFragment extends Fragment {
private HelpItem helpItem;
private TextView mHelpDetails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
UUID helpItemId = (UUID) getArguments().getSerializable(EXTRA_HELP_ITEM_ID);
helpItem = HelpList.get(getActivity()).getHelpItem(helpItemId);
getActivity().setTitle(helpItem.getHelpDescription());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View userView = inflater.inflate(R.layout.fragment_help_item, parent, false);
mHelpDetails = (TextView) userView.findViewById(R.id.help_details);
String displayInfo = "";
if ((helpItem.getHelpDescription() != null) &&
(helpItem.getHelpInformation() != null)) {
displayInfo = helpItem.getHelpDescription() + "\n\n\n" +
helpItem.getHelpInformation();
mHelpDetails.setText(displayInfo);
Log.d(TAG, "3 " + helpItem.getHelpDescription() + " "
+ helpItem.getHelpInformation());
}
return userView;
}
}
..
public class HelpItem {
private UUID mId;
private String helpDescription;
private String helpInformation;
public HelpItem(String hDesc, String hInfo) {
mId = UUID.randomUUID();
helpDescription = hDesc;
helpInformation = hInfo;
}
public UUID getId() {
return mId;
}
public void setId(UUID id) {
mId = id;
}
#Override
public String toString() {
return helpDescription;
}
public String getHelpDescription() {
return helpDescription;
}
public void setHelpDescription(String hDescription) {
this.helpDescription = hDescription;
}
public String getHelpInformation() {
return helpInformation;
}
public void setHelpInformation(String hInformation) {
this.helpInformation = hInformation;
}
}
..
public class HelpListItemPagerActivity extends FragmentActivity {
private ViewPager mViewPager;
private ArrayList<HelpItem> mHelpList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewPager);
setContentView(mViewPager);
mHelpList = HelpList.get(this).getHelpList();
FragmentManager fragManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragManager) {
#Override
public int getCount() {
return mHelpList.size();
}
#Override
public Fragment getItem(int position) {
HelpItem hItem = mHelpList.get(position);
return HelpFragment.newInstance(hItem.getId());
}
});
UUID helpItemId = (UUID)getIntent().getSerializableExtra(HelpFragment.EXTRA_HELP_ITEM_ID);
for (int i = 0; i < mHelpList.size(); i++) {
if (mHelpList.get(i).getId().equals(helpItemId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}

Android DialogFragment views don't get updated when I call show method with explicit setText calls

I'm trying to create a fragment that, when shown, changes it's content based on an extra item I pass on the show() method. The dialog fragment instance is kept for reusability, in other words, I just instantiate the fragment once and call show() with the new object it displays whenever I want it to be displayed. It works fine for the first time it is shown, but for subsequent calls to show, I just can't change the text of the edit texts. You'll see in my class below that I've actually explicitly made the text to be changed to "I was changed" after the show() code block, but this never reflects in the ui.
public class RegisterFragment extends DialogFragment implements View.OnClickListener, DialogInterface.OnClickListener
{
private static final String KEY_SOURCE = "source";
private static String source;
private static JSONObject listEntry;
private RegisterItem item;
private boolean spinnerMode;
private boolean viewsCreated;
private TextView label1, label2;
private EditText field1 = null, field2 = null;
private Spinner spinner;
private ArrayAdapter<String> adapter;
private Button send, cancel;
private OnClickSendCancelButtonListener sendListener;
public static RegisterFragment newInstance(String source)
{
RegisterFragment fragment = new RegisterFragment();
Bundle b = new Bundle();
b.putString(KEY_SOURCE, source);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = this.getArguments();
if (b != null)
{
source = b.getString(KEY_SOURCE);
load(source);
}
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
viewsCreated = false;
}
public RegisterItem getRegisterItem()
{
return this.item;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
this.sendListener = (OnClickSendCancelButtonListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException("Activity must implement RegisterFragment#OnClickSendCancelButtonListener");
}
}
private void load(String source)
{
if (item == null)
item = new RegisterItem();
item.loadData(source);
spinnerMode = item.hasChoices();
if (!viewsCreated)
return;
label1.setText(item.field1Label);
label2.setText(item.field2Label);
send.setText(item.sendButtonText);
cancel.setText(item.cancelButtonText);
Log.v("RegisterFragment", "FIELD1: " + item.defaultField1);
Log.v("RegisterFragment", "FIELD2: " + item.defaultField2);
if (spinnerMode)
{
field1.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
adapter.clear();
for(String choice: item.choices)
adapter.add(choice);
adapter.notifyDataSetChanged();
}
else
{
field1.setVisibility(View.VISIBLE);
spinner.setVisibility(View.GONE);
}
if (item.hasDefaults())
{
Log.v("RegisterFragment", "Setting text for field 2");
field2.setText(item.defaultField2);
Log.v("RegisterFragment", "FIELD2 TEXT: " + field2.getText().toString());
if (spinnerMode)
spinner.setSelection(adapter.getPosition(item.defaultField2));
else
field1.setText(item.defaultField1);
}
}
public void show(FragmentManager manager, String tag, String source, String listEntry)
{
Log.v("Register Fragment", "Showing fragment\nSOURCE STRING: " + source);
load(source);
RegisterFragment.source = source;
try {
RegisterFragment.listEntry = new JSONObject(listEntry);
} catch (JSONException e) {
e.printStackTrace();
}
super.show(manager, tag);
if (field2 != null)
field2.setText("I Have Been Changed");
}
#Override
public void dismiss()
{
if (field1 != null)
field1.setText("");
if (field2 != null)
field2.setText("");
super.dismiss();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.register_screen, null);
spinner = (Spinner) v.findViewById(R.id.register_spinner);
spinner.setAdapter(adapter);
label1 = (TextView) v.findViewById(R.id.register_label1);
label2 = (TextView) v.findViewById(R.id.register_label2);
field1 = (EditText) v.findViewById(R.id.register_field1);
field2 = (EditText) v.findViewById(R.id.register_field2);
send = (Button) v.findViewById(R.id.register_send);
cancel = (Button) v.findViewById(R.id.register_cancel);
send.setOnClickListener(this);
cancel.setOnClickListener(this);
viewsCreated = true;
load(source);
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
viewsCreated = false;
}
}
Your code should have worked . But do try this.
EditText text = (EditText)getDialog().findViewById(R.id.register_field2);
text.setText("I have been changed");

Categories

Resources