I am currently working on a light sensor. I managed to make the sensor work. But I want to change the value of the sensor being shown by multiplying it with 0.002 with a press of a button. I can't seem to get the code of the button to multiply because it keeps saying operator (*) cannot be applied to java.lang.String, double. I have tried the double.parse but can't seems to get to work. Here is my code:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView textView;
SensorManager sensorManager;
Sensor sensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
sensorManager = (SensorManager) getSystemService(Service.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Button button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View multiply) {
textView.setText(Integer.parseInt(textView.getText().toString()*0.002));
}
});
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_LIGHT) {
textView.setText("" + sensorEvent.values[0]);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
Related
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"/>
appreciate if you can help me here.
I am creating a To Do List, where the ListView is in the MainToDoList Activity with a "Add a new Task" button that takes the user to the second activity.
In the second activity, there is a Edit Text field where user can input the title of the task. Two buttons are "Save" and "Cancel"
My question is, how to pass the edit text value after pressing the save button to display it into the listview in the first activity.
First Activity:
public class Todolistactivity extends AppCompatActivity {
private Button btn;
private ListView list;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.todolistactivity);
btn = findViewById(R.id.addTask);
list = findViewById(R.id.task_list);
}
private void addTask() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Todolistactivity.this, EditToDo.class));
}
});
}
Second Activity:
public class EditToDo extends Todolistactivity {
private static final String TAG = "EditToDo";
private Button save;
private Button cancel;
private EditText title;
#Override
protected void onCreate (Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.activity_taskedit);
save = findViewById(R.id.saveTask);
cancel = findViewById(R.id.cancelTask);
title = findViewById(R.id.taskTitle);
saveButton();
cancelButton();
}
private void saveButton(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent backToDo = new Intent
(getBaseContext(),Todolistactivity.class);
String titleEntered = title.getText().toString();
backToDo.putExtra("task", titleEntered);
startActivity(backToDo);
}
});
}
Use startActivityForResult
in your Todolistactivity class
private void addTask() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(Todolistactivity.this, EditToDo.class), 100); // 100 is request code.
}
});
}
//...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String result = data.getStringExtra("task");
}
else if (resultCode == Activity.RESULT_CANCELED) {
//...
}
}
}
In Your EditToDo class
private void saveButton(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String titleEntered = title.getText().toString();
Intent intent = new Intent();
intent.putExtra("task", titleEntered);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}
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
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.
I am developing a simple app in that my video is playing proper. but now I want to give "thank" message after finishing my video
How can I do this?
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
this.setSupportActionBar(toolbar);
final MediaPlayer player = MediaPlayer.create(MainActivity.this,R.raw.video);
Button button = (Button)findViewById(R.id.video_Play);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
player.start();
startActivity(new Intent("com.example.lenovo.play.app.VideoPlay"));
}
});
}
and Second VideoPlay.java
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.video_layout);
view = (VideoView)findViewById(R.id.videoView);
String url = "android.resource://"+getPackageName()+"/"+R.raw.video;
view.setVideoURI(Uri.parse(url));
view.start();
int duration = view.getDuration();
}
Implement MediaPlayer.OnCompletionListener then add your message to onCompletion method:
#Override
public void onCompletion(MediaPlayer mp) {
//message
}