NullPointerException when trying to load a button - android

I am trying to open a new activity. When I do I get a null pointer exception. Everything works untill the following code gets executed.
Button RmTests =(Button)findViewById(R.id.btnRmTests);
RmTests.setOnClickListener(AnsRmTest);
Here is a better look at the code.
public class DisplayTests extends ListActivity {
private DbManagement mdbManager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//mdbManager = new DbManagement(this);
//mdbManager.open();
Button RmTests =(Button)findViewById(R.id.btnRmTests);
RmTests.setOnClickListener(AnsRmTest);
//fillData();
}
private OnClickListener AnsRmTest = new OnClickListener(){
#Override
public void onClick(View v) {
try{
System.out.println("fart");
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
};
I am not sure why the activity would bomb out when it reaches the creation of a button.
Here is the XML as well
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/frameLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="194dp" >
</ListView>
</FrameLayout>
<Button
android:id="#+id/btnNewExam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="#string/strNewExam" />
<Button
android:id="#+id/btnRmExams"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnRmTests"
android:layout_alignBottom="#+id/btnRmTests"
android:layout_alignParentRight="true"
android:text="#string/strRmExams" />
<Button
android:id="#+id/btnRmTests"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnNewExam"
android:layout_alignBottom="#+id/btnNewExam"
android:layout_toLeftOf="#+id/btnRmExams"
android:text="#string/strRmTest" />
</RelativeLayout>
So with that being said I am the following code
setContentView(R.layout.moretime);
When I did that I get the following error:
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
I do have a list view as you can see about but it is called listView1 and I am not sure why I am getting this error message. Thanks in advance.

You need to set the content of your layout to the activity first then initialize views.
privae Button RmTests;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout); // missing
RmTests =(Button)findViewById(R.id.btnRmTests);
RmTests.setOnClickListener(AnsRmTest);
... // rest of the code
}
You can findViewById of the current view hierarchy set to the activity. Since you have not set the content to the activity, when you initialize your button you get NullPointerException.
ALso
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "#android:id/list" (or list if it's in code)
In your xml replace
<ListView
android:id="#+id/listView1"
By
<ListView android:id="#android:id/list"
Also do you require a FrameLayout? Why not have just the listview and the buttons in the relative layout.
http://developer.android.com/reference/android/app/ListActivity.html
Edit:
From the comment below
You can do as below
public class MainActivity extends ListActivity {
String s[] = {"A","B","C","D","E"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, s);
setListAdapter(adapter);
}
}
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate().
If you need to have other views then you can define them in xml extend ListActivity in which case you need to have listview with id "#android:id/list". Like i can have a list and a button at the button. So i need to have a listview with id as "#android:id/list".

Where do you tell your activity which xml it is supposed to load?
Try:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//mdbManager = new DbManagement(this);
//mdbManager.open();
Button RmTests =(Button)findViewById(R.id.btnRmTests);
RmTests.setOnClickListener(AnsRmTest);
//fillData();
}
replace "R.layout.main" with your xml file title. E.g. if it's Main_Layout.xml, replace it with "R.layout.Main_Layout"

Write
setContentView(R.layout.your_layout);
after
super.onCreate(savedInstanceState);

try be adding setContentView(R.layout.your_layout_name); after super.onCreate(savedInstanceState);

You have to set the setContentView .Here is the Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
Button RmTests =(Button)findViewById(R.id.btnRmTests);
RmTests.setOnClickListener(AnsRmTest);
}

I think in you Activity inside onCreate methode you forget to give setContentView
Before initializing the UI components you must set view for activity inside onCreate methode
ie setContentView(R.layout.yourxml)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxml);
//mdbManager = new DbManagement(this);
//mdbManager.open();
Button RmTests =(Button)findViewById(R.id.btnRmTests);
RmTests.setOnClickListener(AnsRmTest);
//fillData();
}
Additional Info
also since your are using ListActivty you must provide listview id as
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="194dp" />
Otherwise it will cause another error

Related

Alert Dialog embedded buttton is not clicking in Android Java

Am trying to click on a button i just added to an AlertDialog but its not responding. The button is on a layout file in the resources folder and then i added this layout to the AlertDialog via the Builder method setView()
I accessed the same Button via my mainactivity after inflating a random view with the layout and set an OnClickListener but its still not working
Here is detail code of what i have tried so far
Layout containing the button
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#FFF"
android:background="#drawable/round2"
android:textSize="20sp"
android:textAlignment="center"
android:padding="5dp"
android:text="Submit"
android:textAllCaps="false"
android:drawablePadding="10sp"
android:id="#+id/submit"
/>
</Linearlayout>
Then in my MainActivity.class, i access the button this way
class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//inflate layout containing button
datView=getLayoutInflater().inflate(R.layout.data_entry,null);
//access button
submit=datView.findViewById(R.id.submit);
//set event listener
submit.setOnClickListener(this);
}
//the interface
#Override
public void onClick(View v) {
check();
}
//custom method check
private void check(){
Toast.makeText(this,"Registering data into database",Toast.LENGTH_LONG).show();
}
}
Despite all that the toast does not show on clicking the button, please help
Please try using android:onClick = "check" in the button in your xml, and also create a method in your MainActivity called public void check(View view){...} with the toast inside of it

android.widget.LinearLayout cannot be cast to android.widget.TextView (android-studio)

Im Trying To paste data(from an Intent) on a customized ListView ,and then I get this error,but when I did it with an uncustomized ListView it worked properly.
I understood that the problem occurs when I change :
ListAdapter theAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,timegone);
to:
ListAdapter theAdapter=new ArrayAdapter<String>(this,R.layout.row_layout,timegone);
But I dont get why it doesnt work!
Here below I added the row_layout.xml file which Causes the app crash.
Thats how it works :
public class Shifts extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shifts);
Intent MyIntent=getIntent();
String timepass=MyIntent.getExtras().getString("time");
ListView thelist=(ListView)findViewById(R.id.MyListView);
String[] timegone=timepass.split(":");
ListAdapter theAdapter=new ArrayAdapter<String>(this,**android.R.layout.simple_list_item_1**,timegone);
thelist.setAdapter(theAdapter);
}
}
And thats how it doesnt work:
public class Shifts extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shifts);
Intent MyIntent=getIntent();
String timepass=MyIntent.getExtras().getString("time");
ListView thelist=(ListView)findViewById(R.id.MyListView);
String[] timegone=timepass.split(":");
ListAdapter theAdapter=new ArrayAdapter<String>(this,**R.layout.row_layout**,timegone);
thelist.setAdapter(theAdapter);
}
}
This is the row_layout.xml that im using in the adapter
<LinearLayout 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:orientation="vertical"
tools:context=".MainScreen"
android:id="#+id/ly"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv1"
android:textSize="30sp"
android:textStyle="bold"
android:padding="15dp"/>
</LinearLayout>
What should I do in order to fix this ?
Thank you!
You need to create custom adapter if you want custom layout of list row..
here you can see the example.

Android Views within Layouts

Ok so I'm running into problems creating an app (force closing) and I think it has to do with the way I implemented the layout. So a few questions: First, I have a relative layout that includes a text input with a button next to it, a list view (still within the relative layout) and another button below that. This is my main 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:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText
android:id="#+id/edit_choice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Button1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/Button1"
android:hint="#string/edit_choice" />
<Button
android:id="#+id/Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="addString"
android:text="#string/button_add" />
<Button
android:id="#+id/Button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:text="#string/button_random" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/Button2"
android:layout_alignParentLeft="true"
android:layout_below="#+id/Button1"
tools:listitem="#android:layout/simple_list_item_1" >
</ListView>
</RelativeLayout>
Before I even changed anything in the .java files when I tried running this, only the text input and the 2 buttons appeared and the theme changed from Holo to Holo light. So I'm wondering if this works, I've only seen examples where the list view matches the parent layout completely.
My second question is how do I handle using the input to add values to the list view, can I do that in the main activity class or can I have another class to handle the list view and still reference the main layout.
This is my Main class:
public class MainActivity extends Activity
{
public ArrayList <String> choices = new ArrayList <String>();
public ListView listView = (ListView) findViewById(R.id.listView1);
public String [] choicesArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView1);
choicesArray = new String [] {"You have not entered a choice yet"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, choicesArray);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//adds the string to the list
public void addString(View view)
{
choicesArray = (String[]) choices.toArray();
EditText editText = (EditText) findViewById(R.id.edit_choice);
String message = editText.getText().toString();
choices.add(message);
}
}
Hopefully this makes sense and thank you for any help.
Problem is you are calling this line
public ListView listView = (ListView) findViewById(R.id.listView1);
before setting content view by setContentView() method in onCreate() so you are getting NullPointerException. Do not forget that before calling findViewById you have to set content view. So delete above line because you are creating function scope listView in onCreate method and your NullPointerException problem will be solved. And also change first line of addString method like this
choicesArray = choices.toArray(choicesArray);
Define your ArrayAdapter as member for your class (not as variable
in onCreate()).
Set the adapter to your listView in onCreate().
Set the onClickListener for your button.
Add the text from EditText to your adapter when you click on the
button.
Profit!

Set custom title bar in PreferenceAcivity

I am using PreferenceActivity, how can I set a custom title bar? Not only text but background color, size - the whole layout.
PreferenceActivity extends ListActivity, and when you inflate the preferences from xml with addPreferencesFromResource(), it puts the stuff into the standard ListView that ListActivity uses.
So basically, you can use setContentView() to specify a layout, but you need to have a ListView in it with the id "#+android:id/list".
So using kleini's example code:
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.login_settings);
setContentView(R.layout.login_settings_layout);
}
You would need a ListView in login_settings_layout.xml that looks something like:
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
This is the only thing that worked for me. Rest of the above stuff did not fetch desired results on my 4.3 Nexus Tablet.
I could not really recreate a proper actionbar like widget, but was able to put a large 'Settings' title on top of the PreferenceActivity, with below steps.
I got the hint from another stackoverflow answer and am just making it more elaborate.
In PreferenceActivity class (remove the existing titlebar)
public class Settings extends PreferenceActivity· {
...
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); // This goes first
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
In res/xml/settings.xml, I would like to draw attention to the first PreferenceCategory
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:layout="#layout/settings_titlebar" />
<PreferenceCategory android:title="Notifications">
<Preference .....
In res/layout/settings_titlebar.xml
Navals-MacBook-Pro:ver_ui_0.2 Naval$ vi res/layout/settings_titlebar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/header_background"
android:enabled="false">
<TextView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="#android:color/transparent"
android:padding="4dip"
android:text="Settings"
android:textSize="32sp"
/>
</RelativeLayout>
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
}
}
Ben's method worked out well for me!!. Here is the code
public class PreferenceCustomTitleActivity extends PreferenceActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
/** Customize your background, textsize, cachetint, dividers
for your list view in the xml **/
setContentView(R.layout.layout_with_simple_listview_only);
ListView list = (ListView) findViewById(android.R.id.list);
View preferenceHeader = getLayoutInflater().inflate(
R.layout.preference_header, null);
list.addHeaderView(preferenceHeader);
}
}
Awesome, worked fine for "NO_TITLE":
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.login_settings);
setContentView(R.layout.login_settings_layout);
}
Or like this:
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitlebar);
addPreferencesFromResource(R.xml.preferences);
}
With a customtitlebar.xml like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/customTitleBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/CustomWindowTitle">
</TextView>

first click on linearlayout doesn flash background click color, it just flash for second and next click

I try to get the effect click background color for linear layout. I've set clickable to linear layout. and from the code also I've put the click listener the setBackgroundResource.
Here it is the xml:
<?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"
>
<LinearLayout
android:id="#+id/llinsertmem"
android:clickable="true"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50px">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="PUSH it"
/>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
and the java code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
linearInsertMem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(android.R.drawable.list_selector_background);
Toast.makeText(testdoank.this, "succeded", Toast.LENGTH_SHORT)
.show();
}
});
}
When first time click the clickable linearlayout, the toast text is displayed but the background color click effect doesn't. The flash background click color is only work from the second click.
any idea what the problem is?
Is not necessary do anything in JAVA code.
You can only add this as attribute:
android:background="#android:drawable/list_selector_background"
And it works for me (on Android 2.2 device)
After try and error, somehow it's work.
just put the setBackgroundResource also on the onCreate.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
linearInsertMem.setBackgroundResource(android.R.drawable.list_selector_background);
linearInsertMem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(android.R.drawable.list_selector_background);
Toast.makeText(testdoank.this, "succeded", Toast.LENGTH_SHORT)
.show();
}
});
}
Don't know the logic explanation. if you have a thought, please.
In the onClick method you are using v as the View which is passed, but that view may not be the LinearLayout which you want to change the background.
Thus you need to create a class level variable or a final varibale and pass the handle for the LineraLayout to the onClick method.
Remove/cut from onCreate:
linearInsertMem.setBackgroundResource(android.R.drawable.list_selector_background);
and paste it into onClick or change v. into linearInsertMem.
I think that Exlipse will then demand that linearInsertMem must be final like:
final LinearLayout linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
Or you can define this object above onCreate like this:
LinearLayout linearInsertMem;
then in onCreate you state:
linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
then onClick method will know exactly which view you want to change if you use linearInsertMem.setBackgroundResource...

Categories

Resources