-1

I am now trying a new activity, by an intent to show the image and name, But I don't know how to add the listener to the code,would someone help me how to put the listener in the code? I want click to the detailsActivity view,and I have the detailsActivity.xml in the below.

MainActivity.java

package net.simplifiedcoding.androidcustomgridview;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements     AdapterView.OnItemClickListener{

    //Web api url

   public static final String DATA_URL =     "http://www.simplifiedcodingreaders.16mb.com/superheroes.php";

    //Tag values to read from json
    public static final String TAG_IMAGE_URL = "image";
    public static final String TAG_NAME = "name";


    //GridView Object
    private GridView gridView;

    //ArrayList for Storing image urls and titles
    private ArrayList<String> images;
    private ArrayList<String> names;


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

        images = new ArrayList<>();
        names = new ArrayList<>();
        gridView = (GridView) findViewById(R.id.gridView);
        gridView.setOnItemClickListener(this);
        //Calling the getData method
        getData();
    }

    private void getData(){
        //Showing a progress dialog while our app fetches the data from url
        final ProgressDialog loading = ProgressDialog.show(this, "Please     wait...","Fetching data...",false,false);

        //Creating a json array request to get the json from our api
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                   public void onResponse(JSONArray response) {
                        //Dismissing the progressdialog on response
                        loading.dismiss();

                        //Displaying our grid
                        showGrid(response);
                   }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );

        //Creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //Adding our request to the queue
        requestQueue.add(jsonArrayRequest);
    }


    private void showGrid(JSONArray jsonArray){
        //Looping through all the elements of json array
        for(int i = 0; i<jsonArray.length(); i++){
            //Creating a json object of the current index
            JSONObject obj = null;
            try {
                //getting json object from current index
                obj = jsonArray.getJSONObject(i);

                //getting image url and title from json object
                images.add(obj.getString(TAG_IMAGE_URL));
                names.add(obj.getString(TAG_NAME));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //Creating GridViewAdapter Object
        GridViewAdapter gridViewAdapter = new GridViewAdapter(this,images,names);

        //Adding adapter to gridview
        gridView.setAdapter(gridViewAdapter);

    }
}

GridViewApapter.java

package net.simplifiedcoding.androidcustomgridview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

import java.util.ArrayList;

public class GridViewAdapter extends BaseAdapter {

    //Imageloader to load images
    private ImageLoader imageLoader;

    //Context
    private Context context;

    //Array List that would contain the urls and the titles for the images
    private ArrayList<String> images;
    private ArrayList<String> names;

    public GridViewAdapter (Context context, ArrayList<String> images, ArrayList<String> names){
        //Getting all the values
        this.context = context;
        this.images = images;
        this.names = names;
    }

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

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

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Creating a linear layout
        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        //NetworkImageView
        NetworkImageView networkImageView = new NetworkImageView(context);

        //Initializing ImageLoader
        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(images.get(position), ImageLoader.getImageListener(networkImageView, R.mipmap.ic_launcher,     android.R.drawable.ic_dialog_alert));

        //Setting the image url to load
        networkImageView.setImageUrl(images.get(position),imageLoader);

        //Creating a textview to show the title
        TextView textView = new TextView(context);
        textView.setText(names.get(position));

        //Scaling the imageview
        networkImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        networkImageView.setLayoutParams(new     GridView.LayoutParams(200,200));

        //Adding views to the layout
       linearLayout.addView(textView);
       linearLayout.addView(networkImageView);

        //Returnint the layout
        return linearLayout;
    }
}

My detailsActivity xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"         android:layout_width="match_parent"
    android:layout_height="wrap_parent"     android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.imageuploadsample.detailsActivity">


    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageViewFull"
        android:layout_alignParentTop="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/TextView" 
            android:text="text"

      />


</RelativeLayout>
Adarsh Yadav
  • 3,752
  • 3
  • 24
  • 46
bbbb
  • 45
  • 1
  • 1
  • 9

2 Answers2

0

All you need to add ItemClickListener on grid view by which you will able to get position of clicked item in grid view. Inside that you can open your Details Activity and pass your data using intent.

 gridview.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
    }
});}

You will find a good example here.

Adarsh Yadav
  • 3,752
  • 3
  • 24
  • 46
0

You need to pass image url and image name with the help of Intents to your Detail Activity on click event of your grid view something like this :-

gridView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Intent intent = new Intent(getBaseContext(),
                    DetailActivity.class);
            intent.putExtra("ImageName", names.get(arg2));
            intent.putExtra("ImageURL", images.get(arg2));
            startActivity(intent);

        }
    });

and your detail activity should look like this:-

public class DetailActivity extends Activity {

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

        Bundle extras = getIntent().getExtras();
        if (extras != null) {

            ((TextView) findViewById(R.id.TextView)).setText(extras
                    .getString("ImageName"));

            ImageLoader imageLoader = CustomVolleyRequestQueue
                    .getInstance(this).getImageLoader();

            // If you are using normal ImageView
            imageLoader.get(extras.getString("ImageURL"), new ImageListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // Log.e(TAG, "Image Load Error: " + error.getMessage());
                }

                @Override
                public void onResponse(ImageContainer response, boolean arg1) {
                    if (response.getBitmap() != null) {
                        // load image into imageview
                        ((ImageView) findViewById(R.id.imageViewFull))
                                .setImageBitmap(response.getBitmap());
                    }
                }
            });
        }

    }

}

I have tested your code apparently there is some problem with base url you are using I have enhanced it and updated it on GitHub you can find it here

https://github.com/hiteshsahu/Volley-Image-Loading-Sample

Since your URL is not correct I am using sample URL to display Images like this

enter image description here

and detail activity looks like this

enter image description here

I strongly recommend you to use fragment instead of activities. Hope it will help you

Community
  • 1
  • 1
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154