片段内的上下文问题(android.view.ContextThemeWrapper无法强制转换为android.app.Activity)

时间:2015-10-18 22:56:42

标签: java android android-fragments android-context

我在SQLite上关注本教程:https://www.youtube.com/watch?v=3k3CunDZpFk&list=PLshdtb5UWjSrEUEKlfHwqQtYu2HxtCwu_&index=8

我正在尝试做他所做的事,但是来自一个片段。我无法理解我得到的上下文错误。有谁可以向我解释一下?

如果您需要进一步的信息,请不要犹豫。

感谢您的时间。

10-18 17:33:16.860    7384-7384/com.example.michael.rogplayer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.michael.rogplayer, PID: 7384
java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to android.app.Activity
        at com.example.michael.rogplayer.BackgroundTask.<init>(BackgroundTask.java:20)
        at com.example.michael.rogplayer.CreateNewChar_Fragment$1.onClick(CreateNewChar_Fragment.java:98)

第20行:activity = (Activity) ctx;

第98行:BackgroundTask backgroundTask = new BackgroundTask(getView().getContext());

这是CreateNewChar_Fragment.java

public class CreateNewChar_Fragment extends DialogFragment {

private static Activity scanForActivity(Context cont) {
    if (cont == null)
        return null;
    else if (cont instanceof Activity)
        return (Activity)cont;
    else if (cont instanceof ContextWrapper)
        return scanForActivity(((ContextWrapper)cont).getBaseContext());

    return null;
}

EditText name;
Button CANCEL, SAVE;
String NAME;
Context CTX;

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public static CreateNewChar_Fragment newInstance(String param1, String param2) {
    CreateNewChar_Fragment fragment = new CreateNewChar_Fragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

public CreateNewChar_Fragment() {

}

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

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    getDialog().setTitle("State your name!");

    return inflater.inflate(R.layout.fragment_create_new_char_, container, false);

}



public void onViewCreated(View container, Bundle savedInstanceState) {
    super.onViewCreated(container, savedInstanceState);

    CTX = container.getContext();
    SAVE = (Button) getView().findViewById(R.id.save);
    CANCEL = (Button) getView().findViewById(R.id.cancel);
    name = (EditText) getView().findViewById(R.id.name);
    NAME = name.getText().toString();

    SAVE.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (TextUtils.isEmpty(name.getText())) {
                Toast.makeText(getView().getContext(), "Are you mute!?!?! State your name!!!",
                        Toast.LENGTH_LONG).show();
            } else {
                BackgroundTask backgroundTask = new BackgroundTask(getView().getContext());
                backgroundTask.execute("add_info", NAME);
                getDialog().dismiss();
            }
        }
    });

    CANCEL.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getDialog().dismiss();
        }
    });
}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    public void onFragmentInteraction(Uri uri);
}
}

这是BackgroundTask.java

public class BackgroundTask extends AsyncTask <String,CharacterDisplay,String> {

Context ctx;
CharacterAdapter characterAdapter;
Activity activity;
ListView listView;
BackgroundTask(Context ctx) {
    this.ctx = ctx;
    activity = (Activity) ctx;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String method = params[0];
    DatabaseOperations databaseOperations = new DatabaseOperations(ctx);

    if (method.equals("add_info")) {
        String name = params[1];
        SQLiteDatabase db = databaseOperations.getWritableDatabase();
        databaseOperations.putInfo(db, name);
        return "One row inserted";

    } else if (method.equals("get_info")) {
        listView = (ListView) activity.findViewById(R.id.char_list);
        SQLiteDatabase db = databaseOperations.getReadableDatabase();
        Cursor cursor = databaseOperations.getInfo(db);
        characterAdapter = new CharacterAdapter(ctx, R.layout.display_character_row);
        String name;
        while (cursor.moveToNext()) {
            name = cursor.getString(cursor.getColumnIndex(TableData.TableInfo.NAME));
            CharacterDisplay characterDisplay = new CharacterDisplay(name);
            publishProgress(characterDisplay);
        }
        return "get_info";
    }
    return null;
}

@Override
protected void onProgressUpdate(CharacterDisplay... values) {
    characterAdapter.add(values[0]);
}

@Override
protected void onPostExecute(String result) {
    if (result.equals("get_info")) {
        listView.setAdapter(characterAdapter);
    } else {
        Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
    }

}
}

这是CharacterDisplay.java

public class CharacterDisplay {

private String name;

public CharacterDisplay(String name) {
    this.setName(name);
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

这是CharacterAdapter.java

public class CharacterAdapter extends ArrayAdapter {
List list = new ArrayList();

public CharacterAdapter(Context context, int resource) {
    super(context, resource);
}

public void add(Character object) {
    list.add(object);
    super.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    CharacterHolder characterHolder;
    if(row == null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflater.inflate(R.layout.display_character_row, parent, false);
        characterHolder = new CharacterHolder();
        characterHolder.tx_name = (TextView) row.findViewById(R.id.char_name);
        row.setTag(characterHolder);
    } else {
        characterHolder = (CharacterHolder) row.getTag();
    }

    CharacterDisplay characterDisplay = (CharacterDisplay) getItem(position);
    characterHolder.tx_name.setText(characterDisplay.getName().toString());
    return row;
}

static class CharacterHolder {
    TextView tx_name;
}
}

1 个答案:

答案 0 :(得分:2)

Activity扩展了ContextThemeWrapper,因此导致播放异常,因为您的ContextThemeWrapper不是Activity的实例。它本身可能是另一个子类或ContextThemeWrapper

要在片段中获得Activity上下文,您可以使用getActivity()代替getView().getContext()