ListActivity从SQlite到LIstFragment NullPointerException

时间:2013-07-18 04:00:48

标签: android sqlite nullpointerexception listactivity

我正在按照本教程[http://vimaltuts.com/android-tutorials/android-load-image-from-sqlite-to-listview] [1]来创建sqlite数据库中的联系人列表,添加,编辑和删除。工作完美,但现在我想将此listActivity更改为listfragment。到目前为止,我还没有能够做到这一点,我得到了Null Pointer Exception(见下文)。我认为碎片循环有问题。能帮忙吗?

原始我的联系人活动

import com.vimaltuts.mycontacts.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;

public class MyContactsActivity extends ListActivity {

    SQLiteConnector sqlCon;
    private CustomContactsAdapter custAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);     
        String[] from = new String[] { Contacts.NAME, Contacts.PHONE,Contacts.MAIL };
        int[] to = new int[] { R.id.name, R.id.phone, R.id.email };
        custAdapter = new CustomContactsAdapter(this,R.layout.contact_list_item, null, from, to);
        this.setListAdapter(custAdapter);       
    }

    @Override
    protected void onResume() {
        super.onResume();
        new GetContacts().execute((Object[]) null);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onStop() {
        Cursor cursor = custAdapter.getCursor();

        if (cursor != null)
            cursor.deactivate();

        custAdapter.changeCursor(null);
        super.onStop();

    }

    private class GetContacts extends AsyncTask<Object, Object, Cursor> {
        SQLiteConnector dbConnector = new SQLiteConnector(MyContactsActivity.this);

        @Override
        protected Cursor doInBackground(Object... params) {
            return dbConnector.getAllContacts();
        }

        @Override
        protected void onPostExecute(Cursor result) {
            custAdapter.changeCursor(result); 
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_my_contacts, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent addContact = new Intent(MyContactsActivity.this,AddEditContacts.class);
        startActivity(addContact);
        return super.onOptionsItemSelected(item);
    }

}

自定义联系人适配器

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomContactsAdapter extends SimpleCursorAdapter {

    private int layout;
    private ImageButton editBtn;
    private ImageButton delBtn;
    LayoutInflater inflator;

    public CustomContactsAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
        super(context, layout, c, from, to,0);
        this.layout = layout;
        inflator= LayoutInflater.from(context);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {     
        View v = inflator.inflate(layout, parent, false);
        return v;
    }

    @Override
    public void bindView(View v, final Context context, Cursor c) {
        final int id = c.getInt(c.getColumnIndex(Contacts.ID));
        final String name = c.getString(c.getColumnIndex(Contacts.NAME));
        final String phone = c.getString(c.getColumnIndex(Contacts.PHONE));
        final String email = c.getString(c.getColumnIndex(Contacts.MAIL));
        final String fb = c.getString(c.getColumnIndex(Contacts.FB));
        final byte[] image = c.getBlob(c.getColumnIndex(Contacts.IMAGE));
        ImageView iv = (ImageView) v.findViewById(R.id.photo);

        if (image != null) {
            if (image.length > 3) {
                iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
            }
        }

        TextView tname = (TextView) v.findViewById(R.id.name);
        tname.setText(name);
        TextView tphone = (TextView) v.findViewById(R.id.phone);
        tphone.setText(phone);
        TextView temail = (TextView) v.findViewById(R.id.email);
        temail.setText(email);

        final SQLiteConnector sqlCon = new SQLiteConnector(context);

        editBtn=(ImageButton) v.findViewById(R.id.edit_btn);    
        editBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(context,AddEditContacts.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                
                intent.putExtra("id", id);
                intent.putExtra("name", name);
                intent.putExtra("phone", phone);
                intent.putExtra("email", email);
                intent.putExtra("fb", fb);
                intent.putExtra("blob", image);
                context.startActivity(intent);
            }

        });

        delBtn=(ImageButton) v.findViewById(R.id.del_btn);  
        delBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                sqlCon.deleteContact(id);   
                Intent intent=new Intent(context,ChildrenListFragment.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }

        });     

        v.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(context,ViewContact.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                
                intent.putExtra("id", id);
                intent.putExtra("name", name);
                intent.putExtra("phone", phone);
                intent.putExtra("email", email);
                intent.putExtra("fb", fb);
                intent.putExtra("blob", image);
                context.startActivity(intent);
            }
        });

    }

}

更改了我的通讯录活动

public class MyContactsActivity  extends ListFragment{

    SQLiteConnector sqlCon;
    private CustomContactsAdapter custAdapter;  


    @Override
  public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);

      Activity activity = getActivity();

      if (activity != null) {


          String[] from = new String[] { Contacts.NAME, Contacts.PHONE,Contacts.MAIL };
          int[] to = new int[] { R.id.name, R.id.phone, R.id.email };
          CustomContactsAdapter custAdapter = new CustomContactsAdapter(activity,R.layout.contact_list_item, null, from, to);
            this.setListAdapter(custAdapter);   
            SQLiteConnector dbConnector = new SQLiteConnector(activity);


      }
  }

    @Override
    public void onResume() {
        super.onResume();
        new GetContacts().execute((Object[]) null);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStop() {
        Cursor cursor = custAdapter.getCursor();

        if (cursor != null)
            cursor.deactivate();

        custAdapter.changeCursor(null);
        super.onStop();

    }

    private class GetContacts extends AsyncTask<Object, Object, Cursor> {
        Activity activity = getActivity();
        SQLiteConnector dbConnector = new SQLiteConnector(activity);

        @Override
        protected Cursor doInBackground(Object... params) {
            return dbConnector.getAllContacts();
        }

        @Override
        protected void onPostExecute(Cursor result) {
            if (isDestroyed) return;
            custAdapter.changeCursor(result); 
        }


    }


    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
        //getActivity().getMenuInflater().inflate(R.menu.activity_my_contacts, menu);
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.activity_my_contacts, menu);


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Activity activity = getActivity();
        Intent addContact = new Intent(activity,AddEditContacts.class);
        startActivity(addContact);
        return super.onOptionsItemSelected(item);
    }


}

错误

07-17 22:01:33.959: E/AndroidRuntime(10924): java.lang.NullPointerException
07-17 22:01:33.959: E/AndroidRuntime(10924):    at com.ektroid.graphico.MyContactsActivity$GetContacts.onPostExecute(MyContactsActivity.java:95)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at com.ektroid.graphico.MyContactsActivity$GetContacts.onPostExecute(MyContactsActivity.java:1)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at android.os.AsyncTask.finish(AsyncTask.java:602)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at android.os.AsyncTask.access$600(AsyncTask.java:156)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at android.os.Looper.loop(Looper.java:137)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at android.app.ActivityThread.main(ActivityThread.java:4424)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at java.lang.reflect.Method.invokeNative(Native Method)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at java.lang.reflect.Method.invoke(Method.java:511)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-17 22:01:33.959: E/AndroidRuntime(10924):    at dalvik.system.NativeStart.main(Native Method)
07-17 22:01:34.569: I/dalvikvm(10924): threadid=3: reacting to signal 3
07-17 22:01:34.569: I/dalvikvm(10924): Wrote stack traces to '/data/anr/traces.txt'
07-17 22:01:35.859: I/Process(10924): Sending signal. PID: 10924 SIG: 9

3 个答案:

答案 0 :(得分:0)

在OnPostExecute内部使用以下条件

if( (!isRemoving()) && (isResumed()) && cursor!=null )

答案 1 :(得分:0)

在onResume中,您将null传递给结果...
因为onResume是在Activity的生命周期中的onCreate之后执行的......

答案 2 :(得分:0)

我逐步检查了碎片的生命周期,也检查了活动的生命周期。我比较了Activity版本VS片段版本。除了doInBackground返回null之外,Fragment版本中的所有内容都显得正常。我找不到原因。我尝试了许多不同的解决方案但没有成功。最后,我决定停止使用片段并使用活动。活动一切都很完美