[Solved] findViewById Returns Null? - G1 Android Development

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 !

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!

Problem Reading Data from Sensors

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.

[Q] Need help to populate a listview from external source

I'm pretty new to java and somewhat new to android and I've been looking everywhere for the past 3 or 4 days but cant seem to find the answer to my question. I'm making an app that is pretty simple and has only one real main function and that is to pull movie names, release dates, and the movie's format (dvd, blu-ray etc) into the app automatically from a very simple file that I will host on my server.
Now I I'm currently able to input the needed information manually via a base-adapter and a strings file within each months activity but I want to have the ability to push the information remotely which will then give my app (and myself) the ability to update the information as well as to place it into the 3 line listview format that I've already established.
Now I've been reading about Simple:XML, gson, SAX, etc but seeing as the information is just 3 small lines of text (again just the movie name, date and format which doesn't use much space and will be using the same string format for all 12 months) my question is what would be the best route as to the format of the file (i.e. xml, json, plain text, etc) and how would I go about getting this information into my app on the fly? I've included some code snippets below in the hopes they will make my question a little more clear.
I've posted this on several other forums and android dev sites and nobody seems to be able to give me some guidance or simply will not reply at all. I cannot continue on my app until I'm able to figure this out and seeing as it is completed aside from this problem it is becoming a very frustrating experience. I'm hopeful that someone here will be able to give my some help out. Thank you in advance.
The string for each result
Code:
public class SearchResults {
private String Name = "";
private String Date = "";
private String Format = "";
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getDate() {
return Date;
}
public void setDate(String Date) {
this.Date = Date;
}
public String getFormat() {
return Format;
}
public void setFormat(String Format) {
this.Format = Format;
}
This below is where the actual list-view is populated and shown. Each new search result creates a three line text-view.
Code:
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
sr1.setName("Movie #1");
sr1.setDate("July 24th");
sr1.setFormat("DVD, Blu-Ray");
results.add(sr1);
sr1 = new SearchResults();
sr1.setName("Movie #2");
sr1.seDate("July 19th");
sr1.setFormat("DVD, Blu-Ray, Digital");
results.add(sr1);
return results;
}
Can anybody help me with this please?

[Resolved] [Q][DEV]Android Development Question about Shared Preferences.

Hi, I'm trying to do a simple login with Facebook in my app but I'm having trouble with Shared Preferences.
The idea is to start the app, it opens Activity A, checks if it's logged, and if it isn't, it sends you to activity B, you login and then go back to A.
My problem is that I can't get the SharedPreferences. I can save it, but I can't get it in the other activity.
So, it gets in a loop: A can't get the SP, so thinks it's not logged in, so send you to B, but B is logged on, and sends you to A...
That's my code in B:
Code:
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Editor edit = fbSP.edit();
edit.putString("access_token", fb.getAccessToken());
edit.putLong("access_expires", fb.getAccessExpires());
edit.commit();
aIMG();
ir();
}
And that's my code in A, where the problem is:
Code:
private SharedPreferences prefs;
public static String TOKEN = null;
public static final String FACEBOOK_DATA = "FacebookStuff";
long EXPIRES = 0;
...
private void SharedP() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(FACEBOOK_DATA, MODE_PRIVATE);
TOKEN = prefs.getString("access_token", null);
EXPIRES = prefs.getLong("access_expires", 0);
if (TOKEN == null && EXPIRES == 0) { //If it's not logged in...
Intent login = new Intent("android.intent.action.FACELOGIN");
startActivity(login);
}
}
Edit: I got it. I was iniciating fbSP with getPreferences, not getSharedPreferences.

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"
/>

Categories

Resources