ShakeDetector is not working in Fragment, how can I do - java

My shake detector is not working in fragment. But worked in activity. what is the reason for this, what should i do.How can ı solve.
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
presenter.takeView(this);
Log.d(TAG, "onViewCreated: " + this);
presenter.initListener();
initUI();
SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
ShakeDetector sd = new ShakeDetector(this);
sd.start(sensorManager);
}
My shake detectror code;
#Override
public void hearShake() {
int position= listDataAdapter.getPosition();
listDataAdapter.removeItem(position);
UserItemPojo item = listDataAdapter.removeItem(position);
if (item != null)
sub_main_presenter.doLike(item);
presenter.isEmpty();
if (userList.isEmpty())
homePresenter.stopPlayer();
Toast.makeText(getContext(),"shakeDetector is working", Toast.LENGTH_LONG).show();
}

Related

AlertDialog "onClick" method not working properly

I currently have an alert dialog that is being displayed on a fragment. The dialog displays to the user with no issues, but the "setPositiveButton" and "setNegativeButton" are not responding to the user interaction correctly, the Log.i after the on "setPositiveButton" is pressed is the only thing that is actually working. I want it to display a Toast message and travel to a new fragment after the possitive button is has been pressed.
private FragmentRequestCodeBinding binding;
//TAG
private static final String TAG = "requestCodeFragment";
//Values
private String firstLetter = "B";
private int secondLetter = 0;
private String thirdLetter = "0";
private String fourthLetter = "0";
private String fifthLetter = "0";
private String dtcCode = firstLetter + secondLetter + thirdLetter + fourthLetter + fifthLetter;
//Buttons
private Button request;
//Views
View root;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentRequestCodeBinding.inflate(inflater, container, false);
root = binding.getRoot();
request = root.findViewById(R.id.requestButton);
// Inflate the layout for this fragment
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final NavController navController = Navigation.findNavController(view);
request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(getContext())
.setIcon(R.drawable.ic_baseline_priority_high_24)
.setTitle("Request for " + dtcCode)
.setMessage("Are you sure you want to request the following code " +
"for this car model?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "Ticket created successfully!",
Toast.LENGTH_SHORT).show();
navController.navigate(R.id.action_requestCodeFragment_to_navigation_profile);
Log.i(TAG, "onClick: Pressed");
}
})
.setNegativeButton("No", null)
.setCancelable(true)
.show();
}
});
}
Sorry to bother guys, the code is all good. I started using a real device instead of the android emulator and everything is working just fine.

Why is my code always receiving a null pointer exception when I have binded the element in to it? I am using Java in Android Studio

I am receiving java.lang.NullPointerException, although I have binded the element correctly.
Tried to check the ID of the element, it matches, but still I receive the same exception.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Text to Speech
tts = new TextToSpeech(this, this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
speakButton = view.findViewById(R.id.speakButton);
}
}
It should be running fine, But I am receiving the java.lang.NullPointerException
You button code should be declared in you fragment not in you activity as the button is in your fragment.xml. As you are accessing the button in onCreate method of the activity it will give nullpointer exception because you fragment's view is not yet rendered.The best practice is to access the view in onViewCreated function of your fragment.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Text to Speech
tts = new TextToSpeech(getActivity(), this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
}
void speakOut(){
}
The solution is to implement TextToSpeech.OnInitListener in the project and make the public variables to be private.
public class TranslatorFragment extends Fragment implements TextToSpeech.OnInitListener{
private Button speakButton; // public Button speakButton;
private TextToSpeech tts;
private EditText speechText; // public EditText speechText;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tts = new TextToSpeech(getActivity(), this);
speakButton = view.findViewById(R.id.speakButton);
speechText = view.findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
}
private void speakOut(){
String text = speechText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status){
if(status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(getActivity(), "Language not supported!", Toast.LENGTH_SHORT).show();
} else {
speakButton.setEnabled(true);
speakOut();
}
}
else
{
Toast.makeText(getActivity(), "Initilization failed!", Toast.LENGTH_SHORT).show();
}
}
public void onDestroy() {
if(tts != null){
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}

NextActivity onCreate() is skipped

I am creating a social app and the users can upload an image and then write a caption on the next screen right after. My problem is that the activity where the user creates the caption, gets completely skipped over and goes to the profile page. The image goes to the firebase storage but I can't write a caption.
07-10 15:23:21.150 30970-31309/tabian.com.hash E/ImageLoader: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
java.lang.UnsupportedOperationException: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromOtherSource(BaseImageDownloader.java:280)
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:99)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.downloadImage(LoadAndDisplayImageTask.java:291)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryCacheImageOnDisk(LoadAndDisplayImageTask.java:274)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:230)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:136)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
GalleryFragment.Java
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: Started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the gallery screen.");
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
if (isTaskRoot()) {
Intent intent = new Intent(GalleryFragment.this.getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
GalleryFragment.this.startActivity(intent);
} else {
Intent intent = new Intent(GalleryFragment.this.getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
GalleryFragment.this.startActivity(intent);
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
}
});
init();
return view;
}
NextActivity.Java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = (EditText) findViewById(R.id.caption) ;
setupFirebaseAuth();
ImageView backArrow = (ImageView) findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the activity");
finish();
}
});
TextView share = (TextView) findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
ProfileActivity.Java :
public class ProfileActivity extends AppCompatActivity implements
ProfileFragment.OnGridImageSelectedListener ,
ViewPostFragment.OnCommentThreadSelectedListener,
ViewProfileFragment.OnGridImageSelectedListener{
private static final String TAG = "ProfileActivity";
#Override
public void onCommentThreadSelectedListener(Photo photo) {
Log.d(TAG, "onCommentThreadSelectedListener: selected a comment thread");
ViewCommentsFragment fragment = new ViewCommentsFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_comments_fragment));
transaction.commit();
}
#Override
public void onGridImageSelected(Photo photo, int activityNumber) {
Log.d(TAG, "onGridImageSelected: selected an image gridview: " + photo.toString());
ViewPostFragment fragment = new ViewPostFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
args.putInt(getString(R.string.activity_number), activityNumber);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_post_fragment));
transaction.commit();
}
private static final int ACTIVITY_NUM = 4;
private static final int NUM_GRID_COLUMNS = 3;
private Context mContext = ProfileActivity.this;
private ProgressBar mProgressBar;
private ImageView profilePhoto;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Log.d(TAG, "onCreate: started.");
init();
}

Map fragment lag on scroll

I am using a Google Maps fragment with a MapView that starts by getting user location and setting a marker with it. But i noticed a lag when user scrolls the map, it's like a frame drop.
I searched for some reasons, but i guess it depends on my code. Something seems wrong, but i don't know what yet.
Here's the code:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setFragment(new MapFragment());
}
protected void setFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
MapFragment.java
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
LocationManager mLocationManager;
Location mUserLocation;
private final String TAG_PARSING_STYLE_FAILURE = "ERROR PARSING JSON";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_map, container, false);
return mView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.testMapView);
if( mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mUserLocation = getUserLocation();
LatLng latLng = new LatLng(mUserLocation.getLatitude(), mUserLocation.getLongitude());
MarkerOptions marker = new MarkerOptions();
marker.position(latLng);
marker.title("My Location");
mGoogleMap.addMarker(marker);
CameraPosition cameraPosition = CameraPosition.builder().target(latLng).zoom(17).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
public Location getUserLocation(){
Location loc = null;
try {
loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (SecurityException ex) {
Log.e("ERROR - LOCATION", ex.toString());
}
return loc;
}
Is there a better approach when using MapFragments?

Show view contents after successfully authentication

How and Where do I set view contents to be displayed for persons who has successfully been authenticated using Facebook SDK?
After the persons has logged In, I want to display a User profile view.
I have tried to Instansiate a new fragment like the code below, but that don't work. The text "Fish" Is not displayed.
public class LoginFragment extends Fragment {
private CallbackManager mCallbackManager;
private static final String TAG = "Facebook";
private LoginButton login;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, " logged in...");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile(); //Access the profile who Is the person login in
if(profile != null) {
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if(fragment == null) {
fragment = new LoggedInFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.i(TAG, " Error");
}
};
public LoginFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
//Ask the use for permission to access friends
loginButton.setReadPermissions("user_friends");
//Because we work with fragments
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager, mCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Here IS fragement that the user should see when he/she Is logged In:
package com.waddapp.bryan.waddapp;
public class LoggedInFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.logged_in, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
TextView mTextDetails = (TextView)view.findViewById(R.id.text_details);
mTextDetails.setText("FISH");
}
public LoggedInFragment() {
}
}
Anyone who can explain how acomplish this?

Categories

Resources