2

I am new in android. When I click on listview item then nothing happens. I checked my code 3 times but couldn't get the what is the problem. I want when an item is clicked the user name will show in a text view in next activity. I don't know what is the problem.

Here is my listview item code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="1dp">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollView">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="#ffffff">

    <ImageView
        android:layout_width="380dp"
        android:layout_height="200dp"
        android:id="@+id/row_postPic"
        android:background="#dcdcdc"
        android:minHeight="50dp"
        android:scaleType="centerCrop"
        android:src="@drawable/url"
        android:layout_below="@+id/row_date"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="name"
        android:id="@+id/row_name"
        android:textSize="18dp"
        android:layout_alignTop="@+id/row_userid"
        android:layout_alignRight="@+id/row_date"
        android:layout_alignEnd="@+id/row_date"
        android:layout_alignLeft="@+id/row_userid"
        android:layout_alignStart="@+id/row_userid" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="date"
        android:id="@+id/row_date"
        android:textSize="16dp"
        android:layout_alignBottom="@+id/imageToDownload2"
        android:layout_alignRight="@+id/row_tittle"
        android:layout_alignEnd="@+id/row_tittle"
        android:layout_marginTop="60dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="tittle"
        android:id="@+id/row_tittle"
        android:layout_below="@+id/row_postPic"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:textSize="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Category"
        android:id="@+id/row_cat"
        android:textSize="16dp"
        android:layout_above="@+id/row_postPic"
        android:layout_alignLeft="@+id/row_name"
        android:layout_alignStart="@+id/row_name" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="UserId"
        android:id="@+id/row_userid"
        android:textColor="#000000"
        android:textSize="18dp"
        android:layout_alignTop="@+id/imageToDownload2"
        android:layout_toRightOf="@+id/imageToDownload2"
        android:layout_toEndOf="@+id/imageToDownload2"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="PostId"
        android:id="@+id/row_postid"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:textColor="#000000"
        android:layout_marginTop="30dp" />

    <TextView
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:text="Like"
        android:id="@+id/row_like"
        android:gravity="center"
        android:layout_below="@+id/row_tittle"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp" />

</RelativeLayout>
</ScrollView>
</RelativeLayout>

and here is list adapter

public class PostAdapter extends BaseAdapter {
    Context context;
    ArrayList<Post> listData;

    public PostAdapter(Context context,ArrayList<Post> listData){
        this.context = context;
        this.listData = listData;
    }

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

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

    @Override
    public long getItemId(int position) {
        return position;
    }
    class ViewHolder {
        private TextView tvlike,tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
    }
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if(view == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.post_item,null);
            viewHolder = new ViewHolder();
            viewHolder.tvTittle = (TextView) view.findViewById(R.id.row_tittle);
            viewHolder.tvPostId = (TextView) view.findViewById(R.id.row_postid);
            viewHolder.tvUseId = (TextView) view.findViewById(R.id.row_userid);
            viewHolder.tvName = (TextView) view.findViewById(R.id.row_name);
            viewHolder.tvCat = (TextView) view.findViewById(R.id.row_cat);
            viewHolder.tvlike = (TextView) view.findViewById(R.id.row_like);
            viewHolder.tvDate = (TextView) view.findViewById(R.id.row_date);

            view.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) view.getTag();
        }
        Post post = listData.get(position);
        String rpostid = post.getPost_id();
        String ruserid = post.getUser_id();
        String rname = post.getUser_name();
        String rcat = post.getPost_cat();
        String rlike = post.getLikes();
        String rdate = post.getPost_time();
        String rtittle = post.getPost_title();
        viewHolder.tvPostId.setText(rpostid);
        viewHolder.tvUseId.setText(ruserid);
        viewHolder.tvName.setText(rname);
        viewHolder.tvCat.setText("Category "+rcat);
        viewHolder.tvlike.setText("Toatal Likes "+rlike);
        viewHolder.tvDate.setText(rdate);
        viewHolder.tvTittle.setText(rtittle);

        return view;
    }
}

here is the home activity

public class Home extends Fragment {

    ListView listView;
    PostAdapter adapter;
    TextView userId;
    ArrayList<Post> postArrayList;
    private SwipeRefreshLayout swipeRefreshLayout;
    DBHandler handler;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_post, container, false);
        listView = (ListView)  view.findViewById(R.id.listview);

        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            new DataFetcherTask().execute();
        }else{
            Toast.makeText(getActivity(), "Internet Error", Toast.LENGTH_LONG).show();
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

                Toast.makeText(getActivity(), "Item clicked : " + position, Toast.LENGTH_LONG).show();
                userId = (TextView)view.findViewById(R.id.row_userid);
                Intent i = new Intent(getActivity(), PostView.class);
                i.putExtra("userid", userId.getText().toString());
                startActivity(i);
            }
        });
        return view;

    }

    private class DataFetcherTask extends AsyncTask<Void, Void, Void> {

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

        @Override
        protected Void doInBackground(Void... args) {
            String serverData = null;// String object to store fetched data from server
            // Http Request Code start
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://xyz.lt/json.php");
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                serverData = EntityUtils.toString(httpEntity);
                Log.d("response", serverData);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Http Request Code end
            // Json Parsing Code Start
            try {
                postArrayList = new ArrayList<Post>();
                JSONObject jsonObject = new JSONObject(serverData);
                JSONArray jsonArray = jsonObject.getJSONArray("post");
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
                    String post_id = jsonObjectPOST.getString("post_id");
                    String user_id = jsonObjectPOST.getString("user_id");
                    String user_name = jsonObjectPOST.getString("user_name");
                    String post_title = jsonObjectPOST.getString("post_title");
                    String likes = jsonObjectPOST.getString("likes");
                    String post_cat = jsonObjectPOST.getString("post_cat");
                    String post_time = jsonObjectPOST.getString("post_time");
                    Post post = new Post();
                    post.setPost_id(post_id);
                    post.setUser_id(user_id);
                    post.setUser_name(user_name);
                    post.setPost_title(post_title);
                    post.setLikes(likes);
                    post.setPost_cat(post_cat);
                    post.setPost_time(post_time);
                    handler.addPost(post);// Inserting into DB
                }
            } catch (JSONException e) {
                e.printStackTrace();

            }
            //Json Parsing code end
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ArrayList<Post> postList = handler.getAllPost();
            adapter = new PostAdapter(getActivity(), postList);
            listView.setAdapter(adapter);
        }
    }



    @Override
    public void onResume() {
        super.onResume();
        new DataFetcherTask().execute();
        ArrayList<Post> postList = handler.getAllPost();
        adapter = new PostAdapter(getActivity(), postList);
        listView.setAdapter(adapter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new DBHandler(getActivity());
        new DataFetcherTask().execute();
    }
}

I want when item will click then new activity will open here is the new activity

public class PostView extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_view);
        TextView textView = (TextView) findViewById(R.id.textView3);

        Intent intent = getIntent();
        if (intent!=null) {
            String stringData= intent.getStringExtra("userid");
            textView.setText(stringData);
        }
    }
}

In this project when some click on the listview item then it pass the vaue of textview of the user name to new intent but as list item clicklistner is not working so I am unable to do that.

Answer is : Do not use Scroll View in Listview Custom item.

3 Answers3

1

this might sound unrelevant, but will u try your code by removing the ScrollView from the list item layout? because the click event is taken by the scrollView and hence there seems to be problem with your onItemCLickListener

inkedTechie
  • 684
  • 5
  • 13
  • Thanks its working now, means problem is Scroll view therefore my code was not worked, Thanks again. :) – Honey Kamboj Jan 30 '16 at 07:01
  • thanks for help but i need one more help when i clicked list item then it does not open new intent its just showing A Toast "You Clicked" – Honey Kamboj Jan 30 '16 at 07:32
  • there should be problem with context, try `getContext()` or `getApplicationContexr()` or `getActivity().getApplicationContext()` etc – inkedTechie Jan 30 '16 at 07:38
  • '@Override public void onItemClick(AdapterView> parent, View view, int position, long id) { Toast.makeText(getActivity(), "Item clicked : " + position, Toast.LENGTH_LONG).show(); userid= (TextView)view.findViewById(R.id.row_userid); Intent i = new Intent(getContext(), PostView.class); i.putExtra("user_id", postArrayList.get(position).getUser_id()); startActivity(i); }' what change i need in this code – Honey Kamboj Jan 30 '16 at 07:43
  • can you post your logcat? – inkedTechie Jan 30 '16 at 07:53
  • that problem is solved but app crash when i click on list item it is giving null pointer exception on **i.putExtra("user_id", postArrayList.get(position).getUser_id());** – Honey Kamboj Jan 30 '16 at 07:59
0

As I Know you already apply onItemClick on your listview thats why it is not working. both onitemclick and onClick doesn't work together better option use onClick in place of onItemClick.

Another thing this is not to good do other thing in onCreateView as it is only for View Inflate. Remove this lines of code from onCreateView to onActivityCreated

 listView = (ListView)  view.findViewById(R.id.listview);

        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            new DataFetcherTask().execute();
        }else{
            Toast.makeText(getActivity(), "Internet Error", Toast.LENGTH_LONG).show();
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

                Toast.makeText(getActivity(), "Item clicked : " + position, Toast.LENGTH_LONG).show();
                userId = (TextView)view.findViewById(R.id.row_userid);
                Intent i = new Intent(getActivity(), PostView.class);
                i.putExtra("userid", userId.getText().toString());
                startActivity(i);
            }
        });
Anjali Tripathi
  • 1,477
  • 9
  • 28
0
try adding 

android:descendantFocusability="blocksDescendants"
in your main layout

eg.`
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:paddingBottom="1dp">`

and set OnItemClickListener to your listView