Problem Reading Data from Sensors - G1 Android Development

Ok, so I'm trying to write a simple app to display the data from all of the sensors on a device. My problem is that whenever I try to instantiate my SensorManager object, my app's screen goes black, followed shortly by the Force Close / Wait dialogue.
My code:
Code:
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//initialize graphics
setContentView(R.layout.main);
xaccelDisplay = (TextView) findViewById(R.id.xaccelDisplay);
yaccelDisplay = (TextView) findViewById(R.id.yaccelDisplay);
zaccelDisplay = (TextView) findViewById(R.id.zaccelDisplay);
//set up sensor manager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
/*sensorManager.registerListener(this,
sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0),
SensorManager.SENSOR_DELAY_GAME);*/
}
Anyone have suggestions? I've looked for demo programs for how to access the sensors, but they all seem to use the sensor functions labeled as deprecated by the official Android website... maybe I'm missing something obvious.

Related

MapActivity, Buttons and OnClickListener

Hi all,
could you give me some help please? I have written a simple MapActivity that contains a mapview (defined in the xml file); it also contains a Button.
If the Button has no OnClickListener associated then the project runs fine (the mapview is of course empty).
If I add an OnclickListener the application simply Force closes.
Has anyone tried this? I was actually following the example in a book but I guess something has changed in the SDK since it was written?
I m using SDK 1.1 (for the moment).
If you have (recently) written something similar, could you give me some pointers please?
thanks
N
"could you give me some pointers please?"
Might be a nullpointer indeed. Check your LogCat (Eclipse: Window, show view, other, logcat), this will probably give you some nice hints.
LOL
ehhehe
havent checked the log yet, will do and then report back here.
if anyone else has other suggestions please dont hesitate!
thanks
N
LogCat
Vlemmix said:
"could you give me some pointers please?"
Might be a nullpointer indeed. Check your LogCat (Eclipse: Window, show view, other, logcat), this will probably give you some nice hints.
Click to expand...
Click to collapse
Vlemmix,
I checked the LogCat and seems too be a nullpointer indeed, but I cannot identify the mistake in the code.
This is the java source for the class. could you please have a look ?
If I un-comment the commented lines, I get a force close. Leave them uncommented and everything works (no click event on the button tho).
package com.chipset.testgps;
import com.google.android.maps.MapView;
import android.widget.Button;
import com.google.android.maps.MapActivity;
import android.os.Bundle;
public class main extends MapActivity {
@Override
public boolean isRouteDisplayed(){
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button but = (Button) findViewById(R.id.gpsButton);
// but.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v){
//
// }
// });
final MapView map = (MapView) findViewById(R.id.myMap);
setContentView(R.layout.main);
}
}
Any help please??
thanks
N
1)
First do the setContentView, after that the Button is findable. The system could not find your Button now, so that's why it is a null. Your MapView map also would be a null in your code.
2)
If you define an object within {} it is only available within that {}
You probably going to need the Object "but" later, so make it a private variable of the class.
3)
Classname should start with a capital.
4) Visit anddev.org or some site like that for coding problems, xda seems to be more focused on system/firmware issues, not application code.
So, this should work:
public class MainActivity extends MapActivity {
final Button but;
final MapView map;
@Override
public boolean isRouteDisplayed() {
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but = (Button) findViewById(R.id.gpsButton);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
}
});
map = (MapView) findViewById(R.id.myMap);
}
}
Right
Hi Vlemmix.
Thanks very much for your help. I can understand what you are telling me, but if its so:
1) with the listener's lines commented, my code does show both the button and the mapview.. shouldnt it force close anyways if the problem is the setcontentView?
2) yeah agree with you on this one, though since I couldnt get even this simplest code to work, I didnt really want to overcomplicate it for now.
3) this is not a requirement is it? I mean its a coding convention, a good one yes, but not mandatory..?
4) Will do thanks, I m trying to get my bearings with all the dev websites etc.
PS about the API Key.. is this strictly required for developing on localhost (testing on the emu)? I find the info a bit confusing to be honest..
I will give your mods a shot this evening and will post here later tonight.
For the moment a big thank you for showing me my (silly) mistakes (I kinda miss .NET at times.. I wouldnt have messed up that bad with it..).
thanks!
N
Quick reply:
1) You can only find a view when the content is set. No content: nothin' to find!
3) Just do it! ;-)
API key, localhost? I don't understand your question... I'm on SDK1.1, did some work on the emulator, now most on the G1, no big difference. Don't know about keys. You probably need a key for generation an apk for the market though.
ApiKey
Vlemmix said:
Quick reply:
1) You can only find a view when the content is set. No content: nothin' to find!
3) Just do it! ;-)
API key, localhost? I don't understand your question... I'm on SDK1.1, did some work on the emulator, now most on the G1, no big difference. Don't know about keys. You probably need a key for generation an apk for the market though.
Click to expand...
Click to collapse
Will try and let you know mate!
The API Key you need to put in the xml for the MapView. apparently google has made this a requirement instead of the bogus key. I just dont understand if this is true also for the apps you test on the emu or only the ones that go 'live'..
Vlemmix
HI there,
just wanted to let you know that moving the setcontentview worked a treat!
Im so very embarassed now
thanks again for your help mate, I owe you one.
N
You're welcome, no problem!

[Solved] findViewById Returns Null?

Hi all,
I'm in the process of adding more features to Contacts.apk (http://forum.xda-developers.com/showthread.php?t=599194), and have run into a "bug" with my latest attempt in adding the green call icon to the Contacts list (similar to Call Log), so that you can dial directly without first tapping on a Contact.
I've posted the problem here: http://www.anddev.org/viewtopic.php?p=31252 and would really appreciate if you all could give me some pointers.
Thank you .
Also, the main issue is:
view.findViewById(R.id.call_icon);
is returning null for some reason.
Note: My github does not contain the source with this problem, please go to the anddev thread and download it from there. Thanks!
Did you pull your pants down then try? It worked for me last time
try typecasting callView
I only looked briefly ... sooo ...
How is callView defined in ContactsListActivity.java?
github doesn't show it ....
Code:
final static class ContactListItemCache {
public TextView nameView;
public CharArrayBuffer nameBuffer = new CharArrayBuffer(128);
public TextView labelView;
public CharArrayBuffer labelBuffer = new CharArrayBuffer(128);
public TextView numberView;
public CharArrayBuffer numberBuffer = new CharArrayBuffer(128);
public ImageView presenceView;
public ImageView photoView;
}
Also, consider a matching return type before the function call ... something like I dunno ...
Code:
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = super.newView(context, cursor, parent);
final ContactListItemCache cache = new ContactListItemCache();
cache.nameView = (TextView) view.findViewById(R.id.name);
cache.labelView = (TextView) view.findViewById(R.id.label);
cache.numberView = (TextView) view.findViewById(R.id.number);
cache.presenceView = (ImageView) view.findViewById(R.id.presence);
cache.photoView = (ImageView) view.findViewById(R.id.photo);
- cache.callView = view.findViewById(R.id.call_icon);
+ cache.callView = (DontPressWithParentImageView ) view.findViewById(R.id.call_icon);
if (cache.callView == null)
Log.d("NULL: CALLVIEW", "Why?");
view.setTag(cache);
return view;
}
I could be off base here ... but since the git appears incomplete in relation to your posted problem ... etc ... best I can do in a quick drive by. Hope it helps.
~enom~
enom: If you go to the anddev thread I've attached the full (non-working, bugged) source. In it:
Code:
final static class ContactListItemCache {
public TextView nameView;
public CharArrayBuffer nameBuffer = new CharArrayBuffer(128);
public TextView labelView;
public CharArrayBuffer labelBuffer = new CharArrayBuffer(128);
public TextView numberView;
public CharArrayBuffer numberBuffer = new CharArrayBuffer(128);
public ImageView presenceView;
public ImageView photoView;
public View callView;
}
jasonpeinko: I did that already, not working. The main issue here is view.findViewById(R.id.call_icon) is returning null .
Thanks for the help guys!
So ... I must be blind ... I don't see the attached bugged source ... still could be off base here ... but ...
Since call_icon is type View, should it not be as such in the xml ...
Code:
/>
- <com.android.contacts.ui.widget.DontPressWithParentImageView android:id="@+id/call_icon"
+ <View android:id="@+i/call_icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
??
Either way, it's late I need sleep.
~enom~
enom: Nope. View is the base class so be it a Button, ImageButton, etc, they can still be assigned to View... .
did you call
Code:
setContentView(R.layout.main);
before your findViewById?
Camalot i understand thats the usual approach but in this case the content view is already set by the constructor in the code. I will give your advice a shot later, but i will be really confused if it works. Thanks!
I found the bug. It's because the layout in use was contacts_list_item_photo.xml and not contacts_list_item. *smacks head*
Thanks for the input guys !

[Q] How to code a "Really quit?" question when user press Back/Home buttons ?

[Q] How to code a "Really quit?" question when user press Back/Home buttons ?
Hello,
I am a noob ANDROID developer.
(I have a simple problem, I searched the forums and didn't found a solution.)
I am developing a strategy game/wargame on Android.
I am looking for a way to code a "really quit?" routine when the user press the back/home buttons.
(if that happens by mistake now, the whole app starts from scratch on restart)
I've seen tons of code examples, but not for this. I have only one (commercial) app that shows that exact behavior, but no access to that particular source code.
I've fiddle with the onPause(), onRestart(), onStop() , onDestroy() methods, trying to halt the process before exiting, but only got into error messages.
Basically when "back" is pressed I loose my "game screen" instantly. I've also looked into the onBackPressed() method, but then this seems to be an issue between Android 1.5/2.x. I'd like my app to run on both platforms.
Thanks for your help in this matter.
Mmm, as far as I know, you can also try to override the onKeyPressed (don't sure of the name, check the API) and check if the key pressed is back key. I think this is compatible with 1.X
http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
Android < 2.0
Code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
Android > 2.0
Code:
@Override
public void onBackPressed() {
// do something on back.
return;
}
If you don't add any code, a back button press will be ignored.
Call finish() method of your running Activity to stop your application.
Deleted post (question already answered)
Thanks!
Here the "quick and dirty" way I did it: User now have to press Back twice to get out!
===
int backPressed=0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
backPressed++;
}
if(backPressed>1){
return super.onKeyDown(keyCode,event);
}
}
return false;
}
===
(Sorry for the indentation, tabs didn't copy..)

Application for notify when your flat is power-less

Hi everyone
I was searching one app for android, but i cannot find any like that.
Basically i need to understand when my flat went down on electricity
beacuse i have food in the fridge, fish in the acquarium or whatever you may have.
I was thinking i could leave a currently unused phone on charge in the wall socket.
When electricity goes off the phone stop charging and it can notify me with email.
Do you think something like that exist?
A general event driven notifier that support email would be fine.
Is there anything like that? on the market even a paid app?
Best regards, Andrea
You could try using Tasker for it.
"To err is human, to forgive is divine"
Sent from my SGS II
Tasker do half of the job...
it detects what i need, it compose the email...
but it cannot send it!!!
It can open a web url directly, so i can program a simple php script to send an email.
But if i could do without a webserver helping me it would be better.
I think that SMS notification will be more reliable in this case. Anyway all that you need is a very simple app, probably no more than several lines of code. If you are still interested in this I can help you to write one (if you have at least basic programming knowledge) or write one for you.
qubas said:
I think that SMS notification will be more reliable in this case. Anyway all that you need is a very simple app, probably no more than several lines of code. If you are still interested in this I can help you to write one (if you have at least basic programming knowledge) or write one for you.
Click to expand...
Click to collapse
solved with tasker. i make it open weburl, on web url i made application that send email.
cause tasker compose but cannot send.
i have programming knowledge,i would like to start,i just don t like java
maybe just a problem of mine
do you have some empty app franework to look at?
asturur said:
solved with tasker. i make it open weburl, on web url i made application that send email.
cause tasker compose but cannot send.
i have programming knowledge,i would like to start,i just don t like java
maybe just a problem of mine
do you have some empty app franework to look at?
Click to expand...
Click to collapse
There are many tutorials for installing Android Development Tools (ADT) and creating simple "Hello world" app. It probably takes 1 hour to do that. For simple app you don't really have to know Java, copy-paste some code samples from the Internet should do the trick, you just need to have at least some basic programming knowledge.
I still think that sending SMS is the most reliable solution. Using Wifi is a bad idea, because it won't work when there is no AC, unless you have a UPS. With 3G its much better, but still you have to rely on the web service you use to send email.
Anyway, here is my code:
Code:
package com.example.powermonitoring;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String NUMBER = "+48123456789";
private static final int THRESHOLD = 10;
private static final String AC_ONLINE = "AC is back online!";
private static final String AC_OFFLINE = "AC is offline!";
private Handler handler = new Handler();
private int counter;
private boolean lastPowerState;
private boolean powerState;
private Runnable runnable = new Runnable() {
[user=439709]@override[/user]
public void run() {
powerState = isPlugged(MainActivity.this);
if (powerState != lastPowerState) {
counter++;
if (counter == THRESHOLD) {
counter = 0;
lastPowerState = powerState;
String message;
if (powerState) {
message = AC_ONLINE;
} else {
message = AC_OFFLINE;
}
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); //for testing
//SmsManager sms = SmsManager.getDefault();
//sms.sendTextMessage(NUMBER, null, message, null, null);
}
}
handler.postDelayed(this, 1000);
}
};
public static boolean isPlugged(Context context) {
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastPowerState = isPlugged(MainActivity.this);
handler.postDelayed(runnable, 1000);
}
}
You just have to remember about including permission in AndroidManifest.xml :
Code:
<uses-permission
android:name="android.permission.SEND_SMS"
/>

Catching unix signals in an Android Application

In my Android application, most of the code and logic is in C++. The C++ code is built as a dynamic library. My Application class loads this native library. In the native library, I want to catch different unix signals that are raised by the OS. I have tried, but unable to trap them.
In the native library, I have done the following :
C++:
void SignalHandler (int signal)
{
__android_log_print(ANDROID_LOG_INFO, TAG, "SignalHandler");
__android_log_print(ANDROID_LOG_INFO, TAG, "signal = %d", signal);
// Do something
}
// Will be called from MainActivity.onCreate()
void NativeFunction (JNIEnv* env, jobject obj) (
JNIEnv* env,
jobject /* this */) {
__android_log_print(ANDROID_LOG_INFO, TAG,"NativeFunction ");
__android_log_print(ANDROID_LOG_INFO, TAG, "Registering for signals...");
if (signal(SIGTERM, SignalHandler) == SIG_ERR)
__android_log_print(ANDROID_LOG_INFO, TAG, "Registering for SIGTERM failed!");
if (signal(SIGINT, SignalHandler) == SIG_ERR)
__android_log_print(ANDROID_LOG_INFO, TAG, "Registering for SIGINT failed!");
__android_log_print(ANDROID_LOG_INFO, TAG, "Successfully registered for signals!");
}
I swiped up from the recents screen or closed the Activity by pressing the Back button, but didn't get any termination signals (lifecycle callbacks of the Activity were called - as expected).
The question is, should I be writing signal handlers to handle these (SIGINT and SIGBREAK) signals? I have only tested these two ways (swipe up and back button press), but there are many ways for Android to terminate an app. Will I ever get SIGTERM, SIGINT or other signals (which expects the application to exit) in the Android environment? I haven't found anything (so far) in the docs.

Categories

Resources