-1

I have successed in passing strings, but i have also int, double, Array and Image and i don't know how to pass them into another activity. I have tried to pass all of this from CustomAdapter. If anyone have an easier way for doing this, let me know. Any help would be appricieated.

This is the code where is JSON:

    public class ListaPreporuka extends AppCompatActivity {
    // Log tag
    private static final String TAG = ListaPreporuka.class.getSimpleName();

    // Movies json url
    private static final String url = "https://api.myjson.com/bins/5679m";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        getSupportActionBar().setTitle("Preporuke");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Učitavanje...");
        pDialog.show();

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("title"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                movie.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);

                                // adding movie to movies array
                                movieList.add(movie);


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }                        

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }
                });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        if (item.getItemId() == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

}

This is the code of Custom List Adapter:

    import com.dusandimitrijevic.app.AppController;
import com.dusandimitrijevic.hororfilmovi_analizeiocene.MoviesSingleActivity;
import com.dusandimitrijevic.hororfilmovi_analizeiocene.R;
import com.dusandimitrijevic.model.Movie;




import java.util.List;




import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;





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

public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }

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

    @Override
    public Object getItem(int location) {
        return movieItems.get(location);
    }

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

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

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.lista_preporuka_red, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView rating = (TextView) convertView.findViewById(R.id.rating);
        TextView genre = (TextView) convertView.findViewById(R.id.genre);
        TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

        // getting movie data for the row
        Movie m = movieItems.get(position);

        // thumbnail image
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

        // title
        title.setText(m.getTitle());

        // rating
        rating.setText("Ocena: " + String.valueOf(m.getRating()));

        // genre
        String genreStr = "";
        for (String str : m.getGenre()) {
            genreStr += str + ", ";
        }
        genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
        year.setText(String.valueOf(m.getYear()));

        convertView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, MoviesSingleActivity.class);

                intent.putExtra("Movie", movieItems.get(position).getId());
                activity.startActivity(intent);

            }
        });

        return convertView;
    }

}

and this is the code from Activity where i'm passing JSON:

    public class MoviesSingleActivity extends AppCompatActivity {

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

        Intent i = getIntent();

        i.getExtras().getString("Movie");



    }

}

EDIT

Movie class:

    public class Movie {
private String id;
private String title, thumbnailUrl;
private int year;
private double rating;
private ArrayList<String> genre;

public Movie() {
}

public Movie(String name, String thumbnailUrl, int year, double rating,
             ArrayList<String> genre) {
    this.title = name;
    this.thumbnailUrl = thumbnailUrl;
    this.year = year;
    this.rating = rating;
    this.genre = genre;
}

public Movie(String id, String name, String thumbnailUrl, int year, double rating,
             ArrayList<String> genre) {
    this.id = id;
    this.title = name;
    this.thumbnailUrl = thumbnailUrl;
    this.year = year;
    this.rating = rating;
    this.genre = genre;
}

public String getTitle() {
    return title;
}

public void setTitle(String name) {
    this.title = name;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public void setThumbnailUrl(String thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
}

public int getYear() {
    return year;
}

public void setYear(int year) {
    this.year = year;
}

public double getRating() {
    return rating;
}

public void setRating(double rating) {
    this.rating = rating;
}

public ArrayList<String> getGenre() {
    return genre;
}

public void setGenre(ArrayList<String> genre) {
    this.genre = genre;
}

public String getId(){
    return id;
}

public void setId(String id){
    this.id = id;
}

}
Dusan Dimitrijevic
  • 3,169
  • 6
  • 22
  • 46
  • Have you thought about using bundle extras? [http://stackoverflow.com/questions/4233873/how-to-get-extra-data-from-intent-in-android][1] [1]: http://stackoverflow.com/questions/4233873/how-to-get-extra-data-from-intent-in-android – booky99 Jul 25 '15 at 21:36
  • I will try, but i don't know how to pass for example Image, ArrayList and double. – Dusan Dimitrijevic Jul 25 '15 at 21:44
  • If you want to pass custom objects you can create one class with singleton to hold the reference to these instances, using singleton will give you access to same instance of that class and you will get same objects in your new activity. refer this for similar issue http://stackoverflow.com/questions/15164144/right-way-way-to-implement-singleton-in-android-for-data-sharing-between-activit – RamIndani Jul 25 '15 at 21:44
  • @RamIndani If you can see i'm trying to pass instances into MoviesSingleActivity from CustomListAdapter in onClickListener method, but i have managed only to pass String. I have edited my question and you can see my Movie class. – Dusan Dimitrijevic Jul 25 '15 at 22:20
  • @RamIndani But what to do if the same activity is started with other parameters in the same task? It will rewrite data of activity that was called first and is located below in the back stack. – Nolan Jul 25 '15 at 22:22
  • @Nolane I believe it will be very requirement specific then one can use Collection to hold object of class but of course in that case you can not go for singleton. – RamIndani Jul 25 '15 at 22:34
  • @RamIndani Glad to see that I clearly got this method. – Nolan Jul 25 '15 at 22:38

2 Answers2

1

I have created some code to help you, I have modified your Movie class to add id to it - to uniquely identify it. I hope you will have id or generate unique id if possible.

import java.util.ArrayList;
public class Movie {
private String id;
private String title, thumbnailUrl;
private int year;
private double rating;
private ArrayList<String> genre;

public Movie() {
}

public Movie(String name, String thumbnailUrl, int year, double rating,
             ArrayList<String> genre) {
    this.title = name;
    this.thumbnailUrl = thumbnailUrl;
    this.year = year;
    this.rating = rating;
    this.genre = genre;
}

public Movie(String id, String name, String thumbnailUrl, int year, double rating,
             ArrayList<String> genre) {
    this.id = id;
    this.title = name;
    this.thumbnailUrl = thumbnailUrl;
    this.year = year;
    this.rating = rating;
    this.genre = genre;
}

public String getTitle() {
    return title;
}

public void setTitle(String name) {
    this.title = name;
}

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public void setThumbnailUrl(String thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
}

public int getYear() {
    return year;
}

public void setYear(int year) {
    this.year = year;
}

public double getRating() {
    return rating;
}

public void setRating(double rating) {
    this.rating = rating;
}

public ArrayList<String> getGenre() {
    return genre;
}

public void setGenre(ArrayList<String> genre) {
    this.genre = genre;
}

public String getId(){
    return id;
}

public void setId(String id){
    this.id = id;
}

}

Once you have this class I have created a class to hold data for your movies.

import java.util.HashMap;


public class MovieModelData {

private HashMap<String, Movie> movieData = new HashMap<String,Movie>();

public void setMovieData(Movie movie){
    movieData.put(movie.getId(), movie);

}

public Movie getMovie(String id){
    return movieData.get(id);
}


}

now just pass your id as string from custom adapter, save your movie object to above hash map in MovieModelData and then get it back in any activity that you want in order of O(1).

I hope this will help

RamIndani
  • 678
  • 8
  • 12
  • Okay, is this okay if i declare in onClickListener method.. i.putExtra("Movie", movieItems.get(position).getId()); – Dusan Dimitrijevic Jul 25 '15 at 23:07
  • And this is what i have add in Activity receiver.. i.getExtras().getString("Movie"); – Dusan Dimitrijevic Jul 25 '15 at 23:07
  • yes this should work and once you got that id you can use it to retrieve your Movie object from above collection – RamIndani Jul 26 '15 at 03:23
  • I have done everything you suggested to me, but now i'm getting an layout of textViews and one image with default ic_launcher i set. Do i need to set result for textView or image? – Dusan Dimitrijevic Jul 26 '15 at 13:15
  • I think you are missing something to generate list view, you will have to set your adapter to list view follow this blog http://theopentutorials.com/tutorials/android/listview/android-custom-listview-with-image-and-text-using-baseadapter/ – RamIndani Jul 26 '15 at 16:44
  • I have edited my question and insert changes from activities i have made. I can't see passed data in activity where is supposed to be passed and i can see in activity where should be listView. As i said i need to pass data from listView on ItemClick into another activity. And in this case it's JSON. – Dusan Dimitrijevic Jul 26 '15 at 19:59
  • Then just pass the JSON as string and retrieve it or use above approach to access it again instead of Movie object pass String as data and access it. – RamIndani Jul 26 '15 at 20:21
0

I recomend store data in class and pass via EventBus https://github.com/greenrobot/EventBus/blob/master/HOWTO.md Or you can use putExtra

Darius Radius
  • 169
  • 3
  • 14