片段 - 无法实例化活动

时间:2014-03-20 16:33:40

标签: android android-fragments fragment

我有一个直接连接到主片段类的活动类。单击该类上的按钮后,它将带我到另一个输入详细信息的类。第一个类可以工作,但只要单击该按钮,就会产生以下错误:

03-20 16:11:17.055: E/AndroidRuntime(828): FATAL EXCEPTION: main
03-20 16:11:17.055: E/AndroidRuntime(828): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{app.norman.tennis/app.norman.tennis.fours.AddActivity}: java.lang.ClassCastException: app.norman.tennis.fours.AddActivity cannot be cast to android.app.Activity
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879)
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.os.Looper.loop(Looper.java:137)
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.app.ActivityThread.main(ActivityThread.java:4340)
03-20 16:11:17.055: E/AndroidRuntime(828):  at java.lang.reflect.Method.invokeNative(Native Method)
03-20 16:11:17.055: E/AndroidRuntime(828):  at java.lang.reflect.Method.invoke(Method.java:511)
03-20 16:11:17.055: E/AndroidRuntime(828):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-20 16:11:17.055: E/AndroidRuntime(828):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-20 16:11:17.055: E/AndroidRuntime(828):  at dalvik.system.NativeStart.main(Native Method)
03-20 16:11:17.055: E/AndroidRuntime(828): Caused by: java.lang.ClassCastException: app.norman.tennis.fours.AddActivity cannot be cast to android.app.Activity
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
03-20 16:11:17.055: E/AndroidRuntime(828):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870)
03-20 16:11:17.055: E/AndroidRuntime(828):  ... 11 more

下面是显示按钮的第一个类(FoursFragment):

 public class FoursFragment extends Fragment {

private DbHelper mHelper;
private SQLiteDatabase dataBase;

private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();

private ListView userList;
private AlertDialog.Builder build;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.display_activity, container, false);

    userList = (ListView) view.findViewById(R.id.List);

    mHelper = new DbHelper(getActivity());

    //add new record
    view.findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("update", false);
            startActivity(i);

        }
    });

    //click to update data
    userList.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("Fname", user_fName.get(arg2));
            i.putExtra("Lname", user_lName.get(arg2));
            i.putExtra("ID", userId.get(arg2));
            i.putExtra("update", true);
            startActivity(i);

        }
    });

    //long click to delete data
    userList.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {

            build = new AlertDialog.Builder(getActivity());
            build.setTitle("Delete " + user_fName.get(arg2) + " "
                    + user_lName.get(arg2));
            build.setMessage("Do you want to delete ?");
            build.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {

                            Toast.makeText(
                                    getActivity(),
                                    user_fName.get(arg2) + " "
                                            + user_lName.get(arg2)
                                            + " is deleted.", 3000).show();

                            dataBase.delete(
                                    DbHelper.TABLE_NAME,
                                    DbHelper.KEY_ID + "="
                                            + userId.get(arg2), null);
                            displayData();
                            dialog.cancel();
                        }
                    });

            build.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = build.create();
            alert.show();

            return true;
        }
    });
    return view;
}

@Override
public void onResume() {
    displayData();
    super.onResume();
}

/**
 * displays data from SQLite
 */
private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    if (mCursor.moveToFirst()) {
        do {
            userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
            user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName);
    userList.setAdapter(disadpt);
    mCursor.close();
}   
 }

现在显示错误的活动:

public class AddActivity extends Fragment implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname;
private boolean isUpdate;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.add_activity, container, false);


    btn_save=(Button) view.findViewById(R.id.save_btn);
    edit_first=(EditText)view.findViewById(R.id.frst_editTxt);
    edit_last=(EditText)view.findViewById(R.id.last_editTxt);

   isUpdate=getActivity().getIntent().getExtras().getBoolean("update");
    if(isUpdate)
    {
        id=getActivity().getIntent().getExtras().getString("ID");
        fname=getActivity().getIntent().getExtras().getString("Fname");
        lname=getActivity().getIntent().getExtras().getString("Lname");
        edit_first.setText(fname);
        edit_last.setText(lname);

    }

     btn_save.setOnClickListener(this);

     mHelper=new DbHelper(getActivity());
    return view;

}

// saveButton click event 
public void onClick(View v) {
    fname=edit_first.getText().toString().trim();
    lname=edit_last.getText().toString().trim();
    if(fname.length()>0 && lname.length()>0)
    {
        saveData();
    }
    else
    {
        AlertDialog.Builder alertBuilder=new AlertDialog.Builder(getActivity());
        alertBuilder.setTitle("Invalid Data");
        alertBuilder.setMessage("Please, Enter valid data");
        alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();

            }
        });
        alertBuilder.create().show();
    }

}

/**
 * save data into SQLite
 */
private void saveData(){
    dataBase=mHelper.getWritableDatabase();
    ContentValues values=new ContentValues();

    values.put(DbHelper.KEY_FNAME,fname);
    values.put(DbHelper.KEY_LNAME,lname );

    System.out.println("");
    if(isUpdate)
    {    
        //update database with new data 
        dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
    }
    else
    {
        //insert data into database
        dataBase.insert(DbHelper.TABLE_NAME, null, values);
    }
    //close database
    dataBase.close();       

}
 }

这个应用程序可以扩展活动,但我第一次处理碎片让我感到很困难。

如果您需要任何其他信息或课程,请告诉我,我会提供。是因为它没有直接连接到片段,而是从后续类调用吗?

2 个答案:

答案 0 :(得分:2)

  

引起:java.lang.ClassCastException:   app.norman.tennis.fours.AddActivity无法转换为   android.app.Activity

你有

 Intent i = new Intent(getActivity(),
                AddActivity.class);
 i.putExtra("update", false);
 startActivity(i);

  Intent i = new Intent(getActivity(),
                AddActivity.class);
   i.putExtra("Fname", user_fName.get(arg2));
        i.putExtra("Lname", user_lName.get(arg2));
        i.putExtra("ID", userId.get(arg2));
        i.putExtra("update", true);
        startActivity(i);

这个

 public class AddActivity extends Fragment implements OnClickListener {

AddActivity不是Activity类。它是一个片段,你无法像活动一样开始片段。

您需要将片段添加到容器中。 FragmentActivity托管。

因此,在您的Activity xml中有一个容器并向其添加或替换片段。

来自文档的示例

Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

答案 1 :(得分:1)

您有此错误日志

Caused by: java.lang.ClassCastException: app.norman.tennis.fours.AddActivity cannot be cast to android.app.Activity

它是becoz AddActivity不是Activity类。它是Fragment,你不能像活动一样开始片段化。

请转到此详细信息:http://developer.android.com/reference/android/app/Fragment.html