Step Counter in Android Studio doesn't count steps - android-studio

I have a problem with an app I'm trying to develop in Android Studio. I'm trying to develop a step counter using the STEP_COUNTER sensor in a Fragment.I decided to show my results in a TextView ('mStepsSinceReboot'), but it keeps being empty. Do you have any idea on how to make it work?
An hypotesis is that I should use a Service, but online I only found implementations that don't require it.
Thanks in advance for your answer. This is the code of my Fragment.
public class StepFragment extends Fragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepCounter;
private boolean isSensorPresent;
private TextView mStepsSinceReboot;
public StepFragment() {
// Required empty public constructor
}
public static StepFragment newInstance(String param1, String param2) {
StepFragment fragment = new StepFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.fragment_step, container, false);
mStepsSinceReboot=v.findViewById(R.id.stepssincereboot);
mSensorManager=(SensorManager) this.getActivity().getSystemService(getContext().SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
mStepCounter=mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
isSensorPresent=true;
}
else{
isSensorPresent=false;
}
return v;
}
#Override
public void onSensorChanged(SensorEvent event) {
mStepsSinceReboot.setText(("Steps since reboot: "+String.valueOf(event.values[0])));
Log.d("Passi", String.valueOf(mStepsSinceReboot));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onResume(){
super.onResume();
if(isSensorPresent){
mSensorManager.registerListener(this,mStepCounter,SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public void onPause(){
super.onPause();
if(isSensorPresent){
mSensorManager.unregisterListener(this);
}
}
#Override
public void onDestroy(){
super.onDestroy();
mSensorManager=null;
mStepCounter=null;
}
}

you added the permission in the manifest file ?
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>

Related

how to fix error 'int java.util.List.size()'

I am all time worked by one source! but now get error
int java.util.List.size()
now my adapter source its :
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.msgsViewHoler> {
List<QueryMessages> queryMessages;
Context mtContext;
public MessagesAdapter(List<QueryMessages> queryMessages, MainActivity mainActivity){
this.queryMessages=queryMessages;
}
#NonNull
#Override
public msgsViewHoler onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.message_row,parent,false);
return new msgsViewHoler(view);
}
#Override
public void onBindViewHolder(#NonNull msgsViewHoler holder, int position) {
final QueryMessages queryMessageses=queryMessages.get(position);
Picasso.get()
.load(queryMessageses.getMpic())
.error(R.mipmap.ic_launcher)
.fit()
.into(holder.mpic);
holder.mname.setText(queryMessageses.getMname());
holder.message.setText(queryMessageses.getMessage());
holder.tarikh.setText(queryMessageses.getTarikh());
}
#Override
public int getItemCount() {
return queryMessages.size();
}
public class msgsViewHoler extends RecyclerView.ViewHolder{
int id;
CardView parent;
ImageView mpic;
TextView mname,message,tarikh;
public msgsViewHoler(View itemView) {
super(itemView);
parent=itemView.findViewById(R.id.message_row);
mpic=itemView.findViewById(iv_profile);
mname=itemView.findViewById(R.id.tv_mastername);
message=itemView.findViewById(R.id.tv_msg);
tarikh=itemView.findViewById(R.id.tv_date);
}
}
and give this error :
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at ir.arvandit.channeleto.adapter.MessagesAdapter.getItemCount(MessagesAdapter.java:62)
thats line is :
return queryMessages.size();
my Activity Main its :
RecyclerView rvmsg;
CardView message_row;
List<QueryMessages> queryMessages;
MessagesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cast();
onClick();
ApiService service=ApiClient.getClient().create(ApiService.class);
Call<List<QueryMessages>> call=service.getQueryMessages();
call.enqueue(new Callback<List<QueryMessages>>() {
#Override
public void onResponse(Call<List<QueryMessages>> call, Response<List<QueryMessages>> response) {
pros.setVisibility(View.GONE);
queryMessages=response.body();
adapter=new MessagesAdapter(queryMessages,MainActivity.this);
rvmsg.setAdapter(adapter);
}
#Override
public void onFailure(Call<List<QueryMessages>> call, Throwable t) {
pros.setVisibility(View.GONE);
nonet.setVisibility(View.VISIBLE);
}
});
}
public void cast(){
rvmsg=findViewById(R.id.rv_message);
rvmsg.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
}
now I need help for fix this error!
Issue is in bellow code
private static final String TAG = "CurrentActivity";
#Override
public void onResponse(Call<List<QueryMessages>> call,
Response<List<QueryMessages>> response) {
Log.v(TAG, "onResponse=" + response.body().toString());
}
check weather response.body() or response is the ArrayList of <List<QueryMessages>>
in new version retrofit if in your json have free parameter , get this error
for example i need id,name,number
but in my json have id,name,number,date ....
i give this error!
and some time if in ApiService have false url!
tanks for help all

Tracking selected tab and changing a textview accordingly

I'm working on my 1st android project, which uses a tab layout. I want to keep track of the active tab and change a textview present in the appbar (main activity).
Here is my main activity, tab manager, and a fragment
MAIN ACTIVITY
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.Tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.tab_rooms_24dp);
tabLayout.getTabAt(1).setIcon(R.drawable.tab_feed_24dp);
tabLayout.getTabAt(2).setIcon(R.drawable.tab_profile_24dp);
tabLayout.getTabAt(0).getIcon().setColorFilter(getResources().getColor(R.color.Accent), PorterDuff.Mode.SRC_IN);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(getResources().getColor(R.color.Accent),PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().clearColorFilter();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "");
adapter.addFragment(new Tab2Fragment(), "");
adapter.addFragment(new Tab3Fragment(), "");
viewPager.setAdapter(adapter);
}
TAB MANAGER
private final List<Fragment> mFragmentList =new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title );
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
FRAGMENT
private static final String TAG = "Tab3Fragment";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab1,container,false);
return view;
}
I tried creating a variable in an abstract class then extending it into all three of these scripts which would be a simple solution but fragments dont seem to work well with extending, not to mention that probably isnt the most efficient method.
So I'm thinking the best method would be to simply handle it from the SectionsPageManager script?
Use addOnPageChangeListener on you pager.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 1) {
setTitle("Tab 1");
} else if (position == 2)
{
setTitle("Tab 2");
}
else
{
setTitle("Home");
}
}
So I got it worked out and figured I'd come post the answer for anyone who may need it.
Not that the above answer sets the app title, not a TextView withing the appbar as stated in the question.
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
private TextView activeTab;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activeTab = (TextView)findViewById(R.id.PageTitle);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager)
{
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "");
adapter.addFragment(new Tab2Fragment(), "");
adapter.addFragment(new Tab3Fragment(), "");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
#Override
public void onPageSelected(int position)
{
switch (position){
case 0: activeTab.setText("text");
break;
case 1: activeTab.setText("better text");
break;
case 2: activeTab.setText("best text");
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}

How to implement onActivityResult within RecyclerView Fragment

I am trying to have a button within a Tab which is part of an activity for uploading images, when clicking the button inside one of the 2 Tabs presented in the activity ( Tab 1 pics, Tab 2 Vid ) the user could choose an image from the device.
My problem is implemneting the onClick Listener and onActivityResult which is not being used when placed after onClick, plus the #Override is being underlined as an error.
I guess i am not implementing the onClick the right way and not sure how to activate onActivityResult the proper way, i would appreciate any guidance;
MainActivty;
public class upload extends AppCompatActivity {
public String UserID;
private static final int REQUEST_SIGNUP = 0;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
Firebase.setAndroidContext(this);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new UploadPictures(), "Pictures");
adapter.addFragment(new UploadVideos(), "Videos");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And here is the Fragment Code;
public class UploadPictures extends android.support.v4.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView picture;
public EditText tagEditText;
public Button tagCurLoc, choosePic, uploadContent;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.pictue_upload, parent, false));
picture = (ImageView) itemView.findViewById(R.id.imgToUpload);
tagEditText = (EditText) itemView.findViewById(R.id.tagEditText);
tagCurLoc = (Button) itemView.findViewById(R.id.tagCurLoc);
choosePic = (Button) itemView.findViewById(R.id.choosePic);
choosePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
onActivityResult(requestCode, resultCode, data);
Toast.makeText(getActivity().getApplicationContext(), "Canceled ", Toast.LENGTH_SHORT).show();
} else {
if (requestCode == RESULT_LOAD_IMAGE) {
Uri selectedImgPath = data.getData();
picture.setImageURI(selectedImgPath);
RealFilePath = Uri.parse(String.valueOf(selectedImgPath));
Toast.makeText(getActivity().getApplicationContext(), " " + RealFilePath, Toast.LENGTH_SHORT).show();
}
}
}
});
uploadContent = (Button) itemView.findViewById(R.id.uploadContent);
}
}
/**
* Adapter to display recycler view.
*/
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private Context mContext;
public ContentAdapter(Context context) {
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return LENGTH;
}
}
Not sure if the onClick listener for the button should be implemented in the Adapter or the View holder, and from there the issue of onActivityResult cant be used ?
Weel, solved after some more reading and few try outs.
The onClick listener should be implemented at the ViewHolder class followed by
#Override
onActivityResult.
within the onClickListener onActivityResult invoked by;
startActivityForResult(intent, RESULT_LOAD_IMAGE);
and within onActivityResult;
onActivityResult(requestCode, resultCode, data);
Considering all of this taking place in an activity extending Fragment.

How to pass data from activity to fragment?

I'm creating a basic app and i stucked at this point where I'm unable to pass data from an activity to fragment.
EmailPage.java
public class EmailPage extends AppCompatActivity{
ImageButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emailpage);
btn = (ImageButton) findViewById(R.id.emailButton);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(EmailPage.this, YourName.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
});
}
}
Email Page
NavHeaderMainMenu1.java
public class NavHeaderMainMenu1 extends Fragment {
public NavHeaderMainMenu1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.nav_header_main_menu1, container , false);
}
}
NavHeaderMainMenu1

ActionBar.Tablistener deprecated

I'm trying to build a swipe tabs view by using fragment activity and actionbar.tablistener. I have referenced other people tutorial and do it, however, it keep on deprecated and do not successful run it. Then I changed to AppComBatActivity and it do not works, show viewgroup error which I don't know why. THen I changed to ActionBarActivity, it worked finally, but no matter how I edit my tab activity, in java class and xml too, it does not show anything.
I have actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) deprecated as well.
I have attached my code as following...
fragmentmenu.class
public class FragmentMenu extends FragmentActivity implements ActionBar.TabListener {
ActionBar actionBar;
ViewPager viewPager;
FragmentPageAdapter ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_menu);
viewPager = (ViewPager)findViewById(R.id.pager);
ft = new FragmentPageAdapter(getSupportFragmentManager());
actionBar = getActionBar();
viewPager.setAdapter(ft);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("Menu").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Report").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Setting").setTabListener(this));
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}
</code>
FragmentPagerAdapter
<code>
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new MyActivity();
case 1:
return new Report();
case 2:
return new Setting();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
</code>
One of the fragment
<code>
public class Report extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.report, container, false);
}
}
}}
Please help!
ActionBar.Tablistener is deprecated. You need to use the TabLayout instead.
Check this tutorial for more infos :
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

Resources