Why does the program not call the method "onLocationChanged"? - android-studio

i wrote this simple code for getting the GPS coordinates but it doesnt call the method "onChangedLocation". I know it should jump into the method only when the coordinates change, but at first start it always should jump into that method or not?
It should display the longtitude and latitude in the catlog.
Im using my phone for debugging.
package tabs;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import androfenix.whetoo.R;
public class Tab1 extends ListFragment implements LocationListener {
double latitude;
double longitude;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_local, container, false);
String[] abc = {"Message1", "Message2", "Message3", "Message1", "Message2", "Message3", "Message1", "Message2", "Message3", "Message1", "Message2", "Message3"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, abc);
setListAdapter(adapter);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
return v;
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "onLocationChanged wird aufgerufen");
longitude = location.getLongitude();
String name = String.valueOf(longitude);
Log.d("longtitude", name);
latitude = location.getLatitude();
String name2 = String.valueOf(latitude);
Log.d("latitude", name2);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Related

how to get particular recycler view ltem category and pass it to new activity

I have created a movie app the app is almost complete but there is one shortcoming where if users click one particular category they have to see all the details of that particular category. I'm new to android so I don't know how to implement this. one of them told we can use sql fetch but i have used retro fit so i dont want to change my backend from json to sql .
I have tried a similar question but did not work uploading my main activity, adapter model class and JSON file data
Mainacivity.Java
package com.example.movieapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Filter;
import com.example.movieapp.adapter.BannerMoviesPagerAdapter;
import com.example.movieapp.adapter.ItemRecyclerAdapter;
import com.example.movieapp.adapter.MainRecyclerAdapter;
import com.example.movieapp.listener.OnItemClickLIstener;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.BannerMovies;
import com.example.movieapp.model.CategoryItemList;
import com.example.movieapp.retrofit.RetrofitClient;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
BannerMoviesPagerAdapter bannerMoviesPagerAdapter;
TabLayout IndicatorTab,categoryTab;
ViewPager bannerMoviesViewpager;
List<BannerMovies> homeBannerList;
List<BannerMovies> tvBannerList;
List<BannerMovies> songBannerList;
List<BannerMovies> audioBannerList;
NestedScrollView nestedScrollView;
AppBarLayout appBarLayout;
MainRecyclerAdapter mainRecyclerAdapter;
ItemRecyclerAdapter itemRecyclerAdapter;
RecyclerView mainRecycler;
List<AllCategory> allCategoryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding this line will prevent taking screenshot in your app
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
IndicatorTab =findViewById(R.id.tab_indicator);
categoryTab =findViewById(R.id.tabLayout);
nestedScrollView =findViewById(R.id.nested_scroll);
appBarLayout =findViewById(R.id.appbar);
homeBannerList=new ArrayList<>();
tvBannerList=new ArrayList<>();
songBannerList=new ArrayList<>();
audioBannerList=new ArrayList<>();
getBannerData();
getAllMoviesData(1);
categoryTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
setBannerMoviesPagerAdapter(tvBannerList);
getAllMoviesData(2);
return;
case 2:
setBannerMoviesPagerAdapter(songBannerList);
getAllMoviesData(3);
return;
case 3:
setBannerMoviesPagerAdapter(audioBannerList);
getAllMoviesData(4);
return;
default:
setBannerMoviesPagerAdapter(homeBannerList);
getAllMoviesData(1);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//titles
allCategoryList=new ArrayList<>();
}
private void setBannerMoviesPagerAdapter(List<BannerMovies> bannerMoviesList) {
bannerMoviesViewpager = findViewById(R.id.banner_viewPager);
bannerMoviesPagerAdapter = new BannerMoviesPagerAdapter(this, bannerMoviesList);
bannerMoviesViewpager.setAdapter(bannerMoviesPagerAdapter);
IndicatorTab.setupWithViewPager(bannerMoviesViewpager);
}
public void setMainRecycler(List<AllCategory>allCategoryList){
mainRecycler=findViewById(R.id.main_recycler);
RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(this,RecyclerView.VERTICAL,false);
mainRecycler.setLayoutManager(layoutManager);
mainRecyclerAdapter =new MainRecyclerAdapter(this,allCategoryList);
mainRecycler.setAdapter(mainRecyclerAdapter);
}
private void getBannerData()
{
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllBanners()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<List<BannerMovies>>() {
#Override
public void onNext(List<BannerMovies> bannerMovies) {
for ( int i=0; i < bannerMovies.size(); i++ )
{
if(bannerMovies.get(i).getBannerCategoryId().toString().equals("1"))
{
homeBannerList.add(bannerMovies.get(i));
} else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("2"))
{
tvBannerList.add(bannerMovies.get(i));
} else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("3"))
{
songBannerList.add(bannerMovies.get(i));
} else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("4"))
{
audioBannerList.add(bannerMovies.get(i));
}
else
{
homeBannerList.add(bannerMovies.get(i));
}
}
}
#Override
public void onError(Throwable e) {
Log.d("bannerData",""+e);
}
#Override
public void onComplete() {
setBannerMoviesPagerAdapter(homeBannerList);
}
})
);
}
private void getAllMoviesData(Integer categoryId)
{
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllCategoryMovies(categoryId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<List<AllCategory>>() {
#Override
public void onNext(List<AllCategory> allCategoryList) {
for ( int i=0; i < allCategoryList.size(); i++ )
{
}
setMainRecycler(allCategoryList);
}
#Override
public void onError(Throwable e) {
Log.d("bannerData",""+e);
}
#Override
public void onComplete() {
}
})
);
}
}
Itemrecycleradpater
package com.example.movieapp.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.movieapp.MovieDetails;
import com.example.movieapp.R;
import com.example.movieapp.model.CategoryItemList;
import java.util.ArrayList;
import java.util.List;
public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ItemViewHolder> implements Filterable {
Context context;
private List<CategoryItemList> categoryItemList;
private List<CategoryItemList>allCategoryListFull;
public ItemRecyclerAdapter(Context context, List<CategoryItemList> categoryItemList) {
this.context = context;
this.categoryItemList = categoryItemList;
allCategoryListFull = new ArrayList<>(categoryItemList);
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview_movies,parent,false));
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, final int position) {
Glide.with(context).load(categoryItemList.get(position).getSmallThumb()).placeholder(R.drawable.image12).into(holder.image_item);
holder.image_item.setOnClickListener(view -> {
Intent i = new Intent(context, MovieDetails.class);
i.putExtra("movieId",categoryItemList.get(position).getId());
i.putExtra("movieName",categoryItemList.get(position).getMovieName());
i.putExtra("smallThumb",categoryItemList.get(position).getSmallThumb());
i.putExtra("movieImageUrl",categoryItemList.get(position).getImageUrl());
i.putExtra("movieFile",categoryItemList.get(position).getFileUrl());
i.putExtra("MovieDesc",categoryItemList.get(position).getMovieDesc());
i.putExtra("Language",categoryItemList.get(position).getLanguage());
i.putExtra("Singers",categoryItemList.get(position).getSingers());
i.putExtra("TrailerUrl",categoryItemList.get(position).getTrailerUrl());
context.startActivity(i);
});
}
#Override
public int getItemCount() {
return categoryItemList.size();
}
#Override
public Filter getFilter() {
return filterNew;
}
private Filter filterNew = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<CategoryItemList> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() ==0){
filteredList.addAll(allCategoryListFull);
}
else{
String filterPattern = constraint.toString().toLowerCase().trim();
for(CategoryItemList item: allCategoryListFull)
{
if(item.getMovieName().toLowerCase().contains(filterPattern))
{
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
categoryItemList.clear();
categoryItemList.addAll((List)results.values);
notifyDataSetChanged();
}
};
public static final class ItemViewHolder extends RecyclerView.ViewHolder
{
ImageView image_item;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
image_item=itemView.findViewById(R.id.image_item);
}
}
}
package com.example.movieapp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.movieapp.R;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.CategoryItemList;
import java.util.List;
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {
Context context;
private List<AllCategory> allCategoryList;
public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
this.context = context;
this.allCategoryList = allCategoryList;
}
#NonNull
#Override
public MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MainViewHolder holder, int position) {
holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());
setItemRecycler(holder.itemRecycler,allCategoryList.get(position).getCategoryItemList());
}
#Override
public int getItemCount() {
return allCategoryList.size();
}
public static final class MainViewHolder extends RecyclerView.ViewHolder {
TextView categoryName;
RecyclerView itemRecycler;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.item_category);
itemRecycler = itemView.findViewById(R.id.item_recycler);
}
}
private void setItemRecycler(RecyclerView recyclerview, List<CategoryItemList> categoryItemList) {
ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context,categoryItemList);
recyclerview.setLayoutManager(new LinearLayoutManager(context,RecyclerView.HORIZONTAL,false));
//recyclerview.setLayoutManager(new GridLayoutManager(context,3));
recyclerview.setAdapter(itemRecyclerAdapter);
}
}
package com.example.movieapp.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.movieapp.R;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.CategoryItemList;
import java.util.List;
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {
Context context;
private List<AllCategory> allCategoryList;
public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
this.context = context;
this.allCategoryList = allCategoryList;
}
#NonNull
#Override
public MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MainViewHolder holder, int position) {
// Here is your call to an individual item or object like category name
holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Stuff to open new activity
List<CategoryItemList> categoryItemList = allCategoryList.get(position).getCategoryItemList()
Intent i = new Intent(context, MopvieList.class); //New screen
i.putExtra("itemList", categoryItemList); //passing serializable object
//NOTE: CategoryItemList class must implement Serializable
}
});
setItemRecycler(holder.itemRecycler, allCategoryList.get(position).getCategoryItemList());
}
#Override
public int getItemCount() {
return allCategoryList.size();
}
public static final class MainViewHolder extends RecyclerView.ViewHolder {
TextView categoryName;
RecyclerView itemRecycler;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.item_category);
itemRecycler = itemView.findViewById(R.id.item_recycler);
}
}
private void setItemRecycler(RecyclerView recyclerview, List<CategoryItemList> categoryItemList) {
ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context, categoryItemList);
recyclerview.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
//recyclerview.setLayoutManager(new GridLayoutManager(context,3));
recyclerview.setAdapter(itemRecyclerAdapter);
}
}
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<CategoryItemList> categoryItemList = allCategoryList.get(position).getCategoryItemList();
Intent i = new Intent(context, MovieCat.class); //my activity for showing all category
i.putExtra("itemList", (Serializable) categoryItemList);
context.startActivity(i);
}
public class AllCategory implements Serializable {}// as instructed made it serializable.
public class MovieCat extends AppCompatActivity {
TextView MovieCat;
String movieNameCat;
ArrayList<CategoryItemList> catItems;
RecyclerView recyclerView;
MainRecyclerAdapter mainRecyclerAdapter;
Button button;
String cat; //for item_list intent
String catId;// for intent
int categoryId;// for get all movies data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_cat);
MovieCat = findViewById(R.id.textView2);
movieNameCat = getIntent().getStringExtra("categoryTitle");
cat = getIntent().getStringExtra("itemList");
button=findViewById(R.id.view_all_btn);
MovieCat.setText(movieNameCat);
catId = getIntent().getStringExtra("categoryId"); getAllMoviesData(categoryId);
getAllMoviesData(categoryId);
}
private void getAllMoviesData(int categoryId) {
{
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllCategoryMovies(categoryId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<List<AllCategory>>() {
#Override
public void onNext(List<AllCategory> itemList) {
for (int i = 0; i < itemList.size(); i++) {
setMainRecycler(itemList);
}
}
#Override
public void onError(Throwable e) {
Log.d("bannerData", "" + e);
}
#Override
public void onComplete() {
}
})
);
}
}
public void setMainRecycler(List<AllCategory> catItems) {
recyclerView = findViewById(R.id.item_cycle);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
mainRecyclerAdapter = new MainRecyclerAdapter(this, catItems);
recyclerView.setAdapter(mainRecyclerAdapter);
}
Updated my code
#KGeeks

adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) ); this code generates error & i am unable to solve error

adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );This Line Generates Error & my knowlwdge is quite low about this error. the both required java file & the detailed error is given after this two java files.
ImageAdapter.java
package com.example.login;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context Context;
private List<Upload> Uploads;
private OnItemClickListener Listener;
public ImageAdapter (Context context, List<Upload> uploads1){
Context = context;
Uploads = uploads1;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent,int viewType) {
View v= LayoutInflater.from(Context).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder,int position) {
Upload uploadCurrent= Uploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(Context)
.load(uploadCurrent.getImageUrl())
.placeholder(R.drawable.logo)
.fit()
.centerInside()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return Uploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_product_name);
imageView = itemView.findViewById(R.id.product_image);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Listener.OnItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem details = menu.add(Menu.NONE ,1,1,"Details");
MenuItem delete = menu.add(Menu.NONE ,2,2,"Delete");
details.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch(item.getItemId()){
case 1:
Listener.OnDetailsClick(position);
return true;
case 2:
Listener.OnDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener{
void OnItemClick(int Position);
void OnDetailsClick(int Position);
void OnDeleteClick(int Position);
}
public void SetOnClickItemListener(OnItemClickListener listener){
Listener = listener;
}
}
MyAddsFragment.java
package com.example.login.ui.login;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.login.ImageAdapter;
import com.example.login.R;
import com.example.login.Upload;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyAddsFragment extends Fragment implements ImageAdapter.OnItemClickListener{
private RecyclerView recyclerView;
private ImageAdapter adapter;
private ProgressBar progressBar;
private DatabaseReference databaseRef;
private List<Upload> Uploads;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_myadds, container, false);
recyclerView = v.findViewById(R.id.Recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressBar = v.findViewById(R.id.progress_bar_1);
Uploads = new ArrayList<>();
databaseRef = FirebaseDatabase.getInstance().getReference("uploads");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot){
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Upload upload = postSnapshot.getValue(Upload.class);
Uploads.add(upload);
}
adapter = new ImageAdapter(getActivity(), Uploads);
recyclerView.setAdapter(adapter);
adapter.SetOnClickItemListener((ImageAdapter.OnItemClickListener) getActivity());
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
return v;
}
#Override
public void OnItemClick(int Position) {
Toast.makeText(getActivity(),"Normal Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDetailsClick(int Position) {
Toast.makeText(getActivity(),"Details Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDeleteClick(int Position) {
Toast.makeText(getActivity(),"Delete Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
}
Error is Given below
01-24 12:33:27.072 6252-6252/com.example.login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6252
java.lang.ClassCastException: com.example.login.HomeActivity cannot be cast to com.example.login.ImageAdapter$OnItemClickListener
at com.example.login.ui.login.MyAddsFragment$1.onDataChange(MyAddsFragment.java:57)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.0:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
....................................................................................................
your class MyAddsFragment is implementing the ImageAdapter.OnItemClickListener so to set adapter.SetOnClickItemListener you can simple use below code -
adapter.SetOnClickItemListener(MyAddsFragment.this)
You can not cast ImageAdapter.OnItemClickListener to HomeActicity.class as it might not implementing it.

Pass different data : ViewPager cards inspired by Duolingo

I just started app developing recently and stumbled upon a problem that I basically can't figure out : https://rubensousa.github.io/2016/08/viewpagercards
He instructed that on CardPagerAdapter.java in instantiateItem, I need to set the data according to the position. But how do I do it?
I want the first card to have a title of "FIRST CARD" while the second "SECOND CARD" and so on.. hope someone could help.
CardPagerAdapter.java
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class CardPagerAdapter extends PagerAdapter implements CardAdapter {
private List<CardView> mViews;
private List<CardItem> mData;
private float mBaseElevation;
public CardPagerAdapter() {
mData = new ArrayList<>();
mViews = new ArrayList<>();
}
public void addCardItem(CardItem item) {
mViews.add(null);
mData.add(item);
}
public float getBaseElevation() {
return mBaseElevation;
}
#Override
public CardView getCardViewAt(int position) {
return mViews.get(position);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.fragment_adapter, container, false);
container.addView(view);
bind(mData.get(position), view);
CardView cardView = (CardView) view.findViewById(R.id.cardView);
if (mBaseElevation == 0) {
mBaseElevation = cardView.getCardElevation();
}
cardView.setMaxCardElevation(mBaseElevation * MAX_ELEVATION_FACTOR);
mViews.set(position, cardView);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
mViews.set(position, null);
}
private void bind(CardItem item, View view) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView description = (TextView) view.findViewById(R.id.description);
Button button = (Button) view.findViewById(R.id.button);
title.setText(item.getTitle());
description.setText(item.getText());
button.setText(item.getButton());
}
}

How do i send my location online in android studio

I'm a beginner to android studio. I'm trying to build an my project app that can send my location to another client with just one click. i.e through online server.
At first I'm trying to test if my button gets the latitude and longitude value from the LocationListener.
below is my mainActivity
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
private String myLoc = " ";
GoogleMap mMap;
Button bShare;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final double Shillong_Lat = 25.5667,
Shillong_Lng = 91.8833;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1000, this);
if (servicesOK() ){
setContentView(R.layout.activity_map);
bShare = (Button) findViewById(R.id.bShare);
bShare.setOnClickListener(this);
if(initMap()) {
Toast.makeText(MainActivity.this, "Ready to map", Toast.LENGTH_SHORT).show();
gotoLocation(Shillong_Lat, Shillong_Lng, 15 );
mMap.setMyLocationEnabled(true);
}else{
Toast.makeText(this, "Map not Connected!", Toast.LENGTH_SHORT).show();
}
}else {
setContentView(R.layout.activity_main);
}
}
private void gotoLocation(double latitude, double longitude, float zoom) {
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, zoom);
mMap.moveCamera(update);
}
public boolean servicesOK(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
}else {
Toast.makeText(this, "Can't connect to map", Toast.LENGTH_SHORT).show();
}return false;
}
private boolean initMap() {
if (mMap == null){
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
}
return(mMap != null);
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MainActivity.this, "Location changed: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
myLoc = GetAddressDetailed(latitude, longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.bShare){
Toast.makeText(MainActivity.this, "Sent: " + myLat + ", " + myLon ,Toast.LENGTH_SHORT).show();
}
}
}

CursorLoader not updating listView, but cursor has correct results

I´m implementing a searchView to an pre-android 3.0 compatible app and am struggling with proper listView reloaing.
I think there is some problem with the support library, or maybe even even with my rare implementation via textChangeListener on EditText istea of onQueryTextChangedListener that I can´t use.
Any help?
Here is the code:
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
public class RecipesActivity extends SherlockFragmentActivity {
public static String category;
private ListMenu listMenu;
public static EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Sherlock);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity_layout);
getSupportActionBar().setBackgroundDrawable(getResources()
.getDrawable(R.drawable.ab_bg_black));
category=getIntent().getExtras().getString("category");
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
listMenu=new ListMenu();
ft.add(R.id.listFragment,listMenu).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Search")
.setIcon(R.drawable.search)
.setActionView(R.layout.collapsible_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS |
MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
et=(EditText)menu.getItem(0).getActionView();
return true;
}
public static class ListMenu extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor> {
private String category;
private String mCurFilter;
private MyCursorAdapter adapter;
private ContentResolver resolver;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//initialization
category=getActivity().getIntent().getStringExtra("category");
setHasOptionsMenu(true);
resolver = this.getActivity().getContentResolver();
final Cursor cursor;
String[] projection=
{BaseColumns._ID,Recipes.NAME,Recipes.KEYWORDS,Recipes.STARRED};
if(category.equals("xxx")){
cursor = resolver.query(Recipes.CONTENT_URI_DRINKS, projection, null, null,
Recipes.STARRED);
} else
if(category.equals("yyy")){
cursor = resolver.query(Recipes.CONTENT_URI_HANGOVERS, projection, null, null,
Recipes.STARRED);
} else
{cursor = resolver.query(Recipes.CONTENT_URI_GAMES, projection, null, null,
Recipes.STARRED);
}
//getActivity().getSupportLoaderManager().initLoader(0, null, this);
getLoaderManager().initLoader(0, null, this);
adapter=new MyCursorAdapter(getActivity(), cursor, true);
setListAdapter(adapter);
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text=s.toString();
String newFilter = (String) (!TextUtils.isEmpty(text) ? text : null);
Log.i("text changed listener","ontextchanged:"+newFilter);
if (mCurFilter == null && newFilter == null){;}else
if(mCurFilter != null && mCurFilter.equals(newFilter)){;}else
{
mCurFilter = newFilter;
getLoaderManager().restartLoader(0, null, ListMenu.this);
Log.i("QueryListMenu","onQueryTextChange");
}
}
#Override public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent=new Intent(getActivity(),Viewer.class);
String[] projection = {Recipes.PATH };
String selection= "("+BaseColumns._ID+"="+id+")";
Cursor c=resolver.query(Recipes.getUri(category), projection, selection, null,
Recipes.STARRED+"DESC"+","+Recipes.NAME+" ASC");
c.moveToFirst();
String path=c.getString(c.getColumnIndex("path"));
intent.putExtra("path", category+"/"+path);
Log.i("onlistitemclick","path:"+path+" with id:"+id);
startActivity(intent);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Uri firstUri=Recipes.getUri(category);
String selection;
String[] projection = {BaseColumns._ID,Recipes.NAME,Recipes.STARRED};
if (mCurFilter != null) {
selection = "(" + Recipes.NAME + " NOTNULL) AND ("
+ Recipes.KEYWORDS + " like '%"+mCurFilter+"%')";
} else {
selection=null;
}
CursorLoader cursorLoader = new CursorLoader(getActivity(),
firstUri, projection, selection, null, Recipes.STARRED+"
DESC"+","+Recipes.NAME+" ASC");
Log.i("recipes activity","mCurFilter="+mCurFilter);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.changeCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.changeCursor(null);
}
}
So the magic was in just a few lines.
You must add a FilterQueryProvider to the adapter:
adapter=new MyCursorAdapter(this, c, true);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
String[] projection = { Recipes._ID, Recipes.NAME, Recipes.KEYWORDS,
Recipes.PATH, Recipes.STARRED };
String selection = Recipes.KEYWORDS + " like '%" + constraint.toString() +"%'";
return getContentResolver().query(Recipes.getUri(cat),projection,
selection, null, Recipes.STARRED + " DESC"
+ "," + Recipes.NAME + " ASC");
}
});

Resources