I am trying to use the pedometer sensor in a fragment to count the number of steps that has been taken since the device last rebooted.
I can get the pedometer working in an Activity but cannot seem to get it working in the fragment. I am new to using fragments so it's probably very simple what I am doing wrong.
My class is below:
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import static com.example.application.placepicker.R.id.count;
public class Tab3 extends Fragment implements SensorEventListener {
private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
count = (TextView) getActivity().findViewById(count); **error
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); **error
}
#Override
public void onResume() {
super.onResume();
activityRunning = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show(); **error
}
}
#Override
public void onPause() {
super.onPause();
activityRunning = false;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (activityRunning) {
count.setText(String.valueOf(event.values[0])); **error
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
My XML file to accompany this is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="114dp"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Step counter"
android:textSize="40sp"
android:textColor="#color/colorAccent"
android:fontFamily="sans-serif"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="33dp"
android:layout_gravity="center_horizontal"
android:textSize="26dp"
android:text="Steps walked so far today:"
android:textColor="#color/colorAccent" />
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginLeft="50dp"
android:text="---"
android:textColor="#color/colorAccent"
android:textSize="36dp" />
</LinearLayout>
You have no member variable for count
private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;
are examples of member variables in your fragment class
count = (TextView) getActivity().findViewById(count);
is setting a TextView to an unknown reference, please initialise count properly i.e.
TextView count = (TextView) getActivity().findViewById(count);
as a function member or:
private TextView count;
with the other class member variables
you will then need to call
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE)
as a fragment has no reference to the getSystemService method by itself, so it needs to go through it's holding activity
as well i know
you should change
count = (TextView) getActivity().findViewById(count);
to
count = (TextView)getView().findViewById(R.id.count);
cause you have to define view , don't call activity.
Related
So, I tried putting a recyclerView in a "popup" dialog using a firebaseRecyclerAdapter.
My problem is, that I know for sure the adapter gets filled because I was using the Logcat to tell me when it adds another "user" to the adapter, but it wont show anything in the recyclerview in the dialog.
I'm having this problem for a couple of days and couldn't find an answer yet, glad if you could help me :)
I'm using a main screen which changes fragments, and from a certain fragment I'm calling this specific dialog.
These are my files:
UserViewHolder - the class which holds the "sets" for the cardview:
public static class UserViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UserViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setName(String name)
{
TextView teacherName=(TextView) mView.findViewById(R.id.txtNameTea);
teacherName.setText(name);
}
public void setEmail(String email)
{
TextView txtEmailTea=(TextView) mView.findViewById(R.id.txtEmailTea);
txtEmailTea.setText(email);
}
public void setImage(final Context ctx, Uri imageUri, User cUser)
{
final ImageView imgProfileTea=(ImageView) mView.findViewById(R.id.imgProfileTea);
Picasso.with(ctx).load(cUser.getImageUri()).into(imgProfileTea);
if(imgProfileTea.getDrawable()==null) {
StorageReference load = FirebaseStorage.getInstance().getReference().child("usersProfilePic/" + cUser.getImageName());
load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri.toString()).into(imgProfileTea);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG);
}
});
}
}
}
Schedules - the fragment which calls the dialog from its toolbar:
package com.example.android.aln4;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.example.android.aln4.LoginActivity.myUser;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static java.lang.System.in;
import static com.example.android.aln4.navDrawerMain.studentsQuery;
public class Schedules extends Fragment {
private Toolbar ScheduleToolbar;
private Button addEvent;
//private TextView txt;
private RecyclerView mRecyclerViewStudentEvent;
private CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM-yyyy", Locale.getDefault());
private String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addEvent:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
mRecyclerViewStudentEvent = (RecyclerView) mView.findViewById(R.id.mRecyclerViewStudentEvent);
mRecyclerViewStudentEvent.setHasFixedSize(true);
mRecyclerViewStudentEvent.setLayoutManager(new LinearLayoutManager(getContext()));
setStudentsList();
mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
final EditText edtEventTitle = (EditText) mView.findViewById(R.id.edtEventTitle);
final TextView txtEventStartTime = (TextView) mView.findViewById(R.id.txtEventStartTime);
final TextView txtEventEndTime = (TextView) mView.findViewById(R.id.txtEventEndTime);
final EditText edtEventLocation = (EditText) mView.findViewById(R.id.edtEventLocation);
Button btnOfferEvent = (Button) mView.findViewById(R.id.btnOfferEvent);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
btnOfferEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int startHour = Integer.parseInt(txtEventStartTime.getText().toString().substring(0, 2));
int startMinute = Integer.parseInt(txtEventStartTime.getText().toString().substring(3, 5));
startTime.set(Calendar.HOUR_OF_DAY, startHour);
startTime.set(Calendar.MINUTE, startMinute);
int endHour = Integer.parseInt(txtEventEndTime.getText().toString().substring(0, 2));
int endMinute = Integer.parseInt(txtEventEndTime.getText().toString().substring(3, 5));
endTime.set(Calendar.HOUR_OF_DAY, endHour);
endTime.set(Calendar.MINUTE, endMinute);
String mId =/*dataSelected+*/ String.valueOf(startHour) + String.valueOf(startMinute);//+selectedUserID
EventCreation newEvent = new EventCreation(mId, startTime, endTime, edtEventTitle.getText().toString(), edtEventLocation.getText().toString(), R.color.colorPrimary);
dialog.dismiss();
}
});
dialog.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
ScheduleToolbar = (Toolbar) getView().findViewById(R.id.schedule_toolbar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
((AppCompatActivity) getActivity()).setSupportActionBar(ScheduleToolbar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
int year = cal.get(Calendar.YEAR);
getActivity().setTitle(month + "-" + year);
compactCalendar = (CompactCalendarView) getView().findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
long millis = System.currentTimeMillis() % 1000;
Event ev1 = new Event(Color.RED, millis, "First try");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
//put events into scroll view adapter
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getActivity().setTitle(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedules, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
private void setStudentsList() {
studentsQuery=mDatabaseReference.orderByChild("teacherNum").equalTo(myUser.getTeacherNum());
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,studentsQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName() + " " + model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()), model);
}
};
mRecyclerViewStudentEvent.setAdapter(firebaseRecyclerAdapter);
}
}
The dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/title"/>
<EditText
android:id="#+id/edtEventTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="כותרת"
android:layout_marginRight="50dp"/>
<android.support.v7.widget.RecyclerView
android:layout_marginTop="50dp"
android:id="#+id/mRecyclerViewStudentEvent"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/clock"/>
<TextView
android:layout_width="wrap_content"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="שעת התחלה"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="50dp"
android:layout_marginTop="5dp"
android:text="21:00" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="25dp"
android:layout_marginRight="50dp"
android:background="#color/darkgray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:text="שעת סיום"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventEndTime"
android:layout_width="match_parent"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="30dp"
android:text="21:45" />
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/location"/>
<EditText
android:id="#+id/edtEventLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="מיקום תחילת השיעור"
android:layout_marginRight="50dp"/>
</RelativeLayout>
<Button
android:id="#+id/btnOfferEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="הצע שיעור"/>
</LinearLayout>
One more thing is that I know is that I'm already able to bring up users into the recyclerView in other fragments.. Here's the code in another fragment:
package com.example.android.aln4;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static com.example.android.aln4.navDrawerMain.teachersQuery;
public class TeachersList extends Fragment {
private RecyclerView mRecyclerViewTeacher;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("מורים");
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
mRecyclerViewTeacher=(RecyclerView) getView().findViewById(R.id.mRecyclerViewTeacher);
mRecyclerViewTeacher.setHasFixedSize(true);
mRecyclerViewTeacher.setLayoutManager(new LinearLayoutManager(getContext()));
setTeachersList();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.teachers_list_frag,container,false);
}
private void setTeachersList() {
teachersQuery=mDatabaseReference.orderByChild("type").equalTo("Teacher");
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,teachersQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName()+" "+model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()),model);
}
};
mRecyclerViewTeacher.setAdapter(firebaseRecyclerAdapter);
}
}
and its xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecyclerViewTeacher"
android:layout_marginTop="57dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
It's one of my first questions here so I apologize if I missed something :)
Any help would be appriciated.
Solved. All I did was regenerating the SHA1 in the firebase settings, and removing the setHasFixedSize line from Schedules activity and it worked just fine.
In my android app I have an image slider using viewpager,which changes images every 2.5 seconds in the main activity,it works fine when I open the app,but the problem is when I jump to another Activity from the MainActivity and come back it,starts to move the images in the slides very fast,as much as I jump to another activity the sliding become more faster.please help.
This is where I have included my 3 slider images
slidelist.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/image1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidetwo"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slideone"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidethree"
android:scaleType="centerCrop"/>
</FrameLayout>
This the slider layout in content main.xml(included in activity)
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_below="#+id/linearone">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
The following is the adpater class
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.rimapps.icar_iisr_turmeric.R;
import java.util.ArrayList;
public class SlideAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public SlideAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slidelist, view, false);
ImageView myImage1 = (ImageView) myImageLayout.findViewById(R.id.image1);
ImageView myImage2 = (ImageView) myImageLayout.findViewById(R.id.image2);
ImageView myImage3 = (ImageView) myImageLayout.findViewById(R.id.image3);
myImage1.setImageResource(images.get(position));
myImage2.setImageResource(images.get(position));
myImage3.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
This is my MainActivity class and here I have defined the timer for the slider
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.internal.NavigationMenuItemView;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.example.rimapps.icar_iisr_turmeric.R;
import com.example.rimapps.icar_iisr_turmeric.control.ButtonAdapter;
import com.example.rimapps.icar_iisr_turmeric.control.SlideAdapter;
import com.example.rimapps.icar_iisr_turmeric.model.ContentsDep;
import com.example.rimapps.icar_iisr_turmeric.utils.LocaleHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import me.relex.circleindicator.CircleIndicator;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
CircleIndicator indicator;
int period=2500, delay = 2500;
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] slide = {R.drawable.slideone, R.drawable.slidetwo, R.drawable.slidethree};
private ArrayList<Integer> slidearray = new ArrayList<Integer>();
Timer swipeTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//Image slider function//
private void init() {
for (int i = 0; i < slide.length; i++)
slidearray.add(slide[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new SlideAdapter(MainActivity.this, slidearray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == slide.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer =new Timer();
swipeTimer.schedule(new
TimerTask() {
#Override
public void run () {
Log.d("hjgv","yughi");
handler.post(Update);
}
},delay,period);
}
#Override
protected void onStop() {
super.onStop();
// swipeTimer.cancel();
delay=0;
period=0;
}
#Override
protected void onRestart() {
super.onRestart();
delay=2500;
period=2500;
}
}
The problem is in your Timer.
when you go another fragment or activity then back to that fragment you must have to cancel your timer ondestroyview because when you back to fragment your oncreateview is call again so timer are initialise and then speed is multiple by 2 time.this happens everytime.
This code in kotlin.
override fun onDestroyView() {
if(swipeTimer != null) {
swipeTimer.cancel()
}
super.onDestroyView()
}
Hope this help you
Just call cancel the instance of Timer in your ondestryView() method
#Override
public void onDestroyView() {
super.onDestroyView();
if(swipeTimer != null) {
swipeTimer.cancel();
}
}
Here is the code I'm using to read the heart rate from a wearable :
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.widget.TextView;
import android.hardware.*;
import android.support.wearable.view.BoxInsetLayout.*;
public class MainActivity extends WearableActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewHeart;
SensorManager mSensorManager;
Sensor mHeartRateSensor;
SensorEventListener sensorEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mTextViewHeart = new TextView(this);
mTextViewHeart.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mTextViewHeart.setText("heart rate ");
mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
// mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
Log.i(TAG, "LISTENER REGISTERED.");
mTextViewHeart.setText("Something here");
mSensorManager.registerListener(this, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
// mSensorManager.registerListener(sensorEventListener, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
}
public void onResume(){
super.onResume();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int)event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
}
else
Log.d(TAG, "Unknown sensor type");
}
}
main_activity.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<android.support.wearable.view.GridViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.wearable.view.DotsPageIndicator
android:id="#+id/page_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:padding="5dp"
android:background="#drawable/rounded_background">
</android.support.wearable.view.DotsPageIndicator>
</RelativeLayout>
The sensor functionality seems fine. The text boxes are not being displayed on screen, instead I just receive a blank screen. How to add mTextViewHeart to the screen programmatically ? Or is required that I add it via main_activity.xml ?
Update :
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.hardware.*;
import android.support.wearable.view.BoxInsetLayout.*;
public class MainActivity extends WearableActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewHeart;
SensorManager mSensorManager;
Sensor mHeartRateSensor;
SensorEventListener sensorEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
RelativeLayout relativeLayout = (RelativeLayout )findViewById(R.id.parent);
mTextViewHeart = new TextView(this);
mTextViewHeart.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mTextViewHeart.setText("heart rate ");
mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
Log.i(TAG, "LISTENER REGISTERED.");
mTextViewHeart.setText("Something here");
mSensorManager.registerListener(this, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
relativeLayout.addView(mTextViewHeart);
}
public void onResume(){
super.onResume();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int)event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
}
else
Log.d(TAG, "Unknown sensor type");
}
}
main_activity.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<android.support.wearable.view.GridViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.wearable.view.DotsPageIndicator
android:id="#+id/page_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:padding="5dp"
android:background="#drawable/rounded_background">
</android.support.wearable.view.DotsPageIndicator>
</RelativeLayout>
I've updated with Pavneet Singh answer but blank screen displayed.
Maybe should configure all UI via XML ?
Update2 :
Updating to use linearlayout does not have an impact :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<android.support.wearable.view.GridViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.wearable.view.DotsPageIndicator
android:id="#+id/page_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:padding="5dp"
android:background="#drawable/rounded_background">
</android.support.wearable.view.DotsPageIndicator>
</LinearLayout>
package com.example.android.wearable.datalayer;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.hardware.*;
import android.support.wearable.view.BoxInsetLayout.*;
public class MainActivity extends WearableActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewHeart;
SensorManager mSensorManager;
Sensor mHeartRateSensor;
SensorEventListener sensorEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
LinearLayout relativeLayout = (LinearLayout )findViewById(R.id.parent);
mTextViewHeart = new TextView(this);
mTextViewHeart.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mTextViewHeart.setText("heart rate ");
mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
Log.i(TAG, "LISTENER REGISTERED.");
mTextViewHeart.setText("Something here");
mSensorManager.registerListener(this, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
relativeLayout.addView(mTextViewHeart);
}
public void onResume(){
super.onResume();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int)event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
}
else
Log.d(TAG, "Unknown sensor type");
}
}
Adding an edittext field also does not display :
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="121dp"
android:ems="10"
android:text="test"
/>
Could the issue be something fundamental ?
This screen layout displays :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click me to another screen" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="I'm screen 1 (main.xml)"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
I have just started learning android. I have develop a program named Android Light Sensor that measure the Intensity of Light. Here is my code:
package com.AndroidLightSensor;
import com.example.andriodlightsensor.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class AndriodLightSensorActivity extends Activity {
ProgressBar lightMeter;
TextView textMax, textReading;
float counter;
Button read;
TextView display;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
counter = 0;
read = (Button) findViewById(R.id.bStart);
display = (TextView) findViewById(R.id.tvDisplay);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lightMeter = (ProgressBar)findViewById(R.id.lightmeter);
textMax = (TextView)findViewById(R.id.max);
textReading = (TextView)findViewById(R.id.reading);
SensorManager sensorManager
= (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor lightSensor
= sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor == null){
Toast.makeText(AndriodLightSensorActivity.this,
"No Light Sensor! quit-",
Toast.LENGTH_LONG).show();
}else{
float max = lightSensor.getMaximumRange();
lightMeter.setMax((int)max);
textMax.setText("Max Reading(Lux): " + String.valueOf(max));
sensorManager.registerListener(lightSensorEventListener,
lightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
SensorEventListener lightSensorEventListener
= new SensorEventListener(){
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType()==Sensor.TYPE_LIGHT){
final float currentReading = event.values[0];
lightMeter.setProgress((int)currentReading);
textReading.setText("Current Reading(Lux): " + String.valueOf(currentReading));
read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
display.setText("" + String.valueOf(currentReading));
}
});
}
}
};
}
Also The xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDisplay"
/>
<ProgressBar
android:id="#+id/lightmeter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="80dp"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:progress="0"
/>
<TextView
android:id="#+id/max"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/reading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Start"
android:layout_y="249dp"
android:textSize="30dp"
android:onClick="onButtonDown"
android:id="#+id/bStart"
></Button>
</LinearLayout>
I want to get the current value whenever I press the button; i:e the value should not keep changing (Like in Stop Watch, but the updated should replace the previous one). In Eclipse, It shows no error, but when I run on my device is says" Unfortunately, Android Light Sensor has stopped."
Please help!!
There are an error that is obvious.
If findViewById is used before setContentView(R.layout.main); the values returned are null.
When you try to use them you get an error.
Put this two lines after setContentView(R.layout.main);
read = (Button) findViewById(R.id.bStart);
display = (TextView) findViewById(R.id.tvDisplay);
I have just copied the official example, and my dialog is very narrow. Why?
My code.
The dialog.
package com.redplanet;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditNameDialog extends DialogFragment implements OnEditorActionListener {
public interface EditNameDialogListener {
void onFinishEditDialog(String inputText);
}
private EditText mEditText;
public EditNameDialog() {
// Empty constructor required for DialogFragment
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_name, container);
mEditText = (EditText) view.findViewById(R.id.txt_your_name);
getDialog().setTitle("Hello");
// Show soft keyboard automatically
mEditText.requestFocus();
getDialog().getWindow().setSoftInputMode(
LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mEditText.setOnEditorActionListener(this);
return view;
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
// Return input text to activity
EditNameDialogListener activity = (EditNameDialogListener) getActivity();
activity.onFinishEditDialog(mEditText.getText().toString());
this.dismiss();
return true;
}
return false;
}
}
The activity.
package com.redplanet;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.widget.Toast;
import com.redplanet.EditNameDialog.EditNameDialogListener;
public class FragmentDialogDemo extends FragmentActivity implements EditNameDialogListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showEditDialog();
}
private void showEditDialog() {
FragmentManager fm = getSupportFragmentManager();
EditNameDialog editNameDialog = new EditNameDialog();
editNameDialog.show(fm, "fragment_edit_name");
}
#Override
public void onFinishEditDialog(String inputText) {
Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
}
Activity layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="#string/hello_world"
tools:context=".FragmentDialogDemo" />
</RelativeLayout>
Dialog layout file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/edit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/lbl_your_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your name" />
<EditText
android:id="#+id/txt_your_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="text" />
</LinearLayout>
In order not to puzzle over workarounds, I'd prefer an AlertDialog to a DialogFragment. The issue I asked about was on Android 2.3.6 and wasn't on Android 4.1.2.