I'm currently getting a ClassCastException in my android app caused by "activity cannot be cast to interface".
Here is my code:
Logcat says the Exception is thrown in the onAttach part in MovieGridFragment on the line "this.clickListener = (clickInterfaceHelper) context;".
My Interface:
public interface clickInterfaceHelper {
void clickOnItem(int id);
void favoriteMovieItem(int movieId); }
The Fragment Class:
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private int index;
private GridView movieGridView;
public List<movieData> movieDataList = new ArrayList<>();
public MovieGridFragment() {} //empty constructor
#Override
public void onAttach(Context context) {
this.clickListener = (clickInterfaceHelper) context;
super.onAttach(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
if(savedInstanceState != null) {
if (!movieDataList.isEmpty()) {
movieDataList = Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA"));
}
}
super.onCreate(savedInstanceState);
}
The MainActivity:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
movieAdapter adapter = new movieAdapter(getActivity(),movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.setSelection(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(clickListener != null)
clickListener.clickOnItem(position);
}
});
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
index = movieGridView.getFirstVisiblePosition();
outState.putSerializable("OLDMOVIEDATA",movieData.movieDataArray);
super.onSaveInstanceState(outState);
}}
and mainactivity:
public class MainActivity extends AppCompatActivity implements clickInterfaceHelper {
public static String sorterString = null;
public static String urlBase = "https://api.themoviedb.org/3/movie/";
public static String urlFinal = null;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, new MovieGridFragment())
.commit();
movieData.movieDataPosition = 0;
}
if(savedInstanceState != null) {
sorterString = savedInstanceState.getString("SORTER");
}
if(savedInstanceState == null)
movieData.movieDataPosition = 0;
if(sorterString==null)
sorterString="popular?";
if(sorterString!="favorite" && sorterString!=null) {
if(networkChecker.isNetworkAvailableChecker(this)) {
movieRequest();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu_act, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.m_popularity_action) {
if(sorterString != "popular?") {
sorterString = "popular?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_action_voter) {
if(sorterString != "top_rated?") {
sorterString = "top_rated?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_favorite_btn) {
if(sorterString != "favorite") {
SQLiteOpenHelper helper = new movieDataDbHelper(this);
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor= database.query(movieDataContract.contractEntry.TABLE_NAME,
new String[] {
movieDataContract.contractEntry.ID,
movieDataContract.contractEntry.IMG_PATH},null,null,null,null,null);
if(cursor.getCount() == 0) {
Toast.makeText(this, "there are no favorite movies yet!",Toast.LENGTH_SHORT).show();
} else {
sorterString = "favorite";
showFavoriteFragment();
}
database.close();
helper.close();
cursor.close();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFavoriteFragment() {
favoriteMoviesDetailsFragment fragment = new favoriteMoviesDetailsFragment();
try {
getFragmentManager().beginTransaction().replace(R.id.activity_container,fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
outState.putString("SORTER", sorterString);
outState.putInt("POSITION",movieData.movieDataPosition);
super.onSaveInstanceState(outState, outPersistentState);
}
public void movieRequest() {
urlFinal = urlBase + sorterString + movieData.apiKey;
urlFinal.trim();
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("results");
movieData.movieDataArray = new movieData[array.length()];
for (int i = 0; i < array.length(); i++) {
movieData movie = new movieData();
JSONObject jsonObject = array.getJSONObject(i);
//movie.setPosition(i);
movie.setMovieId(jsonObject.getString("id"));
movie.setMovieImagePath(jsonObject.getString("poster_path"));
movie.setMovieTitle(jsonObject.getString("original_title"));
movie.setMoviePlot(jsonObject.getString("overview"));
movie.setMovieVoting(jsonObject.getString("vote_average"));
movie.setMovieReleaseDate(jsonObject.getString("release_date"));
movieData.movieDataArray[i] = movie;
}
MovieGridFragment gridFragment = new MovieGridFragment();
gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray); //hier wird datalist eigentlich zugewiesen
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.activity_container, gridFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", String.valueOf(error));
}
}
);
requestQueue.add(jsonObjectRequest);
}
#Override
public void clickOnItem(int id) {
movieData.movieDataPosition = id;
if(movieData.movieDataArray == null) {
movieRequest();
} else {
Intent intent = new Intent(this, detailsActivity.class);
intent.putExtra("FRAGMENT","MOVIE");
startActivity(intent);
}
}
#Override
public void favoriteMovieItem(int movieId) {
movieData.dbPosition = movieId;
Intent intent = new Intent(this,detailsActivity.class);
intent.putExtra("FRAGMENT","favorite");
startActivity(intent);
} }
You can try this
this.clickListener = (MainActivity) getActivity();
You get the FragmentActivity and cast it into your MainActivity
EDIT:
I suggest you to add a function in your fragment like :
public void setListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
And in your activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
MovieGridFragment fragment = new MovieGridFragment();
fragment.setListener(this); // some change here
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment)
.commit();
movieData.movieDataPosition = 0;
}
if(savedInstanceState != null) {
sorterString = savedInstanceState.getString("SORTER");
}
if(savedInstanceState == null)
movieData.movieDataPosition = 0;
if(sorterString==null)
sorterString="popular?";
if(sorterString!="favorite" && sorterString!=null) {
if(networkChecker.isNetworkAvailableChecker(this)) {
movieRequest();
}
}
}
.... no relevant functions
public void movieRequest() {
urlFinal = urlBase + sorterString + movieData.apiKey;
urlFinal.trim();
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("results");
movieData.movieDataArray = new movieData[array.length()];
for (int i = 0; i < array.length(); i++) {
movieData movie = new movieData();
JSONObject jsonObject = array.getJSONObject(i);
//movie.setPosition(i);
movie.setMovieId(jsonObject.getString("id"));
movie.setMovieImagePath(jsonObject.getString("poster_path"));
movie.setMovieTitle(jsonObject.getString("original_title"));
movie.setMoviePlot(jsonObject.getString("overview"));
movie.setMovieVoting(jsonObject.getString("vote_average"));
movie.setMovieReleaseDate(jsonObject.getString("release_date"));
movieData.movieDataArray[i] = movie;
}
MovieGridFragment gridFragment = new MovieGridFragment();
gridfragment.setListener(this); // some change here
gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray); //hier wird datalist eigentlich zugewiesen
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.activity_container, gridFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", String.valueOf(error));
}
}
);
requestQueue.add(jsonObjectRequest);
}
Hope this helps.
The context passed in is not necessarily your activity. It could be a wrapper around it with various theming and other overrides. You can never assume that when passed a Context, you're passed an Activity. If you need a reference to a click handler, write a setClickHandler function and call it explicitly.
Even if it is the Activity, the app doesn't know that- at that point its a Context. You'd need to explicitly cast it, which may not work (and may work on some versions of the OS and not others) due to paragraph 1.
Try to put your interface inside fragment class.
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private int index;
private GridView movieGridView;
public List<movieData> movieDataList = new ArrayList<>();
public MovieGridFragment() {} //empty constructor
#Override
public void onAttach(Context context) {
this.clickListener = (clickInterfaceHelper) context;
super.onAttach(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
if(savedInstanceState != null) {
if (!movieDataList.isEmpty()) {
movieDataList = Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA"));
}
}
super.onCreate(savedInstanceState);
}
public interface clickInterfaceHelper {
void clickOnItem(int id);
void favoriteMovieItem(int movieId);
}
}
To all android beginners, you can use the interface like below-mentioned way.
Define an Interface,
public interface CallBack {
String stringValue(String s);
}
In Fragment,
Callback mCallback;
In onAttach(Context context) method of your fragment,
mCallback = (Callback) context; // Casting to the activity
mcallback.stringValue("Your message");
Then in your Activity, you must implement the interface else you will get
classcastException
public class MainActivity implements CallBack{
#Override
public String stringValue(String s) {
// Here you will get the value from the fragment
return s;
}
}
It's not advisable to pass values between two fragments directly using interfaces. You should use the activity as a mediator while passing values.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have added a filter for my searchview to show recyclerview items that match the query. The search seems to work but the app crashes if there are no items in recyclerview so can someone help me here a bit?
My fragment:
public class TextTypingTabFragment extends Fragment implements TabLayoutFragmentPagerAdapter.ITabLayoutIconFragmentPagerAdapter {
private static final String TAG = TextTypingTabFragment.class.getSimpleName();
private final TextTypingLoaderCallbacks mLoaderCallbacks = new TextTypingLoaderCallbacks();
private TextTypingCustomAdapter mTextTypingCustomAdapter;
private View mView;
private ProgressBar mProgressBar;
private ScrollView mScrollView;
private RecyclerView mRecyclerView;
public TextTypingTabFragment() {
// Required empty public constructor
}
// ----
private Context getContextNonNull() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
return Objects.requireNonNull(getContext());
} else {
return getContext();
}
}
// ----
private int mItemCount = -1;
private int mFirstVisibleItemPosition = -1, mFirstCompletelyVisibleItemPosition = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtil.d(TAG, "Fragment create");
Bundle bundle = new Bundle();
bundle.putString(AppEnvr.EXTRA_PACKAGE_NAME_KEY, MainActivity.sSelectedPackageName);
getLoaderManager().initLoader(1, bundle, mLoaderCallbacks); // Init with 1
setHasOptionsMenu(true);
// ----
LocalBroadcastManager.getInstance(getContextNonNull()).registerReceiver(mSelectedPackageNameChangedCustomReceiver, new IntentFilter(AppEnvr.ACTION_SELECTED_PACKAGE_NAME_CHANGED));
}
#Override
public void onResume() {
super.onResume();
LogUtil.d(TAG, "Fragment resume");
Bundle bundle = new Bundle();
bundle.putString(AppEnvr.EXTRA_PACKAGE_NAME_KEY, MainActivity.sSelectedPackageName);
getLoaderManager().restartLoader(1, bundle, mLoaderCallbacks); // Restart with 1
}
#Override
public void onPause() {
super.onPause();
LogUtil.d(TAG, "Fragment pause");
if (mTextTypingCustomAdapter != null) {
mItemCount = mTextTypingCustomAdapter.getItemCount();
}
if (mRecyclerView != null) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
if (linearLayoutManager != null) {
mFirstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
mFirstCompletelyVisibleItemPosition = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
LogUtil.d(TAG, "Fragment destroy");
LocalBroadcastManager.getInstance(getContextNonNull()).unregisterReceiver(mSelectedPackageNameChangedCustomReceiver);
}
// ----
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_text_typing_tab, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mView = view;
mProgressBar = view.findViewById(R.id.fragment_text_typing_tab_progress_bar);
mScrollView = view.findViewById(R.id.fragment_text_typing_tab_scroll_view);
mRecyclerView = view.findViewById(R.id.fragment_text_typing_tab_recycler_view);
}
// ----
#Override
public Fragment getItem() {
return this;
}
#Override
public CharSequence getPageTitle() {
return "History";
}
#Override
public int getIcon() {
return R.drawable.ic_typesave;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.typed_text_fragment_menu, menu);
final SearchView searchView = new SearchView(getActivity());
searchView.setQuery(null, true);
searchView.setQueryHint("Search");
EditText searchEditText = searchView.findViewById(androidx.appcompat.R.id.search_src_text);
searchEditText.setTextColor(getResources().getColor(R.color.white));
searchEditText.setHintTextColor(getResources().getColor(R.color.tabTextColor));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
Filter filter = mTextTypingCustomAdapter.getFilter();
if (filter != null) {
filter.filter(s);
return true;
}
return false;
}
#Override
public boolean onQueryTextChange(String s) {
Filter filter = mTextTypingCustomAdapter.getFilter();
if (filter != null) {
filter.filter(s);
return true;
}
return false;
}
});
menu.findItem(R.id.action_search).setActionView(searchView);
}
// ----
private final BroadcastReceiver mSelectedPackageNameChangedCustomReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
LogUtil.d(TAG, "Receiver receive");
// ----
if (context == null || intent == null) {
if (context == null) {
LogUtil.w(TAG, "Receiver receive: Context lack");
}
if (intent == null) {
LogUtil.w(TAG, "Receiver receive: Intent lack");
}
return;
}
// ----
String intentAction = null;
try {
intentAction = intent.getAction();
} catch (Exception e) {
LogUtil.e(TAG, e.getMessage());
LogUtil.e(TAG, e.toString());
e.printStackTrace();
}
if (intentAction == null || !intentAction.equals(AppEnvr.ACTION_SELECTED_PACKAGE_NAME_CHANGED)) {
if (intentAction == null) {
LogUtil.w(TAG, "Receiver receive: Intent action lack");
} else if (!intentAction.equals(AppEnvr.ACTION_SELECTED_PACKAGE_NAME_CHANGED)) {
LogUtil.w(TAG, "Receiver receive: Intent action mismatch");
}
return;
}
// ----
LogUtil.d(TAG, "Receiver receive: OK");
// ----
Bundle extras = null;
try {
extras = intent.getExtras();
} catch (Exception e) {
LogUtil.e(TAG, e.getMessage());
LogUtil.e(TAG, e.toString());
e.printStackTrace();
}
if (extras != null) {
if (extras.containsKey(AppEnvr.EXTRA_PACKAGE_NAME_KEY)) {
String packageName = extras.getString(AppEnvr.EXTRA_PACKAGE_NAME_KEY, null);
// ----
Bundle bundle = new Bundle();
bundle.putString(AppEnvr.EXTRA_PACKAGE_NAME_KEY, packageName);
getLoaderManager().restartLoader(1, bundle, mLoaderCallbacks); // Restart with 1
}
}
}
};
// ----
private final class TextTypingLoaderCallbacks implements LoaderManager.LoaderCallbacks<ArrayList<TextTypingObject>> {
private String mPackageName = null;
#NonNull
#Override
public Loader<ArrayList<TextTypingObject>> onCreateLoader(int i, #Nullable Bundle bundle) {
if (mScrollView != null) {
mScrollView.setVisibility(View.GONE);
}
if (mRecyclerView != null) {
mRecyclerView.setVisibility(View.GONE);
}
if (mProgressBar != null) {
mProgressBar.setVisibility(View.VISIBLE);
}
// ----
if (bundle != null) {
mPackageName = bundle.getString(AppEnvr.EXTRA_PACKAGE_NAME_KEY, null);
}
// ----
return new TextTypingLoader(getContextNonNull(), mPackageName);
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList<TextTypingObject>> loader, #Nullable ArrayList<TextTypingObject> textTypingObjectArrayList) {
if (textTypingObjectArrayList != null && !textTypingObjectArrayList.isEmpty()) {
mTextTypingCustomAdapter = new TextTypingCustomAdapter(getContextNonNull(), textTypingObjectArrayList);
} else {
if (mTextTypingCustomAdapter != null) {
mTextTypingCustomAdapter = null;
}
// ----
if (mPackageName != null && MainActivity.sSelectedPackageName != null) {
mPackageName = null;
MainActivity.sSelectedPackageName = null;
getLoaderManager().restartLoader(1, null, mLoaderCallbacks); // Restart with 1
return;
}
}
// ----
if (mProgressBar != null) {
mProgressBar.setVisibility(View.GONE);
}
if (mTextTypingCustomAdapter != null) {
if (mRecyclerView != null) {
int scrollToPosition = -1;
// ----
if (mItemCount != -1 && mFirstVisibleItemPosition != -1) {
int newItemCount = mTextTypingCustomAdapter.getItemCount();
// ----
if (newItemCount == mItemCount) { // No added/removed events
scrollToPosition = mFirstVisibleItemPosition;
} else if (newItemCount > mItemCount) { // Added events found
if (mFirstVisibleItemPosition != 0) {
int addedEventsCount = newItemCount - mItemCount;
scrollToPosition = mFirstVisibleItemPosition + addedEventsCount;
// ----
if (addedEventsCount >= 1 && mFirstVisibleItemPosition >= 1) {
Snackbar snackbar = Snackbar.make(mView, getContextNonNull().getString(R.string.new_events_found, addedEventsCount) + " (text typing)", Snackbar.LENGTH_SHORT);
snackbar.setAction(getContextNonNull().getString(R.string.scroll), v -> mRecyclerView.smoothScrollToPosition(0));
snackbar.show();
}
}
} else /*if (newItemCount < mItemCount)*/ { // Removed events found
scrollToPosition = mFirstVisibleItemPosition;
}
// ----
mFirstVisibleItemPosition = -1;
mItemCount = -1;
}
// ----
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mRecyclerView.getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
if (scrollToPosition != -1) {
linearLayoutManager.scrollToPosition(scrollToPosition);
}
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mTextTypingCustomAdapter);
// ----
mRecyclerView.setVisibility(View.VISIBLE);
// ----
}
} else {
if (mScrollView != null) {
mScrollView.setVisibility(View.VISIBLE);
}
}
// ----
if (mPackageName != null) {
mPackageName = null;
}
}
#Override
public void onLoaderReset(#NonNull Loader loader) {
}
}
}
SearchView Code:
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.typed_text_fragment_menu, menu);
final SearchView searchView = new SearchView(getActivity());
searchView.setQuery(null, true);
searchView.setQueryHint("Search");
EditText searchEditText = searchView.findViewById(androidx.appcompat.R.id.search_src_text);
searchEditText.setTextColor(getResources().getColor(R.color.white));
searchEditText.setHintTextColor(getResources().getColor(R.color.tabTextColor));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
Filter filter = mTextTypingCustomAdapter.getFilter();
if (filter != null) {
filter.filter(s);
return true;
}
return false;
}
#Override
public boolean onQueryTextChange(String s) {
Filter filter = mTextTypingCustomAdapter.getFilter();
if (filter != null) {
filter.filter(s);
return true;
}
return false;
}
});
menu.findItem(R.id.action_search).setActionView(searchView);
}
Error Log: Attempt to invoke virtual method 'android.widget.Filter com.app.app.adapter.TextTypingCustomAdapter.getFilter()' on a null object reference
When you are going to filter like this
Filter filter = mTextTypingCustomAdapter.getFilter();
if not match with any item.then your variable mTextTypingCustomAdapter is null. you should check null safety before filtering in both methods( onQueryTextSubmit() && onQueryTextChange() )
if(mTextTypingCustomAdapter != null){
Filter filter = mTextTypingCustomAdapter.getFilter();}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
How to solve "'catch' or 'finally' expected" error in android studio..?
a screenshot of the error
public class FragmentRecent extends Fragment {
View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterChannel adapterChannel;
private SwipeRefreshLayout swipeRefreshLayout;
private Call<CallbackChannel> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
private OfflineDatabase databaseHelper;
int counter = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_recent, null);
parent_view = getActivity().findViewById(R.id.main_content);
loadInterstitialAd();
swipeRefreshLayout = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_home);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
adapterChannel = new AdapterChannel(getActivity(), recyclerView, new ArrayList<Channel>());
recyclerView.setAdapter(adapterChannel);
// on item list clicked
adapterChannel.setOnItemClickListener(new AdapterChannel.OnItemClickListener() {
#Override
public void onItemClick(View v, Channel obj, int position) {
Intent intent = new Intent(getActivity(), ActivityDetailChannel.class);
intent.putExtra(Constant.KEY_CHANNEL_CATEGORY, obj.category_name);
intent.putExtra(Constant.KEY_CHANNEL_ID, obj.channel_id);
intent.putExtra(Constant.KEY_CHANNEL_NAME, obj.channel_name);
intent.putExtra(Constant.KEY_CHANNEL_IMAGE, obj.channel_image);
intent.putExtra(Constant.KEY_CHANNEL_URL, obj.channel_url);
intent.putExtra(Constant.KEY_CHANNEL_DESCRIPTION, obj.channel_description);
startActivity(intent);
showInterstitialAd();
}
});
// detect when scroll reach bottom
adapterChannel.setOnLoadMoreListener(new AdapterChannel.OnLoadMoreListener() {
#Override
public void onLoadMore(int current_page) {
if (post_total > adapterChannel.getItemCount() && current_page != 0) {
int next_page = current_page + 1;
requestAction(next_page);
} else {
adapterChannel.setLoaded();
}
}
});
// on swipe list
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
adapterChannel.resetListData();
requestAction(1);
}
});
requestAction(1);
return root_view;
}
private void displayApiResult(final List<Channel> channels) {
adapterChannel.insertData(channels);
swipeProgress(false);
if (channels.size() == 0) {
showNoItemView(true);
}
}
private void requestListPostApi(final int page_no) {
ApiInterface apiInterface = RestAdapter.createAPI();
callbackCall = apiInterface.getPostByPage(page_no, Config.LOAD_MORE);
callbackCall.enqueue(new Callback<CallbackChannel>() {
#Override
public void onResponse(Call<CallbackChannel> call, Response<CallbackChannel> response) {
CallbackChannel resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
} else {
onFailRequest(page_no);
}
}
#Override
public void onFailure(Call<CallbackChannel> call, Throwable t) {
if (!call.isCanceled()) onFailRequest(page_no);
}
});
}
private void onFailRequest(int page_no) {
failed_page = page_no;
adapterChannel.setLoaded();
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
} else {
//showToast("Internet Not");
if (databaseHelper.getOfflineData("FragmentCategory").length() != 0) {
setJson(databaseHelper.getOfflineData("FragmentCategory"), false);
}
}
}
//databaseHelper.removeAll();
private void requestAction(final int page_no) {
showFailedView(false, "");
showNoItemView(false);
if (page_no == 1) {
swipeProgress(true);
} else {
adapterChannel.setLoading();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestListPostApi(page_no);
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if (callbackCall != null && callbackCall.isExecuted()) {
callbackCall.cancel();
}
}
private void showFailedView(boolean show, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_home);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction(failed_page);
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_home);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_post_found);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
return;
}
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(show);
}
});
}
public void setJson(String result, Boolean isOnline) {
try {
//inseting result to database
if(isOnline) {
ContentValues offline_data = new ContentValues();
offline_data.put(OfflineDatabase.KEY_OFFLINE_DATA, result);
if(databaseHelper.getOfflineData("FragmentCategory").length()!=0) {
databaseHelper.update("FragmentCategory",offline_data);
} else {
offline_data.put(OfflineDatabase.KEY_ACTIVITY_NAME, "FragmentCategory");
databaseHelper.addOfflineData(offline_data, null);
//handle both exceptions
}
}}}
private void loadInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
interstitialAd.loadAd(new AdRequest.Builder().build());
}
});
} else {
Log.d("AdMob", "AdMob Interstitial is Enabled");
}
}
private void showInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
if (interstitialAd != null && interstitialAd.isLoaded()) {
if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
interstitialAd.show();
counter = 1;
} else {
counter++;
}
} else {
Log.d("AdMob", "Interstitial Ad is Disabled");
}
} else {
Log.d("AdMob", "AdMob Interstitial is Disabled");
}
}}
there you start with try:
public void setJson(String result, Boolean isOnline) {
try {
...
}
...
}
which has to continue with:
try {
...
} catch(Exception e) {
} finally {
}
where either catch or finally are optional (depending where the Exception shall be handled).
How do I save the Exoplayer video current position and text on screen rotation and the video should not paused on Screen rotation? I tried using outState.putInt("position",(int) player.getCurrentPosition); on onSaveInstanceState() but it didn't work. The present code below shows the recipeName == null on onSaveInstanceState while debugging.
public class RecipeStepDetailFragment extends Fragment {
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private BandwidthMeter bandwidthMeter;
private ArrayList<Step> steps = new ArrayList<>();
private int selectedIndex;
private Handler mainHandler;
private String recipeName;
private int contentPosition;
public RecipeStepDetailFragment() {
}
private ListItemClickListener itemClickListener;
public interface ListItemClickListener {
void onListItemClick(List<Step> allSteps,int Index,String recipeName);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView textView;
mainHandler = new Handler();
bandwidthMeter = new DefaultBandwidthMeter();
itemClickListener =(RecipeDetailActivity)getActivity();
ArrayList<Recipe> recipe = new ArrayList<>();
if(savedInstanceState != null) {
steps = savedInstanceState.getParcelableArrayList(SELECTED_STEPS);
selectedIndex = savedInstanceState.getInt(SELECTED_INDEX);
recipeName = savedInstanceState.getString("Title");
}
else {
assert getArguments() != null;
steps =getArguments().getParcelableArrayList(SELECTED_STEPS);
if (steps!=null) {
steps =getArguments().getParcelableArrayList(SELECTED_STEPS);
selectedIndex=getArguments().getInt(SELECTED_INDEX);
recipeName=getArguments().getString("Title");
}
else {
recipe =getArguments().getParcelableArrayList(SELECTED_RECIPES);
//casting List to ArrayList
assert recipe != null;
steps=(ArrayList<Step>) recipe.get(0).getSteps();
selectedIndex=0;
}
}
View rootView = inflater.inflate(R.layout.recipe_step_detail_fragment_body_part, container, false);
textView = rootView.findViewById(R.id.recipe_step_detail_text);
textView.setText(steps.get(selectedIndex).getDescription());
textView.setVisibility(View.VISIBLE);
simpleExoPlayerView = rootView.findViewById(R.id.playerView);
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
String videoURL = steps.get(selectedIndex).getVideoURL();
if (rootView.findViewWithTag("sw600dp-port-recipe_step_detail")!=null) {
recipeName=((RecipeDetailActivity) Objects.requireNonNull(getActivity())).recipeName;
Objects.requireNonNull(((RecipeDetailActivity) getActivity()).getSupportActionBar()).setTitle(recipeName);
}
String imageUrl=steps.get(selectedIndex).getThumbnailURL();
if (!imageUrl.equals("")) {
Uri builtUri = Uri.parse(imageUrl).buildUpon().build();
ImageView thumbImage = rootView.findViewById(R.id.thumbImage);
Picasso.with(getContext()).load(builtUri).into(thumbImage);
}
if (!videoURL.isEmpty()) {
initializePlayer(Uri.parse(steps.get(selectedIndex).getVideoURL()));
if (rootView.findViewWithTag("sw600dp-land-recipe_step_detail")!=null) {
getActivity().findViewById(R.id.fragment_container2).setLayoutParams(new LinearLayout.LayoutParams(-1,-2));
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH);
}
else if (isInLandscapeMode(Objects.requireNonNull(getContext()))){
textView.setVisibility(View.GONE);
}
}
else {
player=null;
simpleExoPlayerView.setForeground(ContextCompat.getDrawable(Objects.requireNonNull(getContext()), R.drawable.ic_visibility_off_white_36dp));
simpleExoPlayerView.setLayoutParams(new LinearLayout.LayoutParams(300, 300));
}
Button mPrevStep = rootView.findViewById(R.id.previousStep);
Button mNextstep = rootView.findViewById(R.id.nextStep);
mPrevStep.setOnClickListener(view -> {
if (steps.get(selectedIndex).getId() > 0) {
if (player!=null){
player.stop();
}
itemClickListener.onListItemClick(steps,steps.get(selectedIndex).getId() - 1,recipeName);
}
else {
Toast.makeText(getActivity(),"You already are in the First step of the recipe", Toast.LENGTH_SHORT).show();
}
});
mNextstep.setOnClickListener(view -> {
int lastIndex = steps.size()-1;
if (steps.get(selectedIndex).getId() < steps.get(lastIndex).getId()) {
if (player!=null){
player.stop();
}
itemClickListener.onListItemClick(steps,steps.get(selectedIndex).getId() + 1,recipeName);
}
else {
Toast.makeText(getContext(),"You already are in the Last step of the recipe", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
private void initializePlayer(Uri mediaUri) {
if (player == null) {
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveVideoTrackSelection.Factory(bandwidthMeter);
DefaultTrackSelector trackSelector = new DefaultTrackSelector(mainHandler, videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
player = ExoPlayerFactory.newSimpleInstance(Objects.requireNonNull(getContext()), trackSelector, loadControl);
simpleExoPlayerView.setPlayer(player);
String userAgent = Util.getUserAgent(getContext(), "Baking App");
MediaSource mediaSource = new ExtractorMediaSource(mediaUri, new DefaultDataSourceFactory(getContext(), userAgent), new DefaultExtractorsFactory(), null, null);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
}else{
player.getCurrentPosition();
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle currentState) {
super.onSaveInstanceState(currentState);
currentState.putParcelableArrayList(SELECTED_STEPS,steps);
currentState.putInt(SELECTED_INDEX,selectedIndex);
currentState.putString("Title",recipeName);
//what code should I insert to save both the text and exoplayer on Screen rotation
// (int)
}
private boolean isInLandscapeMode(Context context) {
return (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
}
#Override
public void onDetach() {
super.onDetach();
if (player!=null) {
player.stop();
player.release();
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (player!=null) {
player.stop();
player.release();
player=null;
}
}
#Override
public void onStop() {
super.onStop();
if (player!=null) {
player.stop();
player.release();
}
}
#Override
public void onPause() {
super.onPause();
if (player!=null) {
player.stop();
player.release();
}
}
}
This is my activity class When I use android version 7.0 it causes java.lang.NullPointerException: Attempt to get length of null array
But when use android version 5.0 or 5.1 its run smothly
public class AdmitedPt extends AppCompatActivity {
ListView listView;
EditText inputSearch;
ProgressDialog pDialog;
private ProgressBar bar;
AdmitedPatientAdapter adapter;
private ArrayList<AdmitedPatient> myPatientList = new ArrayList<AdmitedPatient>();
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admitedpatientlist);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
myToolbar.setLogo(R.drawable.icon1);//set logo beside the Title
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);//for stop automatic keybord opening
bar = (ProgressBar) this.findViewById(R.id.progressBar);
inputSearch = (EditText) findViewById(R.id.inputSearch);
listView = (ListView) findViewById(R.id.admitedPatientView);
// onl();
new HttpRequest(this).execute();
// Add Text Change Listener to EditText
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void scanCustomScanner(View view) {
new IntentIntegrator(this).setOrientationLocked(false).setCaptureActivity(CustomScannerActivity.class).initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
inputSearch.setText(result.getContents());
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to disable internet while roaming, just return false
return true;
}
return true;
}
public class HttpRequest extends AsyncTask<Void, Void, Object[]> {
Object resultObject[];
Context context;
ProgressDialog dialog;
public HttpRequest(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
bar.setVisibility(View.VISIBLE);
}
Gson gson = new Gson();
public Object[] findBedDetails() {
CasesData c = new CasesData(context);
try {
URL url = new URL(String.format(Const.URL_IPD_ADMITED));
// String testUrl = loginUrl.substring(loginUrl.lastIndexOf("/") + 1, loginUrl.length());
System.out.println("Test Url :" + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
System.out.println("Connection stutus :" + connection.getResponseCode());
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response1 = new StringBuffer();
System.out.println("Response :" + response1.toString());
while ((inputLine = in.readLine()) != null) {
response1.append(inputLine);
inputLine = null;
}
in.close();
String response = response1.toString();
c.setIpdadmit(response);
resultObject = gson.fromJson(response, AdmitedPatient[].class);
} catch (ConnectException e) {
Log.e("MYAPP", "exception", e);
resultObject = gson.fromJson(c.getIpdadmit(), AdmitedPatient[].class);
} catch (Exception e) {
}
return resultObject;
}
#Override
protected void onPostExecute(Object[] objects) {
AdmitedPatient[] pt = (AdmitedPatient[]) objects;
for (AdmitedPatient a : pt) {
myPatientList.add(new AdmitedPatient(a.getADMISSION_ID(), a.getFNAME(), a.getAGE()));
}
myPatientList.add(new AdmitedPatient("LS1611001297", "KAMAL", "50Y"));
//Error show in this line java.lang.NullPointerException: Attempt to get length of null array
adapter = new AdmitedPatientAdapter((Activity) context, myPatientList);
listView.setAdapter(adapter);
bar.setVisibility(View.GONE);
}
#Override
protected Object[] doInBackground(Void... params) {
return this.findBedDetails();
}
}
}
This is my adapter class:
public class AdmitedPatientAdapter extends BaseAdapter implements Filterable {
public ArrayList<AdmitedPatient> mDisplayedValues;
public ArrayList<AdmitedPatient> mOriginalValues;
Activity activity;
public AdmitedPatientAdapter(Activity activity, ArrayList<AdmitedPatient> list) {
this.activity = activity;
this.mDisplayedValues = list;
this.mOriginalValues=list;
}
#Override
public int getCount() {
return mDisplayedValues.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
LinearLayout llContainer;
TextView textView1;
TextView textView2;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.admitpatient_listview, null);
viewHolder = new ViewHolder();
viewHolder.llContainer = (LinearLayout)convertView.findViewById(R.id.llContainer);
viewHolder.textView1 = (TextView) convertView.findViewById(R.id.column1);
viewHolder.textView2 = (TextView) convertView.findViewById(R.id.column2);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView1.setText(mDisplayedValues.get(position).ADMISSION_ID);
viewHolder.textView2.setText(mDisplayedValues.get(position).FNAME);
viewHolder.llContainer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent it=new Intent(activity,CollapseView.class);
Bundle bundle = new Bundle();
bundle.putSerializable("my object", mDisplayedValues.get(position));
it.putExtras(bundle);
activity.startActivity(it);
}
});
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mDisplayedValues = (ArrayList<AdmitedPatient>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<AdmitedPatient> FilteredArrList = new ArrayList<AdmitedPatient>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<AdmitedPatient>(mDisplayedValues); // saves the original data in mOriginalValues
}
if (constraint == null || constraint.length() == 0) {
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i).ADMISSION_ID;
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(new AdmitedPatient(mOriginalValues.get(i).ADMISSION_ID, mOriginalValues.get(i).FNAME,mOriginalValues.get(i).AGE));
}
}
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
I need to put a 30sec timer in my otp verfication page after 30secs timer should be gone and the keyboard should pop up. what needs to be done??
Below are my java files.
SignUpFragment.java
SignUpActivity activity;
/**
* Declaring Variables for Views
*/
TextView SignupAlreadyMember;
EditText SignUpName, SignUpEmail,referCode;
Button SignUpRegister;
VirtualApplication virtualApplication;
// Progress dialog
private ProgressDialog pDialog;
public SignUpFragment() {
}
#Override
public void onAttach(Activity activit) {
super.onAttach(activit);
this.activity = (SignUpActivity) activit;
virtualApplication = (VirtualApplication) activity.getApplicationContext();
}
int bodyId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bodyId = getArguments().getInt("output");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sign_up, container, false);
activity.setTempTitle("signup");
inItViews(view);
SignUpRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterUser();
// showVerifyMobileScreen(123);
}
});
SignUpEmail.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
RegisterUser();
}
return false;
}
});
SignupAlreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gotoLoginScreen();
}
});
return view;
}
private void gotoLoginScreen() {
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
activity.finish();
}
public boolean validCellPhone(String number) {
return Patterns.PHONE.matcher(number).matches();
}
private void RegisterUser() {
String email = SignUpEmail.getText().toString().trim();
String name = SignUpName.getText().toString().trim();
String code=referCode.getText().toString().trim();
if (email.isEmpty() ||!SystemUtil.isValidMobile(email)) {
SignUpEmail.setError("Enter Mobile number here");
return;
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name);
jsonObject.put("phone_number", email);
jsonObject.put("body_id", bodyId);
jsonObject.put("referral_code",code);//referral_code
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
jsonObject.put("imei", SystemUtil.getIMEINumber(activity, tm)) ;
} catch (JSONException e) {
e.printStackTrace();
}
SignUpRegister.setEnabled(false);
requestForRegistration(jsonObject);
}
private void requestForRegistration(JSONObject jsonObject) {
showpDialog();
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, AppConstants.REGISTER_URL, jsonObject, this, this);
customJSONObjectRequest.setTag("Register");
customJSONObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
customJSONObjectRequest.setShouldCache(true);
requestQueue.add(customJSONObjectRequest);
//
}
private void showVerifyMobileScreen(int userId) {
VerificationFragment verificationFragment = new VerificationFragment();
Bundle bundle = new Bundle();
bundle.putInt("userId", userId);
bundle.putString("mobile", SignUpEmail.getText().toString().trim());
verificationFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, verificationFragment).commit();
}
private void inItViews(View view) {
TextView SignUPHeader = (TextView) view.findViewById(R.id.SignUPHeader);
TextView Signupmessage= (TextView) view.findViewById(R.id.Signupmessage);
Signupmessage.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUPHeader.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignupAlreadyMember = (TextView) view.findViewById(R.id.SignupAlreadyMember);
SignupAlreadyMember.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpName = (EditText) view.findViewById(R.id.SignUpName);
SignUpName.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpEmail = (EditText) view.findViewById(R.id.SignUpEmail);
SignUpEmail.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpRegister = (Button) view.findViewById(R.id.SignUpRegister);
SignUpRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
referCode = (EditText) view.findViewById(R.id.referCode);
referCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
SignUpRegister.setEnabled(true);
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
SystemUtil.sysOut("register::::: " + jsonObject.toString());
if (JSONUtil.readBoolean(jsonObject, "status")) {
int userId = JSONUtil.readInt(jsonObject, "user_id");
showVerifyMobileScreen(userId);
}else{
SignUpRegister.setEnabled(true);
}
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
}
VerificationFragment.Java
SignUpActivity activity;
TextView verifyTitleOne, verifyTitleTwo, verifyChnageNumber, verificationResend;
EditText SignUpMobile, VerficationCode;
Button VerificationRegister;
int userId;
String mobile;
boolean isResend;
public VerificationFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
userId = bundle.getInt("userId");
mobile = bundle.getString("mobile");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_verfication, container, false);
activity.setTempTitle("details");
inItViews(view);
SignUpMobile.setText("" + mobile);
VerificationRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!VerficationCode.getText().toString().trim().isEmpty()) {
Toast.makeText(activity, "Verifying", Toast.LENGTH_LONG).show();
showpDialog();
getDefaultData();
} else {
VerficationCode.setError("Enter Code");
}
}
});
verificationResend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isResend) {
isResend = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject, AppConstants.RESEND_OTP_URL);
}else
Toast.makeText(activity,"Please Wait",Toast.LENGTH_SHORT).show();
}
});
// setvalues();
return view;
}
private void setvalues() {
VerficationCode.setText("51692");
VerificationRegister.performClick();
}
private void getDefaultData() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_id", userId);
jsonObject.put("token", VerficationCode.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject,AppConstants.VERIFY_NUMBER_URL);
}
private void requestServer(JSONObject jsonObject, String url) {
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, url, jsonObject, this, this);
customJSONObjectRequest.setTag("verify");
requestQueue.add(customJSONObjectRequest);
}
private void gotoSelectSizesPage(JSONObject jsonObject) {
Bundle bundle = new Bundle();
bundle.putString("output", jsonObject.toString());
DoneFragment homeKitFragment = new DoneFragment();
homeKitFragment.setArguments(bundle);
activity.setTempTitle("");
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, homeKitFragment).commit();
}
private void inItViews(View view) {
verifyTitleOne = (TextView) view.findViewById(R.id.verifyTitleOne);
verifyTitleOne.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyTitleTwo = (TextView) view.findViewById(R.id.verifyTitleTwo);
verifyTitleTwo.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyChnageNumber = (TextView) view.findViewById(R.id.verifyChnageNumber);
verifyChnageNumber.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verificationResend = (TextView) view.findViewById(R.id.verificationResend);
verificationResend.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpMobile = (EditText) view.findViewById(R.id.SignUpMobile);
SignUpMobile.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerficationCode = (EditText) view.findViewById(R.id.VerficationCode);
VerficationCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerificationRegister = (Button) view.findViewById(R.id.VerificationRegister);
VerificationRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get("pdus");
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], "3gpp");
smsMessageStr = smsMessage.getMessageBody().toString();
// String address = smsMessage.getOriginatingAddress();
/*smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";*/
}
VerficationCode.setText("" + stripNonDigits(smsMessageStr));
VerificationRegister.performClick();
}
}
};
private ProgressDialog pDialog;
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
public static String stripNonDigits(
final CharSequence input) {
final StringBuilder sb = new StringBuilder(
input.length());
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (c > 47 && c < 58) {
sb.append(c);
}
}
return sb.toString();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (SignUpActivity) activity;
activity.registerReceiver(broadcastReceiver, new IntentFilter(
AppConstants.BROADCAST_ACTION_SMS));
}
#Override
public void onDetach() {
super.onDetach();
activity.unregisterReceiver(broadcastReceiver);
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
isResend=false;
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
if (JSONUtil.readBoolean(jsonObject, "status") &&jsonObject.has("user_data")) {
gotoSelectSizesPage(jsonObject);
}
}
}