I'm rather new to android programming, and am running into my old friend the NullPointerException...
I've been on it for quite a while now, but can't figure out what is wrong.
basicly gives me a NullPointerException when I try to call any .setText() methods, maybe someone sees what I'm doing wrong here...(though i tried to follow examples as close as possible)
public class lessonView extends Activity {
TextView adressOfLecture;
TextView lecturer;
TextView lesson;
Lecture lecture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson_view);
Bundle data = getIntent().getExtras();
lecture = (Lecture) data.getParcelable("student");
adressOfLecture = (TextView)findViewById(R.id.lectureViewAdressLabel);
lecturer = (TextView)findViewById(R.id.lectureViewLecturerLabel);
lesson = (TextView)findViewById(R.id.lectureViewTitle);
updateLabels();
}
#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_lesson_view, 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);
}
private void updateLabels(){
adressOfLecture.setText(lecture.getRoom());
lecturer.setText(lecture.getTutor());
lesson.setText(lecture.getName());
}
}
also, here's my xml file:
<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="com.coronarip7.app.stupla.lessonView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(ort)"
android:id="#+id/lectureViewAdressLabel"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/lectureViewTitle"
android:layout_marginRight="86dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dozent"
android:id="#+id/lectureViewLecturerLabel"
android:layout_toEndOf="#+id/lectureViewTitle"
android:layout_alignTop="#+id/lectureViewAdressLabel"
android:layout_alignParentEnd="true"
android:layout_marginRight="27dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lectureViewTitle"
android:gravity="center_horizontal"
android:text="test"
android:textSize="40dp"
android:textStyle="bold"
android:padding="10dp"
android:layout_row="0"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
and the logcat I'm getting:
04-25 01:23:51.058 12236-12236/com.coronarip7.app.stupla E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.coronarip7.app.stupla, PID: 12236
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coronarip7.app.stupla/com.coronarip7.app.stupla.lessonView}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.coronarip7.app.stupla.lessonView.updateLabels(lessonView.java:59)
at com.coronarip7.app.stupla.lessonView.onCreate(lessonView.java:31)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
seriously, I am out of ideas on how to fix it...
First check if you properly put the extra in the intent. Then I would use the following test in your onCreate method:
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
}
Then test if lecture is null like Rami wrote earlier.
Ok guys, thanks for the suggestions, but I'll go the global route. I'll create a static version of my array (from which i wanted to pass an object via the Intent), and just pass an int[] array with the coordiantes and call it in the new view.
But thanks for the quick answers anyways!
(I'm new to stackoverflow, is there a way to mark a question as "solved", or "not-needed-to-be-solved-anymore"?)
Do not use static objects in your code like arrays, objects, they have globally available, you should create intent and add your data into your intent like and call your activity
Intent intent = new Intent ();
intent.putExtra ("student",value);
start activity with intent
And in your
lessonViewActivity check for intent like
Intent intent = getIntent();
if (intent.hasExtra("student")){
lecture = (Lecture) intent.getParcelableExtra("student");
if (lecture !=null){
updateLabels ();
}
}
Related
Hello i'm struggling with these error for past of couple of hours to no avail. I am trying to pass data from my activity to the fragment but not succeeding in doing so. My guess it's complaining about my <fragment> in activity_second.xml file. My guess might be wrong. Has anyone encountered this error? But i don't know how to resolve this error.Would some please guide in me what i did wrong. Below is my code:
first_fragment.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragmentPic" >
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/users_FirstName"
android:textSize="#dimen/font_size"
android:layout_gravity="center_horizontal"/>
<com.facebook.login.widget.ProfilePictureView
android:id="#+id/profilePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
>
</com.facebook.login.widget.ProfilePictureView>
</LinearLayout>
FirstFragment.java:
public class FirstFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.first_fragment, container, false);
Bundle bundle = new Bundle();
bundle = this.getArguments();
String profileId = bundle.getString("profileId"); //complains here and returns null
TextView textView = (TextView)rootView.findViewById(R.id.textName);
textView.setText(bundle.getString("names"));
return rootView;
}
}
activity_second.xml:
<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"
android:background="#color/backgroundColor"
>
<include android:id="#+id/toolBar"
layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/first_fragment"
class="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
android:id="#+id/fragment1"
/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
secondActivity.java:
public class secondActivity extends AppCompatActivity {
private Intent intent;
private Toolbar toolbar;
private String firstName, profileId;
private FirstFragment firstFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
intent = getIntent();
firstName = intent.getStringExtra("firstName");
profileId = intent.getStringExtra("Id");
toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
toolbar.setLogo(R.drawable.ic_menu_image);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
firstFragment = new FirstFragment();
Bundle bundle = new Bundle();
bundle.putString("names", firstName);
bundle.putString("profileId", profileId);
firstFragment.setArguments(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.drawer, firstFragment,"newFrag").commit();
}
#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_second, 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.
switch(item.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, secondActivity.class );
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this error below:
29 01:50:11.402 13536-13536/edu.sjsu.cmpe277.termproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: edu.sjsu.cmpe277.termproject, PID: 13536
java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.sjsu.cmpe277.termproject/edu.sjsu.cmpe277.termproject.secondActivity}: android.view.InflateException: Binary XML file line #82: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.view.InflateException: Binary XML file line #82: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at edu.sjsu.cmpe277.termproject.secondActivity.onCreate(secondActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at edu.sjsu.cmpe277.termproject.Fragments.FirstFragment.onCreateView(FirstFragment.java:44)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1185)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1287)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2243)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:278)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:78)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at edu.sjsu.cmpe277.termproject.secondActivity.onCreate(secondActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
Get rid of
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/first_fragment"
class="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
android:id="#+id/fragment1"
/>
and use only the explicitly transaction you are using in your Activity. You can't pass a Bundle, declaring a Fragment in the layout, and try to accessing it, is making your app crash
In your activity_second.xml file, change:
class="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
to
android:name="edu.sjsu.cmpe277.termproject.Fragments.FirstFragment"
That's the correct prefix to use.
This question already has answers here:
I would like to set my variables at the top of my class instead of in the method
(4 answers)
Closed 7 years ago.
I'm new to Android Studio (and am hating the transition experience from Eclipse). I'm trying to write an app that currently has two activities. I already wrote the Java code for the main logic and it works fine, but haven't put it in the second activity yet. As I'm trying to write and run the app, it gives me an error.
There's a LoginActivity and MainActivity. Currently LoginActivity just has a dummy text and a button that takes the user to MainActivity. Currently MainActivity has just a TextView in it. When I click it, the app crashes and gives the following error. I can see it has something to do with initiating MainActivity but I can't seem to fix it.
09-10 20:16:43.012 21126-21126/com.projects.example.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.projects.example.myapp, PID: 21126
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.projects.example.myapp/com.projects.example.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2072)
at com.projects.example.myapp.MainActivity.<init>(MainActivity.java:22)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
My xml code:
<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: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=".LoginActivity"
android:orientation="vertical" >
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/loginbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="goToMainActivity" />
</LinearLayout>
LoginActivity relevant code:
public void goToMainActivity(View view)
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
MainActivity code as requested (line 22 is indicated by the prefix **):
public class MainActivity extends AppCompatActivity {
String currentWinnerName = "";
**TextView currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);**
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentWinnerLabel.setText("Finding...");
//try
//{
//checkCurrentWinner(); //will implement this
//}
//catch (Exception e)
//{
//print e.getMessage() to log
//}
}
#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);
}
The reason is, that you are trying to assign value to currentWinnerLabel before activity is created.
Unless activity is created, the context is null, and you are calling findViewById method on a null object reference.
Just change your code:
TextView currentWinnerLabel;
and after:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);
...
So, I have this ListView, which I would like that each one of its items had a background (the same background for all of them). So far I've been trying to use this code:
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<CharSequence> lv = ArrayAdapter.createFromResource(this,
R.array.countries_array, android.R.layout.simple_list_item_1);
listView.setAdapter(lv);
for (Integer i = 0; i < listView.getCount(); ++i) {
View listItem = listView.getChildAt(i);
listItem.setBackgroundResource(R.drawable.edittext_custom);
}
It's simple, I increment i and then use it to know the position in which it is and it will set that items background, and it repeats until all items have the same background. Sound easy. Is there a better way to do this? If not, can someone please help figure it out why this simple code doesn't work? I'm pretty sure I'm missing something basic.
Exception:
05-18 15:08:45.659 10157-10157/com.example.fabiocompany.goquiz W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41917da0)
05-18 15:08:45.679 10157-10157/com.example.fabiocompany.goquiz E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.fabiocompany.goquiz, PID: 10157
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fabiocompany.goquiz/com.example.fabiocompany.goquiz.TopicosActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.access$900(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.fabiocompany.goquiz.TopicosActivity.onCreate(TopicosActivity.java:47)
at android.app.Activity.performCreate(Activity.java:5451)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.access$900(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
XML:
<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"
android:background="#drawable/bggoquiz"
tools:context="com.example.fabiocompany.goquiz.TopicosActivity"
android:focusable="true"
android:focusableInTouchMode="true">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/searchView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="10dp"
android:divider="#android:color/transparent"
android:dividerHeight="20.0sp"
/>
<SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchView"
android:background="#drawable/edittext_custom"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
If you need something else, please do tell, I'll try to help.
Instead of doing all this you could create a new xml file named listitem.xml with textview as below
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tv_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background = "<give your desired background>"
/>
Modify your ArrayAdapter to
ArrayAdapter<String> lv = new ArrayAdapter<String>(this,
R.layout.listitem, R.id.tv_item, <your array>);
As you are applying same background to all items simply setting it ones in xml will do the work. You do not require to loop through list.
Problem is with your this method,.listView.getChildAt(i); this works only on the items which are currently visible
So this is how you need to use them.
final int numVisibleChildren = listView.getChildCount();
final int firstVisiblePosition = listView.getFirstVisiblePosition();
for (int i = firstVisiblePosition; i < firstVisiblePosition + numVisibleChildren; i++) {
View view = listView.getChildAt(i - firstVisiblePosition);
listItem.setBackgroundResource(R.drawable.edittext_custom);
}
Assuming that listView.getChildAt is returning null because the corresponding position has an invisible (or non-existent) object, then simply test for null ...
for (Integer i = 0; i < listView.getCount(); ++i) {
View listItem = listView.getChildAt(i);
if (listItem != null) {
listItem.setBackgroundResource(R.drawable.edittext_custom);
}
}
I am building an app named Ping in Android Studio. So far my activities are LoginActivity ProfileActivity and Timeline. My issue is that a button in the layout corresponding to the Timeline activity has an onClick method that isn't working. When the button is clicked, the emulator gives the "Unfortunatley, Ping has stopped." I'm defining the buttons and onClick methods the same way I have for other buttons whose functions are working, just this one does not seem to work. I'm receiving an error saying the method can't be found, but I've written the method in the corresponding activity. Here is the logcat:
04-30 10:40:08.727 2075-2075/com.ping_social.www.ping E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ping_social.www.ping, PID: 2075
java.lang.IllegalStateException: Could not find a method onProfilePress(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'profileButton'
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NoSuchMethodException: onProfilePress [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:4000)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Here is my Timeline activity class:
package com.ping_social.www.ping;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class TimeLine extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_line);
/*print log that shows we've got here*/
Log.i("LoginActivity", "Layout has been set");
}
#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_time_line, 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);
}
/*called when user presses the Log in button*/
public void onProfilePress(View view){
/*Log the button press*/
Log.i("TimeLine", "Has reached the onProfilePress method");
Intent intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
}
}
And here is my Timeline layout xml 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"
android:theme="#style/GeneralTheme"
tools:context="com.ping_social.www.ping.TimeLine">
<TextView android:text="#string/no_pings" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textIsSelectable="false"
android:textColor="#color/PING_TOP_BAR_RED"
android:id="#+id/textView4" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/timeline_button"
android:id="#+id/timelineButton"
android:textColor="#color/PING_TOP_BAR_RED"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_ping_button"
android:id="#+id/newPingButton"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/activity_button"
android:id="#+id/activityButton"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/profile_button"
android:id="#+id/profileButton"
android:layout_weight="1"
android:onClick="onProfilePress"/>
</LinearLayout>
</RelativeLayout>
I'm pretty positive there are not spelling issues, and there are also no other buttons that share the same ID or methods that share the same name. Been stuck on this for a few days, any help is very much appreciated!
Ok, so I made my own test. I've put together a basic relative layout with a single button, put android:theme="#style/AppTheme" in it, and a button - app crashed with the same error. Then I removed android:theme attribute - onclick event fired as it should.
All the same happened when I used AppCompatActivity instead of now-deprecated ActionBarActivity.
It's hard for me to say why it doesn't work with android:theme. It's one of Lollipop's features, but I tried to launch in on API 5.0 emulator. The article states that currently this attribute is only supported for android.support.v7.widget.Toolbar.
Here is my MainActivity :
public class MainActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getCheckBox();
/*
cb = (CheckBox) super.findViewById(R.id.checkbox);
cb.setOnCheckedChangeListener(this);
*/
}
public void getCheckBox(){
cb = (CheckBox) super.findViewById(R.id.checkbox);
cb.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.getId()==R.id.checkBox){
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(buttonView.getText().toString());
}
}
}
And here my layout :
<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=".MainActivity">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My One"
android:id="#+id/checkBox"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="160dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Two"
android:id="#+id/checkBox2"
android:layout_alignTop="#+id/checkBox"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_below="#+id/radioGroup"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="50dp" />
</RelativeLayout>
I get the following exceptions when i run
02-20 15:55:28.130 2110-2110/sqllistviewdemo.wptrafficanalyzer.in.radiobutton E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: sqllistviewdemo.wptrafficanalyzer.in.radiobutton, PID: 2110
java.lang.RuntimeException: Unable to start activity ComponentInfo{sqllistviewdemo.wptrafficanalyzer.in.radiobutton/sqllistviewdemo.wptrafficanalyzer.in.radiobutton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
at sqllistviewdemo.wptrafficanalyzer.in.radiobutton.MainActivity.getCheckBox(MainActivity.java:34)
at sqllistviewdemo.wptrafficanalyzer.in.radiobutton.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Can you please guide me ? how do you work with checkbox if you don't want to use a button click listener ?
Thanks a lot in advance :)
You are fetching your CheckBox with
findViewById(R.id.checkbox);
when in the xml, the id is
android:id="#+id/checkBox"
The id is case sensitive so check your capitalization. Basically your code is fetching a view by ID and not finding it. Therefore your cb object is set to null and you throw a nullpointer here
cb.setOnCheckedChangeListener(this);
Use MainActivity.this instead of super for getting view from current layout of MainActivity Activity after calling setContentView:
cb = (CheckBox) MainActivity.this.findViewById(R.id.checkBox);
After initializing the checkBox. add this piece of code for eliminating the null reference.
assert checkBox != null;
After washing my face with some freshwater i found that i gave the wrong ID
instead of
R.id.checkBox
i used
R.id.checkbox