My Android App is crashed when I register SensorManager.registerListener - sensormanager

Below is my code. I am having a problem when I call SensorManager.registerListener, my app will crash. Can someone tell me what's going on?
I just follw the web guide to setup SensorManger, Sensor(Accelerometer) and then register the action lintener to detect the montion of accelerometer.
I used API 21 to develop this app.
public class MainActivity extends ActionBarActivity implements SensorEventListener{
private TextView tip;
private SensorManager mSensorManager;
private Sensor mSensor;
private float axisX = 0;
private float axisY = 0 ;
private float axisZ = 0;
#Override
protected void onResume() {
super.onResume();
setUpAcceleratorSensor();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpAcceleratorSensor();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpAcceleratorSensor(){
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if((mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null);
else
Toast.makeText(this, "No Sensor Device Exist", Toast.LENGTH_LONG).show();
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[0] != 0 || event.values[1] != 0 || event.values[2] != 0){
axisX = event.values[0];
axisY = event.values[1];
axisZ = event.values[2];
tip.setText("Detect your montion");
}
}
else
Toast.makeText(this, "Cannot Get Sensor Device", Toast.LENGTH_LONG).show();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Thanks.

First that I always check when something like this goes wrong, is to check that you have all the correct permissions in the Android Manifest; however, I don't believe that there are any permissions associated with using the position sensors. I would check on this first. That is what comes to mind first, after you post logcat, we will be able to give a more detailed answer.

Try getting the sensor this way
mSensor = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0); instead in your setUpAccelerometer() method.

Related

SupportMapFragmentManagers getMapAsync() does not trigger onMapReady(GoogleMap map)

I have a
public abstract class MyMapFragment implements OnMapReadyCallback
{
//
public GoogleMap googleMap;
SupportMapFragment mapFragment;
#IdRes
public abstract int getSupportMapFragId();
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// http://stackoverflow.com/a/36592000/5102206
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// Do something for lollipop and above versions
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(getSupportMapFragId());
} else {
// do something for phones running an SDK before lollipop
mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(getSupportMapFragId());
}
mapFragment.getMapAsync(this);
}
//..
#Override
public void onMapReady(GoogleMap map) {
this.googleMap = map;
}
}
According to my breakpoints onViewCreated() is called, but onMapReady() is not called (breakpoint on this.googleMap = map not triggered)
On Android 5, 6 and 7 it works fine so far and I can see the Map..
On Android 4.X (API 16 - API 19) devices my app starts up, but then it seem to freeze there... I see a white blank screen.
On Android 4.X OS devices:
1. With getFragmentManager(), the mapFragment object is null after the else condition.
2. With getChildFragmentMenager() the mapfragment seem to be valid and non-null, but onMapReady not triggered.
What am I missing here?
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically
If you want to inflate a map in a fragment you can either do it in xml or do it in java code like this:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentByTag("mapFragment");
if (mapFragment == null) {
mapFragment = new SupportMapFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.mapFragmentContainer, mapFragment, "mapFragment");
ft.commit();
fm.executePendingTransactions();
}
mapFragment.getMapAsync(callback);
}
And also the simple container
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
Also, you don't need to implement the onMapReadyCallback in the class definition. Instead of callback you create a new OnMapReadyCallback() right there:
MapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
}
});
You also need these
MapView mMapView;
private GoogleMap googleMap;
I hope this helps somehow !
There was an issue with a blocking thread from RxJava on main thread. So it was not an Google Maps issue.
I don't quite understand why you are nesting fragments, specially because it can cause performance issues.
If you take a look at Google Samples, the Google Maps examples uses an Activity and SupportMapFragment:
public class MapsActivityCurrentPlace extends AppCompatActivity
implements OnMapReadyCallback, ConnectionCallbacks,
OnConnectionFailedListener {
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
(FrameLayout)findViewById(R.id.map), false);
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
setContentView(R.layout.activity_maps);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.d(TAG, result.getErrorMessage());
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "Play services connection suspended");
}
}

Update ListView via AsyncTask or IntentService

I am trying to Update my Custom ListView which is fed by two String Arrays:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getStringArray(ARG_PARAM1);
mParam2 = getArguments().getStringArray(ARG_PARAM2);
}
setupListView();
}
private void setupListView() {
listItemList = new ArrayList();
if (mParam1 != null && mParam2 != null && mParam1.length == mParam2.length) {
for (int i = 0; i < mParam1.length; i++) {
listItemList.add(new MyListItem(mParam1[i], (mParam2[i]).substring(0, 75) + "..."));
}
} else {
listItemList.add(new MyListItem("Loading...", "Swipe Down for Update"));
}
mAdapter = new MyListAdapter(getActivity(), listItemList);
}
mParam1 and mParam2 are Values which are fetched by an XML parser (IntentService) class in the MainActivity which i can show if needed.
Now, if i am to fast, and the mPara1 and mPara2 is empty there won´t be any ListView shown. Now i want to solve this by some AsyncTask or IntentService whatever is useful. I tried AsyncTask, which didn´t work at all. I tried notifyDataSetChanged() which didn´t work too...
Now, how could i solve this....
Using AsyncTask i have the problem that i don´t know how to passt the two Arrays to publishProgress() correctly
THis is how my AsyncTask looks like:
class UpdateListView extends AsyncTask<Void, String, Void> {
private MyListAdapter adapter;
private ArrayList listItemList;
#Override
protected void onPreExecute() {
adapter = (MyListAdapter) mListView.getAdapter();
}
#Override
protected Void doInBackground(Void... params) {
for (String item1 : mParam1) {
publishProgress(item1);
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
adapter.add(new MyListItem(values[0], values[1]));
}
#Override
protected void onPostExecute(Void result) {
Log.d("onPostExecute", "Added successfully");
}
}
Okay solved it...My Fragments are running in same Activity where the Data is loaded in, so i just created getter and setter in MainActivity and access them in the needed Fragment via
String[] titles =(MainActivity) getActivity()).getTitlesArray();
String[] text=(MainActivity) getActivity()).getTextArray();
Whatever i do trying setting Bundle with
bundle.putStringArray(TITLES,titles);
doesn´t work. Should work using parceable/serializable class but didn´t try...

Multiple MediaPlayer background instead of 1

I'm trying to run an App that has only one background song that runs on all activities. But some how when I open another activity, (all the activities are extends of the main activity), the application opens another session of the song. I tried to fix it but with no success.
I don't understand why the "Music:IsPlaying" is always false despite that the song is playing, this is my code:
public class MainActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Music = MediaPlayer.create(MainActivity.this, R.raw.ad_matai);
if (!Music.isPlaying())
{
Music.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void OpenMyProfile(View view)
{
Intent open_my_profile = new Intent(this,MyProfile.class);
startActivity(open_my_profile);
}
public void OpenPeople(View view)
{
Intent open_people = new Intent(this,PazamPeople.class);
startActivity(open_pazam_people);
}
Why don't You use service for that? If You have task which should be active for longer than single activity lifecycle it should be service for that. Hit Google with 'music service android'

how to delete item from listview and refresh that

I need some help in my homework here...
I want to do a listview with itens from editText.. but I dont know how to delete and edit the item, I tryed to use ContextMenu. I will post my code, and if you think that i have to change anything, tell me.. I'm begginer.
private Button bt;
private ListView lv;
private EditText et;
private ArrayList<String> Arraylt = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_l);
bt = (Button)findViewById(R.id.bt);
lv = (ListView)findViewById(R.id.lv);
et = (EditText)findViewById(R.id.et);
lv.setOnCreateContextMenuListener(this);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view,
int posicao, long id) {
Object o = lv.getItemAtPosition(posicao);
et.setText(String.valueOf(o));
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addadicionar();
}
});
}
public void addadicionar() {
Arraylt.add(et.getText().toString());
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Arraylt));
et.setText("");
}
hey this is my note pad code it will help you .. have a look
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.listView1)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.edit:
// edit stuff here
return true;
case R.id.delete:
ArrayAdapter <String> adapter=new ArrayAdapter<String>(menu.this,android.R.layout.simple_list_item_1,data);
Cursor cursor2=mydb1.rawQuery("SELECT * FROM notes;", null);
data.remove(info);
lv.setAdapter(adapter);
cursor2.moveToPosition(info.position);
int id= cursor2.getInt(cursor2.getColumnIndex("id"));
mydb1.delete("notes", "id=?", new String[] {Integer.toString(id)});
list(view); // this will refresh my list by calling my display list method here
return true;
default:
return super.onContextItemSelected(item);
}
try to remove the item from listItems(List), then call adapter.notifyDataSetChanged();
try this code :
// note : you need to create xml file in res/menu folder which conatain deleter and editer item
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.listView1)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.Deletar:
// edit stuff here
return true;
case R.id.editar:
ArrayAdapter <String> adapter=new ArrayAdapter<String>(menu.this,android.R.layout.simple_list_item_1,data);
data.remove(info);
lv.setAdapter(adapter);
list(view); // this will refresh my list by calling my display //list method here
return true;
default:
return super.onContextItemSelected(item);
}
Yes, I win!.. now, I can edit and delete the item from listview...
private Button bt;
private ListView lv;
private EditText et;
private ArrayList<String> Arraylt = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_l);
bt = (Button)findViewById(R.id.bt);
lv = (ListView)findViewById(R.id.lv);
et = (EditText)findViewById(R.id.et);
lv.setOnCreateContextMenuListener(this);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int posicao, long id) {
Object o = lv.getItemAtPosition(posicao);
et.setText(String.valueOf(o));
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addadicionar();
}
});
}
public void addadicionar() {
Arraylt.add(et.getText().toString());
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Arraylt));
et.setText("");
}
sorry for the bad indent..

Eclipse DisplayMessageActivity error

I have a question about an error I get in Eclipse.
Eclipse says "The nested type DisplayMessageActivity cannot hide an enclosing type"
This is my script:
package com.example.warzonegaming;
public class DisplayMessageActivity {
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Does someone knows an fix for this, because I can't go further now.
Regards
Try learn basics of javapackage com.example.warzonegaming;
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}