Fetch data from database SQLite with fragment - java

This is my fragment activity i am getting error while accessing database my code is :-
public class Test extends Fragment {
View view;
private Cursor c;
private final String DB = "Canary";
private SQLiteDatabase db2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.test, container, false);
Button b = (Button) view.findViewById(R.id.test_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Listning",Toast.LENGTH_LONG).show();
}
});
db2 = SQLiteDatabase.openOrCreateDatabase(DB, null);
Log.d("Lee", "working her1");
c=db2.rawQuery("SELECT * FROM business_master", null);
Log.d("Lee", "working here2");
c.moveToFirst();
String id=c.getString(c.getColumnIndex("id"));
Log.d("id", "" + id);
String email=c.getString(c.getColumnIndex("email"));
Log.d("email", email);
String password=c.getString(c.getColumnIndex("password"));
db2.close();
return view;
} }
The error i am getting :-
01-20 11:35:57.168 17081-17081/com.purplefront.canary E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.purplefront.canary, PID: 17081
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
at com.purplefront.canary.Test.onCreateView(Test.java:36)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
If i remove the database access it will work fine as expected but i need database access in fragment only.
Any help would be appreciated.

Related

How to rectify this error iin Recyclerview with database

When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}

Library in Android Studio - NullPointerException

i tried to use a library (https://android-arsenal.com/details/1/1414) for a sticky header in a list view. I this configured well the library because i can use classes from there.
The code i'm using is like in the example from the link above, but i get a nullPointerExeption at ".build();"
This is the code :
public class MainActivity extends Activity {
ViewGroup containerLayout ;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
containerLayout = (ViewGroup) findViewById(R.id.containerLayout);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[]{"Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
StikkyHeaderBuilder.stickTo(listView)
.setHeader(R.id.header,containerLayout )
.minHeightHeader(250)
.animator(new IconAnimator())
.build();
} }
And this is my error log:
08-14 15:10:57.188 32562-32562/com.example.cretucalinn.stickyheader1
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cretucalinn.stickyheader1, PID: 32562
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.cretucalinn.stickyheader1/com.example.cretucalinn.stickyheader1.MainActivity}:
java.lang.NullPointerException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2412)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
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
it.carlom.stikkyheader.core.StikkyHeader.disallowTouchBehindHeader(StikkyHeader.java:47)
at
it.carlom.stikkyheader.core.StikkyHeader.build(StikkyHeader.java:38)
at
it.carlom.stikkyheader.core.StikkyHeaderBuilder$ListViewBuilder.build(StikkyHeaderBuilder.java:113)
at
it.carlom.stikkyheader.core.StikkyHeaderBuilder$ListViewBuilder.build(StikkyHeaderBuilder.java:95)
at
com.example.cretucalinn.stickyheader1.MainActivity.onCreate(MainActivity.java:61)
at android.app.Activity.performCreate(Activity.java:5458)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470) 
at android.app.ActivityThread.access$900(ActivityThread.java:174) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5593) 
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)

Android CursorAdapter giving java.lang.NullPointerException error

I am having a few issues running my custom CursorAdapter in my application. According to my logcat, the error I get:
11-08 06:41:03.228 6109-6109/? W/System.err? java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
11-08 06:41:03.229 6109-6109/? W/System.err? at com.app.name.MyActivity.onCreate(MyActivity.java:71)
11-08 06:41:03.231 6109-6109/? E/AndroidRuntime? FATAL EXCEPTION: main
occurs at line 71 which sets the adapter (obj.setAdapter(myAdapter)). Initially I thought my database data retrieve function (Cursor chatCursor = mydb.selectConversation(msgId);) did not return any data but after testing it with the chatCursor.getCount() function, I realized that was not the case. Kindly assist me in solving this issue. Below are the codes for my activity, adapter and logcat. Thanks in advance.
MyAdapter.java
public class MyAdapter extends CursorAdapter {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public MyAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.chat_left, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView user = (TextView) view.findViewById(R.id.reply_user);
TextView msg = (TextView) view.findViewById(R.id.reply_msg);
String theTime = cursor.getString(cursor.getColumnIndexOrThrow("message_id"));
String theMessage = cursor.getString(cursor.getColumnIndexOrThrow("message"));
user.setText(theTime);
msg.setText(String.valueOf(theMessage));
}
}
MyActivity.java
public class MyActivity extends ListActivity {
//Utils Class
Utils util;
final Context context = this;
private ProgressBar dialog;
ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
util = new Utils(this);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
final Integer msgId = extras.getInt("id");
obj = (ListView) findViewById(R.id.list);
Cursor chatCursor = mydb.selectConversation(msgId);
MyAdapter myAdapter = new MyAdapter(this, chatCursor);
obj.setAdapter(myAdapter);
}
}
logcat
11-08 06:41:03.228 6109-6109/? W/System.err? java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
11-08 06:41:03.229 6109-6109/? W/System.err? at com.app.name.MyActivity.onCreate(MyActivity.java:71)
11-08 06:41:03.231 6109-6109/? E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2351)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.app.name.MyActivity.onCreate(MyActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
11-08 06:41:03.238 559-832/? W/ActivityManager? Force finishing activity com.app.name/.MyActivity
11-08 06:41:03.742 559-574/? W/ActivityManager? Activity pause timeout for ActivityRecord{42e71938 u0 com.app.name/.MyActivity}
Take a look to your activity_view.xml. Probably the listview ID isn't "list" as you state when you try to find it with findViewById(R.layout.list).

java.lang.RuntimeException: Unable to start activity ComponentInfo{..}java.lang.NullPointerException

I want to add some data to sqlite dy fragmnet.but when i Run the code it gives this error..
java.lang.RuntimeException: Unable to start activity ComponentInfo{codes.project.sameera.o_project/codes.project.sameera.o_project.Indi_Add_Details_menu}: java.lang.NullPointerException
i can add data to sqlite by this code without using Fragment.but when i convert my class into Fragmnet this happen.
How Can i fix this..?
this is my Fragment_addStudentDetails class
public class Fragment_addStudentDetails extends Fragment implements View.OnClickListener {
EditText fName,mName, Address, sName, hNo, mNo, presentSpo;
DatabaseAdapter databaseHelper;
Button btnAdd;
Button btnView;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_add_student_details,container,false);
fName=(EditText) view.findViewById(R.id.editTextfname);
mName=(EditText) view.findViewById(R.id.editTextmName);
Address = (EditText) view.findViewById(R.id.editTextAdd);
sName = (EditText) view.findViewById(R.id.editTextsure);
hNo = (EditText) view.findViewById(R.id.editTexttpH);
mNo = (EditText) view.findViewById(R.id.editTextTPM);
presentSpo = (EditText) view.findViewById(R.id.editTextPS);
btnAdd = (Button) view.findViewById(R.id.btnAdd);
btnView = (Button) view.findViewById(R.id.btnView);
btnAdd.setOnClickListener(this);
btnView.setOnClickListener(this);
databaseHelper = new DatabaseAdapter(getActivity());
return view;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAdd:
addStudent(view);
break;
case R.id.btnView:
viewDetails(view);
break;
default:
break;
}
}
public void addStudent(View view){
String fname = fName.getText().toString();
String mname = mName.getText().toString();
String sname = sName.getText().toString();
String address = Address.getText().toString();
String TPhome = hNo.getText().toString();
String TPmobile = mNo.getText().toString();
String presentsport = presentSpo.getText().toString();
long id= databaseHelper.insertData(fname, mname, sname, address, TPhome, TPmobile, presentsport);
if(id<0){
Message.message(getActivity(),"Error inInsertiong Data");
}else
{
Message.message(getActivity(),"Succecsfuly inserted to data");
}
}
public void viewDetails(View view){
String data = databaseHelper.getAllData();
Message.message(getActivity(),data);
}
}
log cat
java.lang.RuntimeException: Unable to start activity ComponentInfo{codes.project.sameera.o_project/codes.project.sameera.o_project.Indi_Add_Details_menu}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at codes.project.sameera.o_project.Fragment_addStudentDetails.onCreateView(Fragment_addStudentDetails.java:38)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.Activity.performStart(Activity.java:5240)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
           
btnAdd is null which results in the NullPointerException in btnAdd.setOnClickListener(this). This is because the fragment_add_student_details layout contains no View with the btnAdd id.

Android Fragment causes NullPointerException

First going to say that I know there are a lot of similar posts to this, and I have seen them, however I am new to android development and am not yet familiar enough with it to modify those other answers to fix my exact problem.
I have a fragment that was created by default with a new project that contains a button and text view, and in my MainActivity.java i've made an onClick function for the button. This function throws the NPE. Here's the LogCat:
03-10 19:26:52.620: D/AndroidRuntime(878): Shutting down VM
03-10 19:26:52.620: W/dalvikvm(878): threadid=1: thread exiting with uncaught exception (group=0xb2af2ba8)
03-10 19:26:52.630: E/AndroidRuntime(878): FATAL EXCEPTION: main
03-10 19:26:52.630: E/AndroidRuntime(878): Process: com.example.main, PID: 878
03-10 19:26:52.630: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.main/com.example.main.MainActivity}: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:102)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:136)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-10 19:26:52.630: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:515)
03-10 19:26:52.630: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-10 19:26:52.630: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-10 19:26:52.630: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878): Caused by: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878): at com.example.main.MainActivity.onCreate(MainActivity.java:31)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.Activity.performCreate(Activity.java:5231)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-10 19:26:52.630: E/AndroidRuntime(878): ... 11 more
03-10 19:31:54.292: I/Process(878): Sending signal. PID: 878 SIG: 9
The MainActivity.java:
package com.example.main;
import android.support.v7.app.ActionBarActivity;
...
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
final TextView myText = (TextView) findViewById(R.id.text1);
Button myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myText.setText("Yes!");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
If the TextView and the Button are in the layout's fragment, you need to find their id in the onCreatedView method of the fragment. Then, you should do:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final TextView myText = (TextView) rootView.findViewById(R.id.text1);
Button myButton = (Button) rootView.findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myText.setText("Yes!");
}
});
return rootView;
}
}
then myButton is null. so findViewById(R.id.button1) is returning null. You should make sure that is the id you have used for the button your layout (R.layout.fragment_main)
I don't see any fetal mistakes in your OnCreate code but here are some hints to solve the problem
1) Make sure that youractivity is initialized in the Manifest.xml file.
2) Try to run the project after commenting the onClickListener part to make sure that your problem is not in the inflation or in the Layout xml file itself.
3) Try to debug yourOnCreate method and monitor all the different variable values by selecting the variable TO find out the problem
4) Make sure that your button and TextView are in the layout that you are inflating
I hope I could help
The myButton.setOnClickListener(new View.OnClickListener() line gives an exception because its done after you started the fragment, I believe. Put that code in the fragment constructor, and you should be good.

Categories

Resources