2

I am not sure why I am getting this class cast exception. I have do [Project --> Clean] several times, still didnt work.

Someone please help me.

Thank you.

This is 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);
    }
}
 }

This is 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" />

This is 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" />

This is error log.

    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
4
  • post your fragment_schedule.xml layout Commented Mar 25, 2014 at 4:35
  • gosh... TextView is not ListView dude what are you trying to achieve? Commented Mar 25, 2014 at 4:35
  • @SimplePlan I have edited. Commented Mar 25, 2014 at 4:43
  • @SMR I trying to achieve the name sir Commented Mar 25, 2014 at 4:44

2 Answers 2

2

You go wrong over here

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

textViewMatrix is TextView id not a ListView id and also post your fragment_schedule.xml file

And change this

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

to

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

And used in your Fragment like

myListView = (ListView) rootView.findViewById(R.id.list);
Sign up to request clarification or add additional context in comments.

3 Comments

can u help me to review this code. I would like to use him code.
I have provide the link on previous comment. If u dont mind, can u have a look into it.
sir, did u get the answer ?
1

You have this

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

Probably id textViewMatrix is a TextView.

Confirmed by the fact you already initialize textview with the same id

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

You need to have a ListView in your fragment_schedule.xml

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

Then

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

Edit :

Change this

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

to

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

And then

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

2 Comments

@ultra_buckner you are welcome. Reading the stakctrace will give you a hint. Always look at the caused by part and next time you can fix the problem easily
Im sory master, noted :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.