Kaushal28 Kaushal28 - 4 months ago 173
Java Question

Error: setContentView(R.layout.main) in Android Studio

I'm developing a simple app for learning purpose, In which there is a single check box and a text line, which shows it is checked or unchecked. But it shows an error in line

setContentView(R.layout.main)
and
cb=(CheckBox)findViewById(R.id.check)
this is my java code:

package com.example.kaushal.checkbox;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.R;

public class Checkbox extends Activity
implements CompoundButton.OnCheckedChangeListener {
CheckBox cb;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(R.layout.main);
cb=(CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
cb.setText("This checkbox is: checked");
}
else {
cb.setText("This checkbox is: unchecked");
}
}
}


It is not a duplicate question,I've seen the answers of the same questions but it was all for eclipse.I'm working with android studio.

This is my xml layout code:

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Checkbox">


<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This checkbox is: unchecked" />

</RelativeLayout>


I'm new to android so please guide me.

Answer

I found the answer by my self. I thing the error is not because of wrong import as answered here. It was because of the use of wrong name and id of layout file and check box respectively. My .xml layout file name was activity_my_checkbox.xml. So I should use:

setContentView(R.layout.activity_my_checkbox);

And my check box id was c instead of check, so I should use

cb=(CheckBox)findViewById(R.id.c);
Comments