Jordi Jordi - 1 month ago 8
Android Question

onClickItem ListView custom ArrayAdapter Android Studio

Good afternoon,

I'm trying to touch a listItem from my listView and detect the touch (and get which listItem was touched) because after that I'm going to show a new Activity with the information of the post.

But I'm having problems because I don't know how to do it and also I tried a lot of different tutorials and codes and it's never working in my case, and that's why I'm going to post my full code because I'm out of options right now.

That's my code:

public class Blog extends AppCompatActivity {

// URL
String url = "https://www.mywebsite.com/";

// Key JSON
String keyJSON = "posts";

// Construct the data source
ArrayList<Blog> array = new ArrayList<Blog>();

// Background color action bar
String actionBarBackgroundColor = "#00b7bb";

// Title action bar
String actionBarTitle = "Blog";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blog);

// Action Bar
setupActionBar(actionBarBackgroundColor, actionBarTitle);

// Create the adapter to convert the array to views
final BlogAdapter adapter = new BlogAdapter(this, array);

// Load posts
initBlog(adapter);
}

// Action Bar
public void setupActionBar(String color, String titulo) {
// Create Action bar
ActionBar mActionBar = getSupportActionBar();

// Display title
getSupportActionBar().setTitle(titulo);

// Action bar background
mActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(color)));

// Show back arrow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}

// Get the information and display it in the ListView
private void initBlog(final BlogAdapter adapter) {

// List View
ListView listView = (ListView) findViewById(R.id.listv);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Log.d("Click","Click");
}
});

// Attach the adapter to a ListView
listView.setAdapter(adapter);

JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
try{
JSONObject jsonResponse = new JSONObject(response.toString());

//Show result
//Log.d("Result", jsonResponse.toString());

JSONArray jsonMainNode = jsonResponse.optJSONArray(keyJSON);

// Create products
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String titulo = jsonChildNode.getString("title");
String fecha = jsonChildNode.getString("fecha");
String imagen = jsonChildNode.getString("imagen");
String introtext = jsonChildNode.getString("introtext");
String fulltext = jsonChildNode.getString("fulltext");

Blog newPost = new Blog(titulo, fecha, imagen, introtext, fulltext);

adapter.add(newPost);
}
}
catch(JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
});

// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}

// Back arrow action
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MenuPrincipal.class);
startActivityForResult(myIntent, 0);
return true;
}
}


List View:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="0dp"
tools:context=".Blog.Blog"
>
<ListView
android:id="@+id/listv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10px">
</ListView>




List Item View:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:layout_gravity="center_vertical|center_horizontal">

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal"
android:gravity="right">

<TextView
android:id="@+id/blog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:gravity="left"
android:textColor="@color/colorBlack"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:padding="0px" />

<TextView
android:id="@+id/blog_fecha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginTop="0dp"
android:textColor="@color/colorBlack"
android:layout_marginBottom="0dp"
android:textStyle="italic" />

<ImageView
android:id="@+id/blog_image"
android:gravity="center_vertical|center_horizontal"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="0dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:layout_width="match_parent"
android:layout_height="350px" />

<TextView
android:id="@+id/blog_intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:textColor="@color/colorBlack"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
android:lineSpacingExtra="4sp" />

<Button
android:text="Ver post"
android:layout_width="wrap_content"
android:id="@+id/button"
android:textAppearance="@style/TextAppearance.AppCompat"
android:background="@color/color"
android:textColor="@color/blanco"
android:layout_height="wrap_content"
android:textSize="18sp"
android:paddingLeft="20px"
android:paddingRight="20px"
android:layout_marginTop="20px" />

</LinearLayout>

</LinearLayout>


BlogAdapter:

public class BlogAdapter extends ArrayAdapter<Blog> {

public BlogAdapter(Context context, ArrayList<Blog> blogs) {
super(context, 0, blogs);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

// Get the data item for this position
Blog blog = getItem(position);

// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.blog_item, parent, false);
}


TextView blogTitulo = (TextView) convertView.findViewById(R.id.blog_title);
TextView blogFecha = (TextView) convertView.findViewById(R.id.blog_fecha);
ImageView blogImagen = (ImageView) convertView.findViewById(R.id.blog_image);
TextView blogIntrotext = (TextView) convertView.findViewById(R.id.blog_intro);

blogTitulo.setText(blog.titulo);
blogFecha.setText(blog.fecha);
blogIntrotext.setText(blog.introtext);

Picasso.with(getContext()).load(blog.imagen).into(blogImagen);

return convertView;
}
}


Thanks in advance,

Regards

Answer

First of all make your class Parcelable or Serializable You need to add the ItemClickListener to your listview

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(Blog.this,ActivityToOpen.class);
                intent.putParcelable("BlogModeKey",array.get(position));
                startActivity(intent);
            }
        });

and read that object in ActivityToOpen.

Note or send each Blog model attribute one by one using putExtra

And don't use same name for model Class and Activity