ClassCastException: android.widget.TextView不能强制转换为android.wi



我不知道为什么我得到这个类强制转换异常。我已经做了几次[Project -> Clean],但仍然没有成功。

谁来帮帮我。

谢谢。

这是ScheduleFragment.java

 public class ScheduleFragment extends Fragment {
    public static final String PREFS_NAME="PreferencesValue";
    public ProgressDialog pDialog;
    private ListView myListView;
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    ArrayList<HashMap<String, String>> subjectList;     
    // url to get all subjects list
    private static String url_all_subjects = "http://192.168.1.12/android_project/get_subjects.php";
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_STUDENT = "student";
    private static final String TAG_MATRIX_ID = "matrix_id";
    private static final String TAG_NAME = "name";
    // subject JSONArray
    JSONArray student = null;

public ScheduleFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.fragment_schedule, container, false);
    //Bring the value from login page
   TextView tvmatrix = (TextView)rootView.findViewById(R.id.textViewMatrix);        
   SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);        
   tvmatrix.setText(settings.getString("matrix", "A13123"));
    //-------------------------------------------------------------------------

 //------------------------------------CREATING A LISTVIEW-----------------------
    // Loading subject in Background Thread
    new LoadAllSubject().execute();
 // Hashmap for ListView
    subjectList = new ArrayList<HashMap<String, String>>();
    myListView = (ListView) rootView.findViewById(R.id.textViewMatrix);
    // on selecting single subject
    myListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String matrix_id = ((TextView) view.findViewById(R.id.textViewMatrix)).getText()
                    .toString();
            // Starting new intent
            Intent in = new Intent(getActivity().getApplicationContext(),
                    SingleSubject.class);
            // sending matrix id to next activity
            in.putExtra(TAG_MATRIX_ID, matrix_id);
            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });
    return rootView;
}
/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllSubject extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = ProgressDialog.show(ScheduleFragment.this.getActivity(), "Progress", "Loading subjects. Please wait...", false);
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
    }
    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_subjects, "GET", params);
        // Check your log cat for JSON reponse
        Log.d("All Subjects: ", json.toString());
        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // subject found
                // Getting Array of Subject
                student = json.getJSONArray(TAG_STUDENT);
                // looping through All Subjects
                for (int i = 0; i < student.length(); i++) {
                    JSONObject c = student.getJSONObject(i);
                    // Storing each json item in variable
                    String matrix_id = c.getString(TAG_MATRIX_ID);
                    String name = c.getString(TAG_NAME);
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    // adding each child node to HashMap key => value
                    map.put(TAG_MATRIX_ID, matrix_id);
                    map.put(TAG_NAME, name);
                    // adding HashList to ArrayList
                    subjectList.add(map);
                }
            } else {
                // no subjects found
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        super.onPostExecute(file_url);
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread           
                 ListAdapter adapter = new SimpleAdapter(
                           getActivity(), subjectList,
                        R.layout.all_subject, new String[] { TAG_MATRIX_ID,
                                TAG_NAME},
                        new int[] { R.id.matrix_id, R.id.name });
                // updating listview
                myListView.setAdapter(adapter);
    }
}
 }

这是all_subject.xml

     <TextView
    android:id="@+id/matrix_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="gone" />

<!-- Name Label -->
<TextView
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="6dip"
    android:paddingLeft="6dip"
    android:textSize="17dip"
    android:textStyle="bold" />

这是fragment_schedule.xml

        <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
<TextView
    android:id="@+id/textViewMatrix"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="66dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

这是错误日志。

    03-25 12:14:06.177: W/dalvikvm(1129): threadid=1: thread exiting with uncaught   exception (group=0x40d09930)
      03-25 12:14:06.271: E/AndroidRuntime(1129): FATAL EXCEPTION: main
      03-25 12:14:06.271: E/AndroidRuntime(1129): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ultra.esc/com.ultra.esc.HomeActivity}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
      03-25 12:14:06.271: E/AndroidRuntime(1129):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at android.os.Handler.dispatchMessage(Handler.java:99)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at android.os.Looper.loop(Looper.java:137)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at android.app.ActivityThread.main(ActivityThread.java:5039)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at java.lang.reflect.Method.invokeNative(Native Method)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at java.lang.reflect.Method.invoke(Method.java:511)
     03-25 12:14:06.271: E/AndroidRuntime(1129):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at dalvik.system.NativeStart.main(Native Method)
    03-25 12:14:06.271: E/AndroidRuntime(1129): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at com.ultra.esc.ScheduleFragment.onCreateView(ScheduleFragment.java:88)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at android.app.Fragment.performCreateView(Fragment.java:1695)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at android.app.BackStackRecord.run(BackStackRecord.java:682)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
    03-25 12:14:06.271: E/AndroidRuntime(1129):     at android.app.Activity.performStart(Activity.java:5113)
   03-25 12:14:06.271: E/AndroidRuntime(1129):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
   03-25 12:14:06.271: E/AndroidRuntime(1129):  ... 11 more

你这里出错了

 myListView = (ListView) rootView.findViewById(R.id.textViewMatrix);

textViewMatrix是TextView id不是ListView id,也张贴你的fragment_schedule.xml文件

改变这个

<ListView
  android:id="@android:id/list" ...../>

<ListView
    android:id="@+id/list"
    .......
    ......../>

和使用在你的片段,如

myListView = (ListView) rootView.findViewById(R.id.list);

你有这个

 myListView = (ListView) rootView.findViewById(R.id.textViewMatrix);

可能id textViewMatrixTextView

确认你已经用相同的id初始化textview

TextView tvmatrix = (TextView)rootView.findViewById(R.id.textViewMatrix); 
// see the id textViewMatrix its a textview and you use the same to initialize listview

你需要在你的fragment_schedule.xml中有一个ListView

<ListView
android:id="@+id/listView1
然后

myListView = (ListView) rootView.findViewById(R.id.listView1);
编辑:

改变这

<ListView
android:id="@android:id/list" 
//  you would use this id when you extend ListFragment and inflate a custom layout fro the fragment.

<ListView
android:id="@+id/list"

myListView = (ListView) rootView.findViewById(R.id.list);

最新更新