Android Fatal Exception: main ve bunun sebebi de Java.lang.NullPointerException olduğunu belirten hatanın çözümü activity içindeki onCreate() metoudunda aşağıdaki gibi bir tanımlama yapmalısınız. Benim layout default olduğunda ismi main dir.
setContentView(R.layout.main);
Bunun sebebi bir layoutun içindeki componentlere findViewById(); metodu ile erişiyorsanız mutlaka o layoutu setContentView(R.layout.layout_name); ile belirtmelisiniz.
Bir de findById() ile componente erişmeden kullanırsak o da NullPointerException veriri. Yani textView=(TextView) findViewById(R.id.textView1_dene); şeklinde bir atama yapmadan textViewi kullanamam.
MyMainActivity.java
package com.ethem.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MyMainActivity extends Activity {
private TextView textView;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Aşağıdaki satır yorum halinde olduğundan NullPointerException hatası verecek.
// setContentView(R.layout.main);
textView=(TextView) findViewById(R.id.textView1_dene);
button=(Button) findViewById(R.id.button1_dene);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
textView.setText("Button tiklandi");
}
});
}
}
main.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"
>
<TextView android:text="Deneme" android:id="@+id/textView1_dene" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:text="Button" android:id="@+id/button1_dene" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>


Write a Comment
Let me know what you think?