1

我从服务器获取 json 数据,我想将该数据传递给我的数据库,我想在我的列表视图中显示这些数据,现在它抛出了一些空指针异常。

Mainactivity.java

   public class MainActivity extends ListActivity implements FetchDataListener,OnClickListener{
    private static final int ACTIVITY_CREATE=0;
    private static final int TAG_CATEGORY = 0;
    private static final String CATEGORY_COLUMN_ID = "_id";
    private static final String CATEGORY_COLUMN_TITLE = "title";
    private static final String CATEGORY_COLUMN_CONTENT = "content";
    private static final String CATEGORY_COLUMN_COUNT = "count";
    private static final int Application = 0;
    private ProgressDialog dialog;
    ListView lv;
    ListView lv1;
    private List<Application> items;
    private Button btnGetSelected;
    private Button praycount;
    public int pct;
    private String stringVal;
    private TextView value;
    private int prayers;
    private int prayerid;
    EditText myFilter;
    ApplicationAdapter adapter;
     private GinfyDbAdapter mDbHelper;
     JSONArray contacts = null;
        private SimpleCursorAdapter dataAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_item); 
        mDbHelper=new GinfyDbAdapter(MainActivity.this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());


        lv1 =(ListView)findViewById(R.id.list); 
        lv =(ListView)findViewById(R.id.list);



        btnGetSelected = (Button) findViewById(R.id.btnget);
        btnGetSelected.setOnClickListener(this);

        myFilter = (EditText) findViewById(R.id.myFilter);


        // Adding items to listview


        /**
         * Enabling Search Filter
         * */




        new GetDataAsyncTask().execute();
        //praycount.setOnClickListener(this);
        //initView();
    }



    /*private void initView(){
        // show progress dialog
        dialog = ProgressDialog.show(this, "", "Loading...");
        String url = "http://www.ginfy.com/api/v1/posts.json";
        FetchDataTask task = new FetchDataTask(this);
        task.execute(url);


    }   */

    private class GetDataAsyncTask extends AsyncTask<Void, Void, Boolean> {
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        protected void onPreExecute() {
            Dialog.setMessage("Loading.....");
            Dialog.show();
        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            Dialog.dismiss();
            Intent intent = new Intent(MainActivity.this, MainActivity.class);
            startActivity(intent);
        }
        @Override
        protected Boolean doInBackground(Void... params) {
            getProdData();
            return null;
        }
    }

    public void getProdData() {
        // getting JSON string from URL
        JSONParser  jsonObject = new JSONParser();
        //JSONObject jsonObject = new JSONObject();
            //JSONArray aJson = jsonObject.getJSONArray("post");
            String url = "http://www.ginfy.com/api/v1/posts.json";
            // getting JSON string from URL
            //JSONArray aJson = jsonObject.getJSONArray(url);
            JSONArray Json = jsonObject.getJSONFromUrl(url);

            try {
                // Getting Array of Contacts
                contacts = Json.getJSONArray(TAG_CATEGORY);

                // looping through All Contacts
                for(int i = 0; i < contacts.length(); i++){
                    JSONObject c = contacts.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(CATEGORY_COLUMN_ID);
                    String title = c.getString(CATEGORY_COLUMN_TITLE);
                    String  content = c.getString(CATEGORY_COLUMN_CONTENT);
                    String  count = c.getString(CATEGORY_COLUMN_COUNT);

                    mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    private void fillData() {
        mDbHelper.open();   
        Cursor projectsCursor = mDbHelper.fetchAllProjects();
        //startManagingCursor(projectsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};

        /* Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter projects = 
                new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
        setListAdapter(projects);
        */
        // create the adapter using the cursor pointing to the desired data 
        //as well as the layout information
         dataAdapter  = new SimpleCursorAdapter(
          this, R.layout.activity_row, 
          projectsCursor, 
          from, 
          to,
          0);
         setListAdapter(dataAdapter);




    }



    private void setListAdapter(SimpleCursorAdapter dataAdapter2) {
        // TODO Auto-generated method stub

    }

它在这一行显示错误, registerForContextMenu(getListView());它抛出空指针异常。

mycategory.java

public class Category {

    String _id; 
    String title; 
    String content;
    String count;
    public Category(String id, String title, String content, String count) {
        super();
        this._id = id;
        this.title = title;
        this.content = content;
        this.count = count;
    }
    public String getId() {
        return _id;
    }
    public void setId(String id) {
        this._id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
}

这是我给的数据库部分

public class GinfyDbAdapter {

    private static final String DATABASE_NAME = "test";
    private static final String DATABASE_TABLE_PROJ = "projects";
    private static final int DATABASE_VERSION = 3;
    public static final String CATEGORY_COLUMN_ID = "_id";
    public static final String CATEGORY_COLUMN_TITLE = "title";
    public static final String CATEGORY_COLUMN_CONTENT = "content";
    public static final String CATEGORY_COLUMN_COUNT = "count";


    private static final String TAG = "GinfyDbAdapter";
    private DatabaseHelper mDbHelper;
    private static SQLiteDatabase mDb;
    private final Context mCtx;





    public void saveCategoryRecord(String id, String title, String content, String count) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(CATEGORY_COLUMN_ID, id);
        contentValues.put(CATEGORY_COLUMN_TITLE, title);
        contentValues.put(CATEGORY_COLUMN_CONTENT, content);
        contentValues.put(CATEGORY_COLUMN_COUNT, count);
        mDb.insert(DATABASE_NAME, null, contentValues);
        }
    public Cursor getTimeRecordList() {
        return mDb.rawQuery("select * from " + DATABASE_NAME, null);
        }
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }



        private static final String DATABASE_CREATE_PROJ =
                "create table " + DATABASE_TABLE_PROJ + " ("
                + CATEGORY_COLUMN_ID + " integer primary key , "
                + CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String DATABASE_CREATE_PROJ = "CREATE TABLE " +  DATABASE_TABLE_PROJ + "( "
                + CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
                + CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER   );" ;
                db.execSQL(DATABASE_CREATE_PROJ);     
    }

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


}

    public void saveCategoryRecord(Category category) {

        String query = "insert into"+ DATABASE_NAME+ " values( ?, ?, ?, ?, ?, ? )";
        SQLiteStatement stmt = mDb.compileStatement(query);
        stmt.bindString(1, category.getId());
        stmt.bindString(2, category.getTitle());
        stmt.bindString(3, category.getContent());
        stmt.bindString(4, category.getCount());
        stmt.execute();
    }

    public Cursor fetchAllProjects() {
        // TODO Auto-generated method stub
        return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
    }

    public GinfyDbAdapter(Context ctx) {
        this.mCtx = ctx;

    }

     public GinfyDbAdapter open() throws SQLException {
            mDbHelper = new DatabaseHelper(mCtx);
            mDb = mDbHelper.getWritableDatabase();
            return this;
        }


}

将json数据发送到数据库并显示在列表视图中,我的代码是否正确

Logcat 错误是

07-05 08:59:57.605: E/AndroidRuntime(30062): FATAL EXCEPTION: main
07-05 08:59:57.605: E/AndroidRuntime(30062): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonandroid/com.example.jsonandroid.MainActivity}: java.lang.NullPointerException
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.os.Looper.loop(Looper.java:137)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.ActivityThread.main(ActivityThread.java:5039)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at java.lang.reflect.Method.invokeNative(Native Method)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at java.lang.reflect.Method.invoke(Method.java:511)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at dalvik.system.NativeStart.main(Native Method)
07-05 08:59:57.605: E/AndroidRuntime(30062): Caused by: java.lang.NullPointerException
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.Activity.registerForContextMenu(Activity.java:2857)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at com.example.jsonandroid.MainActivity.onCreate(MainActivity.java:68)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.Activity.performCreate(Activity.java:5104)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-05 08:59:57.605: E/AndroidRuntime(30062):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
4

2 回答 2

1

您的课程没有扩展ListActivity

    registerForContextMenu(getListView());

http://developer.android.com/reference/android/app/ListActivity.html#getListView()

public ListView getListView ()

获取活动的列表视图小部件。

你有这个可以删除的。

private View getListView() {
    // TODO Auto-generated method stub
    return null; // returning null
}

你也有这个

 lv1 =(ListView)findViewById(R.id.list); 
 lv =(ListView)findViewById(R.id.list);

两者都引用相同的资源ID。

从你的评论中你说你得到

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

您自己的视图必须包含一个 ID 为“@android:id/list”的 ListView 对象(或者如果它在代码中,则为列表)

           <ListView 
           android:id="@android:id/list" // must have this
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:background="#00FF00"
           android:layout_weight="1"
           android:drawSelectorOnTop="false"/>

编辑:

    public class MainActivity extends ListActivity{// implements FetchDataListener,OnClickListener{
     private GinfyDbAdapter mDbHelper;
     JSONArray contacts = null;
        private SimpleCursorAdapter dataAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        mDbHelper=new GinfyDbAdapter(MainActivity.this);
        mDbHelper.open();
        Cursor projectsCursor = mDbHelper.fetchAllProjects();
        if(projectsCursor!=null)
        {
        fillData(projectsCursor);
        }
        else
        {
             new GetDataAsyncTask().execute();
        }
    }

    private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        protected void onPreExecute() {
            Dialog.setMessage("Loading.....");
            Dialog.show();
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Dialog.dismiss();

            Cursor projectsCursor = mDbHelper.fetchAllProjects();
            if(projectsCursor!=null)
            {
            mDbHelper=new GinfyDbAdapter(MainActivity.this);
            mDbHelper.open();
            fillData(projectsCursor);
            }
        }
        @Override
        protected Void doInBackground(Void... params) {
            getData();
            return null;
        }
    }
    public void getData()
    {
          try
            {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpGet request = new HttpGet("http://www.ginfy.com/api/v1/posts.json");
        // HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");     

        HttpResponse response = httpclient.execute(request);
        HttpEntity resEntity = response.getEntity();
        String _response=EntityUtils.toString(resEntity); // content will be consume only once
         Log.i("................",_response);
        httpclient.getConnectionManager().shutdown();
        JSONObject jsonObject = new JSONObject(_response);
        JSONArray contacts = jsonObject.getJSONArray("post");//(url);
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);
                String id = c.getString("id");
                String title = c.getString("title");
                String  content = c.getString("content");
                String  count = c.getString("content");
                mDbHelper=new GinfyDbAdapter(MainActivity.this);
                mDbHelper.open();
                mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
    @SuppressWarnings("deprecation")
    private void fillData(Cursor projectsCursor) {
        //mDbHelper.open();   

        if(projectsCursor!=null)
        {
        String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
        int[] to = new int[]{R.id.textView1, R.id.textView2, R.id.textView3};
         dataAdapter  = new SimpleCursorAdapter(
          this, R.layout.activity_row, 
          projectsCursor, 
          from, 
          to,
          0);
         setListAdapter(dataAdapter);
        }else
        {
            Log.i("...........","null");
        }
    }
}

数据库类的另一个变化

void saveCategoryRecord(Category category) {
      ///  SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
        values.put(CATEGORY_COLUMN_CONTENT, category.getContent()); 
        values.put(CATEGORY_COLUMN_COUNT, category.getCount());   
        // Inserting Row
        mDb.insert(DATABASE_TABLE_PROJ, null, values);
        mDb.close(); // Closing database connection

    }
于 2013-07-05T09:17:04.467 回答
0

从 ListActivity 扩展您的活动

于 2013-07-05T09:19:21.863 回答