xyz rety xyz rety - 5 months ago 13
Android Question

how to get item from ListView

m trying to type cast data but when i write "TextView clickData=(TextView) view" under onItemClick(...) logcat shows msg " java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView" the how can i get item from ListView which are clicked

this belongs from main activity:

public class ListViewForAllContact extends AppCompatActivity {
ListView myListView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.listviewforallcontact);



ContactDatabase onbOfContactDatabase=new ContactDatabase(getBaseContext());

Cursor mCursor= onbOfContactDatabase.phoneName();

String[] fromFileName=new String[]{ContactDatabase.NAME};
int[] toViewId=new int[]{R.id.textView5};
SimpleCursorAdapter simpleCursorAdapter;

simpleCursorAdapter=new SimpleCursorAdapter(this,R.layout.forreading,mCursor,fromFileName,toViewId,0);
myListView=(ListView)findViewById(R.id.listView);
myListView.setAdapter(simpleCursorAdapter);

myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

TextView clickData=(TextView) view;//becouse of this line error will come.

Toast.makeText(getBaseContext(), clickData.getText(), Toast.LENGTH_LONG).show();
}
});

}
}


this is xml with ListView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">


<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>


this is second xml file with TextView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView5"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"/>

</RelativeLayout>

Answer

Not sure if i understand your question correctly but i assume you would like to get your data as a String, rather than a TextView (the latter does not really make sense).

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Cursor cursor = (Cursor) simpleCursorAdapter.getItem(position);
    String data = cursor.getString(0); // replace 0 with the desired column index

    Toast.makeText(getBaseContext(), data, Toast.LENGTH_LONG).show();
}