0

I am making a application in which i create a list view with two text fields and one check box ....and when i click or check on check box then the both text are added to database. but my emulator force stopped my application. please help ...thanx in advance.

This is my first main java class named Database2Activity

package data.base;
import android.app.ListActivity;
import android.os.Bundle;
public class Database2Activity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String[] str1 = new String[]{"Hari","Gopal","shayam","sita"};
    String[] str2 = new String[]{"123","2555","sksi","mahi"};
    setListAdapter(new Second(this, str1, str2));   
}
}

This is my Second class which name Second.java

package data.base;

import com.example.phone_no.DBhelper;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

public class Second extends ArrayAdapter<String> {
 String string1[];

 Context context;
    String string[];
     TextView textView;
    TextView textView1;

    CheckBox checkBox;
    EditText editText;
    public Second(Context context, String[] objects, String[] Object1)
    {

        super(context,R.layout.main, objects);

        this.context=context;
        this.string=objects;
        this.string1=Object1;
      //  this.imageView = Object3;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {

        LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view=inflater.inflate(R.layout.main,parent,false);
          textView=(TextView)view.findViewById(R.id.text1);


        textView1=(TextView)view.findViewById(R.id.text2);
       // imageView = (ImageView)view.findViewById(R.id.text3);
        textView.setText(string[position]);
        textView1.setText(string1[position]);

        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub

                DBhelper DB = new DBhelper(context);
                DB.open();
                DB.adddata("A", string[position], string1[position]);
                DB.getAlldata();
                DB.close();


            }
        });

        return view;    //To change body of overridden methods use File | Settings | File Templates.

    }

}

This is my Third Class named DBhelper which managed database actions

package com.example.phone_no;



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBhelper {
public static final String KEY_ID = "id";
public static final String KEY_NAME = "names";

public static final String KEY_PHONE = "phoneno";

private final Context ourContext;
private static final String DATABASE_TABLE = "Contactinfo";
private static final int DATABASE_VERSION = 27;
private static final String DATABASE_NAME = "contactdata.db";
private DbHelper ourHelper;
private SQLiteDatabase ourDatabase;
// end for location
private static class DbHelper extends SQLiteOpenHelper {
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        /*db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ID
                + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT NULL , "
                + KEY_PHONE + " INTEGER NULL);");*/
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ID
                + " INTEGER , " + KEY_NAME + " TEXT NULL , "
                + KEY_PHONE + " INTEGER NULL);");

        // string value
        String y = "CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ID
                + " INTEGER PRIMARY KEY  , " + KEY_NAME + " TEXT NULL , "
                + KEY_PHONE + " INTEGER NULL);";

        System.out.println("query" + y);
        Log.d("query", y);






    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);

    }

}

public DBhelper(Context c) {
    ourContext = c;
}
public DBhelper open() throws SQLException 
{
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

public void close() 
{
    ourHelper.close();
}
public long adddata(String id,String name,String number) 
{
    // TODO Auto-generated method stub
    // add the custom Image Gallery Image Path to Data Base
    ContentValues cv = new ContentValues();
    cv.put(KEY_ID, id);
    cv.put(KEY_NAME, name);
    cv.put(KEY_PHONE, number);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);
}

public void getAlldata() 
{
    Cursor details = null;
    if (ourDatabase.isOpen() == false)

        ourDatabase = ourHelper.getWritableDatabase();
    if (ourDatabase.isOpen()) 
    {
        details = ourDatabase.query(DATABASE_TABLE, null, null, null, null, null, null);
         for(details.moveToFirst();!details.isAfterLast();details.moveToNext())
        {
             String a=details.getString(0);
            String b=details.getString(1);
            String c=details.getString(2);
            System.out.println("id--"+a+"name"+b+"phoneno"+c);
        }



    }


}
public long delete_image(String id) 
  {
    if (ourDatabase.isOpen() == false)
        ourDatabase = ourHelper.getWritableDatabase();
      if (ourDatabase.isOpen()) 
        {
            return ourDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + id, null);
        }
        return 0;
    }



}

This is my main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<EditText
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:id="@+id/edit"
/>
<Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
     />
  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:layout_weight="1"
        android:id="@+id/text1"
        />
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:layout_weight="1"
        android:id="@+id/text2"
        />
    <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/check"
            />



</LinearLayout>

This is Logcat Window massages

03-12 02:04:21.028: D/AndroidRuntime(21905): Shutting down VM
03-12 02:04:21.028: W/dalvikvm(21905): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-12 02:04:21.308: E/AndroidRuntime(21905): FATAL EXCEPTION: main
03-12 02:04:21.308: E/AndroidRuntime(21905): java.lang.NullPointerException
03-12 02:04:21.308: E/AndroidRuntime(21905):    at data.base.Second.getView(Second.java:51)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.widget.AbsListView.obtainView(AbsListView.java:1315)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.widget.ListView.makeAndAddView(ListView.java:1727)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.widget.ListView.fillDown(ListView.java:652)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.widget.ListView.fillFromTop(ListView.java:709)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.widget.ListView.layoutChildren(ListView.java:1580)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.widget.AbsListView.onLayout(AbsListView.java:1147)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.view.View.layout(View.java:7035)
03-12 02:04:21.308: E/AndroidRuntime(21905):    at android.widget.FrameLayout.onLayout(FrameLayout.java:333)

And in last This is my Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="data.base"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".Database2Activity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="Second"/>
</application>

</manifest>
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
dev
  • 61
  • 1
  • 8
  • You should watch the Google I/O talks [TurboCharge your UI](http://www.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html) and [World or ListView](http://www.google.com/events/io/2010/sessions/world-of-listview-android.html) they will help you write a _much_ faster Adapter. – Sam Mar 11 '13 at 20:43

2 Answers2

2
Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

You need use a ListView in your ListActivity's layout (main.xml) with the id android:id="@android:id/list.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);  // This layout must have a ListView
Sam
  • 86,580
  • 20
  • 181
  • 179
  • how can i change the id of ListView . i m new in this field so please explanin your solution – dev Mar 11 '13 at 20:32
  • Well, you are using the same layout for your Activity and your row layout. The Activity's layout should have a ListView in it, the row layout should not... – Sam Mar 11 '13 at 20:33
  • It looks like you want to use ListAcitivty's default layout, so remove `setContentView(R.layout.main);`. _Or_ create a new XML file with a ListView and use this in `setContentView(R.layout.listview_layout);` – Sam Mar 11 '13 at 20:36
  • i Remove "setContentView"(R.layout.main); ......... but my code still gives me null pointer execption .... – dev Mar 11 '13 at 20:56
1

Remove the setContentView(R.layout.main); from your onCreate - you are overwriting the default view for a ListActivity (which contains the android.R.id.list element) with the layout that you are using for each element.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Agreed, the author uses `main.xml` in _both_ the Activity and the Adapter. It looks like it should only be used in the Adapter. – Sam Mar 11 '13 at 20:34
  • ya i Do this when i run my code again then it shows me error = "03-12 02:04:21.308: E/AndroidRuntime(21905): java.lang.NullPointerException 03-12 02:04:21.308: E/AndroidRuntime(21905): at data.base.Second.getView(Second.java:51) " – dev Mar 11 '13 at 20:36
  • @dev That's progress! :) In your Adapter change `super(context,R.layout.main, objects);` to `super(context, R.layout.main, R.id.text1, objects);` – Sam Mar 11 '13 at 20:38
  • @ianhanniballake nope itsnot working ...... and i not understand ur solution and super is bydefault constructud here – dev Mar 11 '13 at 20:51
  • @dev - you are getting the error on line 51 because you never initialize checkBox - make sure you have a CheckBox checkBox = (CheckBox)view.findById(R.id.check); – ianhanniballake Mar 11 '13 at 20:55
  • @ianhanniballake Thanx dude .......you are right ......sometime i make silly and stupid mistakes ......here is 2pm in night and my mind is totally busted bcoz of this code. y the way thanx dude finally i can go to sleep. – dev Mar 11 '13 at 21:08