getActivity() inside viewholder - java

I have created a Recyclerview, with itemobjects, Adapter, viewholder and activity.
The Recyclerview works fine.
My problem is when an item is clicked from Recyclerview, I want to direct the user to TicketDetails activity.
I have the code to get the clicked item and its position in the view holder, but when I try to create a new intent to new activity like this inside view holder
startActivity(new Intent(getActivity(), TicketDetails.class));
I am unable to resolve getActivity()
ViewHolder
public class TicketsRecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView priority;
public TextView sts_open;
public TextView sts_overdue;
public TextView tkt_from;
public TextView tkt_subject;
public TextView tkt_assignedto;
public TextView tkt_created_date;
public TextView txt_ticket_id;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
public TicketsRecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
priority = (ImageView) itemView.findViewById(R.id.priority_status_icon);
sts_open= (TextView) itemView.findViewById(R.id.tv_Tk_opn_status);
sts_overdue = (TextView) itemView.findViewById(R.id.tv_Tk_overdue);
tkt_from = (TextView) itemView.findViewById(R.id.tv_Tk_from);
tkt_subject = (TextView) itemView.findViewById(R.id.tv_Tk_subject);
tkt_assignedto = (TextView) itemView.findViewById(R.id.tv_Tk_Assignedto);
tkt_created_date = (TextView) itemView.findViewById(R.id.tv_Tk_Created_date);
txt_ticket_id = (TextView) itemView.findViewById(R.id.tv_Tk_TicketID);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
String ticket_id = txt_ticket_id.getText().toString();
Log.d("ZD-clicked : ", "Position => "+String.valueOf(position)+", Ticket Id => "+ticket_id);
startActivity(new Intent(getActivity(), TicketDetails.class));
// if (selectedItems.get(getAdapterPosition(), false)) {
// selectedItems.delete(getAdapterPosition());
// view.setSelected(false);
// }
// else {
// selectedItems.put(getAdapterPosition(), true);
// view.setSelected(true);
// }
}
}
Adapter
public class TicketsRecyclerViewAdapter extends RecyclerView.Adapter<TicketsRecyclerViewHolders>{
public List<TicketsItemObject> TicketsItemList;
private Context context;
public TicketsRecyclerViewAdapter(Context context, List<TicketsItemObject> itemList) {
this.TicketsItemList = itemList;
this.context = context;
}
#Override
public TicketsRecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_tickets_row, null);
TicketsRecyclerViewHolders rcv = new TicketsRecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(TicketsRecyclerViewHolders holder, int position) {
holder.priority.setImageResource(TicketsItemList.get(position).getStatus_priority());
holder.sts_open.setText(TicketsItemList.get(position).getStatus_open());
holder.sts_overdue.setText(TicketsItemList.get(position).getStatus_overdue());
holder.tkt_from.setText(TicketsItemList.get(position).getTicket_from());
holder.tkt_subject.setText(TicketsItemList.get(position).getTicket_subject());
holder.tkt_assignedto.setText(TicketsItemList.get(position).getTicket_assignedto());
holder.tkt_created_date.setText(TicketsItemList.get(position).getTicket_created_date());
holder.txt_ticket_id.setText(TicketsItemList.get(position).getTicket_id());
}
#Override
public int getItemCount() {
return this.TicketsItemList.size();
}
}
Item Object
public class TicketsItemObject {
private int status_priority;
private String status_open;
private String status_overdue;
private String ticket_from;
private String ticket_subject;
private String ticket_assignedto;
private String ticket_created_date;
private String ticket_id;
public TicketsItemObject(int status_priority, String status_open, String status_overdue, String ticket_from, String ticket_subject, String ticket_assignedto, String ticket_created_date, String ticket_id) {
this.status_priority = status_priority;
this.status_open = status_open;
this.status_overdue = status_overdue;
this.ticket_from = ticket_from;
this.ticket_subject = ticket_subject;
this.ticket_assignedto = ticket_assignedto;
this.ticket_created_date = ticket_created_date;
this.ticket_id =ticket_id;
}
public int getStatus_priority() {
return status_priority;
}
public String getStatus_open() {
return status_open;
}
public String getStatus_overdue() {
return status_overdue;
}
public String getTicket_from() {
return ticket_from;
}
public String getTicket_subject() {
return ticket_subject;
}
public String getTicket_assignedto() {
return ticket_assignedto;
}
public String getTicket_created_date(){return ticket_created_date;}
public String getTicket_id(){return ticket_id;}
}
Activity
public class Dashboard extends AppCompatActivity {
private Toolbar toolbar;
public DrawerLayout drawerLayout;
public ListView drawerList;
private navigationDrawerFragment drawerFragment;
private CompanyProfileAdapter mAdapter;
ApplicationEnvironmentURL applicationEnvironment;
ProgressDialog pDialog;
Context context;
String BASEURL;
String FilteredData;
String allAgents;
List<TicketsItemObject> items = new ArrayList<TicketsItemObject>();
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private TicketsRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Dashboard");
setContentView(R.layout.activity_dashboard);
applicationEnvironment = new ApplicationEnvironmentURL(this.context);
context = this.getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.app_bar_dashboard);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (navigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setup(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
String islogged = prefs.getString("islogged", "Not defined");
String userid = prefs.getString("userid", "Not defined");
String profileToken = prefs.getString("profileToken", "Not defined");
String companyId = prefs.getString("companyId", "Not defined");
String companyName = prefs.getString("companyName", "Not defined");
String ProfileId = prefs.getString("ProfileId", "Not defined");
Log.d("islogged : ", islogged);
Log.d("userid : ", userid);
Log.d("profileToken : ", profileToken);
Log.d("companyId : ", companyId);
Log.d("companyName : ", companyName);
Log.d("ProfileId : ", ProfileId);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view_tickets);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
layoutManager = new LinearLayoutManager(Dashboard.this);
recyclerView.setLayoutManager(layoutManager);
getTickets(ProfileId, companyId, profileToken);
View newTicket = findViewById(R.id.newtic);
newTicket.setOnClickListener(onClickListener);
}
/* Multiple Button on click event handle */
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.newtic:
// Create a login URl, before starting anything
if(isNetworkAvailable()){
Intent intentTicket = new Intent(Dashboard.this, NewTicket.class);
startActivity(intentTicket);
} else {showErrorMessage("Please check your internet connection.", "No Connectivity!"); }
break;
}
}
};
private void getTickets(String profileId, String companyId, String profileToken){
if(isNetworkAvailable()) {
try {
setFilteredDataURL(companyId);
FilteredData = new getFilteredData().execute(profileToken).get();
Log.d("Full Filtered Data", FilteredData);
setTicketsURL(profileId, companyId);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new getNewTickets().execute(profileToken);
}else{ showErrorMessage("Please check your internet connection.", "No Connectivity!"); }
}
................
.............
..More...........

getActivity() only works in fragments. A view will have activity Context. So get Context from the view.
Change
startActivity(new Intent(getActivity(), TicketDetails.class));
to
Context context = view.getContext();
context.startActivity(new Intent(context, TicketDetails.class));

You can try
holder.itemView.context as Activity

Interface approach
You can also solve this problem using interface
1) Create an interface
public interface ItemclickListerner{
public void startActivity(int index);
}
2) Implement the interface in the Activity
public class YourActivity extends AppcompatActivity implements ItemclickListerner{
protected void onCreate(Bundle bundle)
.......
#override
public void startActivity(int index)
{
Intent i = new Intent(YourActivity.this, SecondActivity.class)
startActivity(i);
}
}
3) Use the ItemclickListerner in the holder
public class TicketsRecyclerViewHolders extends .... {
private ItemclickListerner listener;
// Typecast the listener
public TicketsRecyclerViewHolders(Context context)
{
listener = (ItemclickListerner)context;
}
// Call the listener method
#Override
public void onBindViewHolder(TicketsRecyclerViewHolders holder, int position{
listener.startActivity(position)
}
}

You can use an interface to pass the itemclick from Adapter to your activity or fragment. Inside the callback you can call the Intent.
See this thread for more info. See #Jacob Tabaks answer.
EDIT:
See #AkshayBhat's answer for an alternative method.

You have context in your constructor.So you can use context to go to an Activity from adapter.
Intent goTicket = new Intent(context, MyDetailActivity.class);
goTicket.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Pass fragment to the Adaptar constructor.
Check if fragment is currently added to its activity and then launch particular activity:
if (fragment.isAdded())
fragment.startActivity(intent)

Related

How to transfer string from TextView to main activity with onClick listener

I want to create an onclick listener that reads the String from one TextView and then I somehow pass that string onto the main activity in order to open a third activity
So my main activity looks like this
public class AdvancedResults extends AppCompatActivity {
private RecyclerView mRecyclerView;
private AdvancedAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private ArrayList<String> saved_recipes_with_ingredients = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_results);
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test1", "test2");
advancedList.add(new AdvancedItem(R.drawable.ic_android, "test3", "test4");
mRecyclerView = findViewById(R.id.recyclerView1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new AdvancedAdapter(advancedList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// I want to open a new activity and append the string from the TextView here (maybe with get/set)
}
});
}
And my recycler adapter looks like this
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageViewADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
//how do I get the string from the TextView and pass it onto the main class?
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList) {
mAdvancedList = advancedList;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
i'm just not sure how im supposed to do that and what method to use.
So if you want the text from the text view you do:
String text = textViewId.getText();
But in your case you want to add the text for each one of the views on the list
So on the adapter how make a on click listener:
if (listener != null) {
int position = getAdapterPosition();
String text = mTextView1.getText();
Intent i = new Intent(getApplicationContext(), YourActitivity.class);
i.putExtra("nameYouWant", text)
startActivity(i);
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
Now on your activity :
String text = intent.getStringExtra("nameYouWant");
You can use interface to pass the second String param. So just add one String param like this -
public interface OnItemClickListener {
void onItemClick(int position, String text);
}
And in adapter pass the string on click of the item along with the position
listener.onItemClick(position, mTextView1.getText().toString());
And in the activity, you will receive the String text, from there you can pass it to ThirdActivity via bundle.
mAdapter.setOnItemClickListener(new AdvancedAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position, String textData) {
Intent i = new Intent(this, ThirdActivity.class);
i.putExtra("TEXT_KEY", textData);
}
});
Hope it will help!!

how to set a path param using retrofit

how to get ID position in call retrofit
GET https://api.themoviedb.org/3/movie/{movie_id}/credits?api_key=<>
i need to get position id send to server in loadCast function
and in MovieService that's retrofit call i need send postion id befor credits
i don't know how to do that if any one can help me thanks so much for that <3
//this my call retrofit server
public interface MovieService {
#GET("popular?" + Common.API_KEY + "&language=en-US")
Call<MoviesList> getPopular(#Query("api_key") String api_key);
#GET( ListMovieAdapter.SELECTED_MOVIE +"/credits?" + Common.API_KEY +
"&language=en-US")
Call<MovieCast> getCast(
#Query("api_key") String api_key);
----------------------------------------------------------------
package com.example.android.movie;
/**
* Created by yuyu on 12-Nov-18.
*/
public class MovieDetails extends YouTubeBaseActivity {
Result selectedMovie;
private ArrayList<Cast> cast;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView mRecyclerView;
private CastMovieAdapter castMovieAdapter;
private TextView name;
private ImageView imageMovie;
private TextView date;
private TextView rating;
private ArrayList<Result> results;
MovieService mService;
private static final String YT_API_KEY = "###";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_details);
selectedMovie =
getIntent().getParcelableExtra(ListMovieAdapter.SELECTED_MOVIE);
mRecyclerView = (RecyclerView) findViewById(R.id.cast_recycler);
mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
cast = new ArrayList<>();
castMovieAdapter = new CastMovieAdapter(cast, MovieDetails.this);
mRecyclerView.setAdapter(castMovieAdapter);
results = new ArrayList<>();
mService = Common.getMovieService();
loadTriler();
loadMovies();
loadCast();
}
this function to load movie
private void loadMovies() {
mService.getPopular(Common.API_KEY).enqueue(new Callback<MoviesList>()
{
#Override
public void onResponse(Call<MoviesList> call, Response<MoviesList>
response) {
results.clear();
results.addAll(response.body().getResults());
name = (TextView) findViewById(R.id.name_movie);
rating = (TextView) findViewById(R.id.rating);
date = (TextView) findViewById(R.id.date_det);
imageMovie = (ImageView) findViewById(R.id.imageView);
date.setText(selectedMovie.getReleaseDate());
name.setText(selectedMovie.getTitle());
rating.setText(String.valueOf(selectedMovie.getVoteAverage()));
final String image = Common.IMAGE_LOAD +
selectedMovie.getPosterPath();
Picasso.with(MovieDetails.this)
.load(image)
.into(imageMovie);
}
#Override
public void onFailure(Call<MoviesList> call, Throwable t) {
Log.d("===LoadMovies", "onResponse: " + t);
}
});
}
//i have proplem here in send ID postion
private void loadCast() {
mService.getCast(
ListMovieAdapter.SELECTED_MOVIE+Common.API_KEY).enqueue(new
Callback<MovieCast>() {
#Override
public void onResponse(Call<MovieCast> call, final
Response<MovieCast> response) {
cast.clear();
cast.addAll(response.body().getCast());
mRecyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onFailure(Call<MovieCast> call, Throwable t) {
}
});
}
}
package com.example.android.movie.Adapter;
/**
* Created by yuyu on 11-Nov-18.
*/
public class ListMovieAdapter extends
RecyclerView.Adapter<ListMovieAdapter.MyViewHolder> {
private ArrayList<Result> mMovies;
private Context context;
public static final String SELECTED_MOVIE = "selected_movie";
private int lastPosition = -1;
public ListMovieAdapter(ArrayList<Result> mMovies, Context context) {
this.mMovies = mMovies;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_views, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//Animation Scroll
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.down_from_top);
holder.itemView.startAnimation(animation);
lastPosition = position;
holder.nameMovie.setText(mMovies.get(position).getTitle());
final String image = Common.IMAGE_LOAD +
mMovies.get(position).getPosterPath();
Picasso.with(context)
.load(image)
.into(holder.imageMovie);
holder.rating.setText(String.valueOf(
mMovies.get(position).getVoteAverage()));
holder.dateMovie.setText(mMovies.get(position).getReleaseDate());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context, MovieDetails.class);
Result result = mMovies.get(position);
intent.putExtra(SELECTED_MOVIE, result);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mMovies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ImageView imageMovie;
TextView nameMovie;
TextView rating;
TextView dateMovie;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
this.imageMovie = (ImageView)
itemView.findViewById(R.id.image_movie);
this.nameMovie = (TextView) itemView.findViewById(R.id.name_movie);
this.rating = (TextView) itemView.findViewById(R.id.rating);
this.dateMovie = (TextView) itemView.findViewById(R.id.date);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
}
From the Retrofit documentation:
URL MANIPULATION A request URL can be updated dynamically using
replacement blocks and parameters on the method. A replacement block
is an alphanumeric string surrounded by { and }. A corresponding
parameter must be annotated with #Path using the same string.
#GET("group/{id}/users")
Call<List<User>> groupList(#Path("id") int groupId);
https://square.github.io/retrofit/

Cannot call method of RecyclerView adapter from an activity

I am trying to set the data for recycler view to display from an AsyncTask. I am calling the method setdataEntries from the postExecute of inner class AsyncTask. But the android studio is showing me error could not find the method.
Adapter class
public class EntryAdapter extends RecyclerView.Adapter<EntryAdapter.ViewHolder> {
List<UserTuple> entries;
final private itemClickListener mOnClickListener;
public interface itemClickListener{
void onItemClick(UserTuple utuple);
}
public EntryAdapter(itemClickListener clickhandler) {
mOnClickListener = clickhandler;
}
public void setdataEntries(List<UserTuple> Data) {
entries = Data;
notifyDataSetChanged();
}
#Override
public EntryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singleusertuple,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(EntryAdapter.ViewHolder holder, int position) {
holder.Username.setText(entries.get(position).getUsername());
holder.Password.setText(entries.get(position).getPassword());
}
#Override
public int getItemCount() {
return entries.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView Username;
private TextView Password;
private CardView card;
public ViewHolder(View itemView) {
super(itemView);
Username = itemView.findViewById(R.id.susername);
Password=itemView.findViewById(R.id.pass);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
UserTuple ut=new UserTuple(entries.get(adapterPosition).getUsername(),entries.get(adapterPosition).getPassword());
mOnClickListener.onItemClick(ut);
}
}
}
Calling Activity
public class Usertuple extends AppCompatActivity implements EntryAdapter.itemClickListener {
private RecyclerView recyclerView ;
private RecyclerView.Adapter adapater;
private SnapHelper snapHelper;
private List<UserTuple> entries;
private ProgressBar mLoadingIndicator;
private Bundle extras;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logins);
extras = getIntent().getExtras();
//String site= extras.getString("sitename");
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
Log.i("Logins","Size of returned list "+entries.size());
recyclerView = findViewById(R.id.recycleview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
adapater = new EntryAdapter(this);
recyclerView.setAdapter(adapater);
snapHelper= new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
dataView();
}
public void dataView() {
String site= extras.getString("sitename");
recyclerView.setVisibility(View.VISIBLE);
new FetchDataTask().execute(site);
}
#Override
public void onItemClick(UserTuple utuple) {
}
private String key(){
SharedPreferences sharedPref = getSharedPreferences(
"User", this.MODE_PRIVATE);
final String passphrase = sharedPref.getString("userid", "none");
return passphrase;
}
public void showerror(){
recyclerView.setVisibility(View.GONE);
Toast.makeText(this,"Error in retrieving",Toast.LENGTH_SHORT).show();
}
public setdata(List<UserTuple> data){
adapater.setdataEntries(data);
}
public class FetchDataTask extends AsyncTask<String, Void, List<UserTuple>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected List<UserTuple> doInBackground(String... params) {
/* If there's no zip code, there's nothing to look up. */
if (params.length == 0) {
return null;
}
String site = params[0];
try {
AppDatabase db = Room.databaseBuilder(getApplicationContext(),AppDatabase.class, "production")
.build();
entries =db.entryDao().getSpecific(site);
for(UserTuple ut : entries){
Log.i("password",ut.getPassword());
String st = new Decryption().decrypt(ut.getPassword(),key());
Log.i("After decryption",st);
ut.setPassword(st);
}
return entries;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(List<UserTuple> Data) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
if (Data != null) {
adapater.setdataEntries(Data);
} else {
showerror();
}
}
}
}
I want the database calls to be a background task. I don't want the activity to freeze waiting for database calls. Any ideas? Thanks
Declare adapter like
private EntryAdapter adapter;
instead of
private RecyclerView.Adapter adapater;
because RecyclerView.Adapter class does not have any method named setdataEntries but only EntryAdapter class has this method so only the object of type EntryAdapter can call setdataEntries method.
Or you can use down-casting as
((EntryAdapter)adapater).setdataEntries(data);

Parse JSON value to an Activity from a ListView. Beginner

I just learned java and also android app development.
I've been able to populate json object to a listview from a web-service to my NewActivity.class. but having problems with setting OnItemClickListener for my listview by parsing json value from my jsonparser class to my DetailActivity.class.
I tried reading some answers from here but got lost at some point. I Will be very glad if anyone makes an input. Thanks
JSON PARSER CLASS
public class JSONParser {
public static List<Events> parseFeed(String content) {
try {
JSONArray ar = new JSONArray(content);
List<Events> eventList = new ArrayList<>();
for (int i = 0; i < ar.length(); i++) {
JSONObject obj = ar.getJSONObject(i);
String headline = obj.optString("Content");
Events events = new Events();
events.setId(obj.getInt("id"));
events.setTitle(obj.getString("Title"));
events.setPostDate(obj.getString("PostDate"));
events.setSummary(obj.getString("Summary"));
events.setContent(obj.getString("Content"));
events.setPicture(obj.getString("Picture"));
eventList.add(events);
}
return eventList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
This is my NewActivity.class.
public class NewActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
final String LOG = "ListActivity";
private List<Events> eventsList;
private ListView lvEvents;
ProgressBar pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
lvEvents = (ListView) findViewById(R.id.listview1);
pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
if (isOnline()){
requestData("http://json/events.php");
} else {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
protected void updateDisplay() {
EventListAdapter adapter = new EventListAdapter(this, R.layout.mylist_view, eventsList );
lvEvents.setAdapter(adapter);
lvEvents.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(NewActivity.this, EventsDetail.class);
intent.putExtra("selectedEvents", eventlist[position]);
startActivity(intent);
}
private void requestData(String uri){
MyTask task = new MyTask();
task.execute(uri);
}
protected boolean isOnline(){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public class MyTask extends AsyncTask<String, String, List<Events>> {
#Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
#Override
protected List<Events> doInBackground(String... params) {
String data = HttpManager.getData(params[0]);
eventsList = JSONParser.parseFeed(data);
for (Events events : eventsList) {
try {
String imageUrl = events.getPicture();
InputStream imageRead = (InputStream) new URL(imageUrl).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(imageRead);
events.setBitmap(bitmap);
imageRead.close();
} catch (Exception e){
e.printStackTrace();
}
}
return eventsList;
}
#Override
protected void onPostExecute(List<Events> results) {
eventsList = results;
updateDisplay();
pb.setVisibility(View.INVISIBLE);
}
}
And this my Events.class
public class Events implements Serializable {
public int id;
public String Title;
public String PostDate;
public String Summary;
public String Content;
public String Picture;
public Bitmap bitmap;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPicture() {
return Picture;
}
public void setPicture(String picture) {
Picture = picture;
}
public String getPostDate() {
return PostDate;
}
public void setPostDate(String postDate) {
PostDate = postDate;
}
public String getSummary() {
return Summary;
}
public void setSummary(String summary) {
Summary = summary;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
Lastly my DetailActivity.class which has three TextView to receive the JSON values
public class EventsDetail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView detailname = (TextView) findViewById(R.id.detailTitle);
TextView eventDetail = (TextView) findViewById(R.id.detailContent);
TextView eventDate = (TextView) findViewById(R.id.detailDate);
}
You need to this way:
1. Make class Serializable
public class Events implements Serializable{
// Other stuff
}
2. onItemClick of ListView.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(NewActivity.this, EventsDetail.class);
intent.putExtra("object",eventList[position]);
startActivity(intent);
}
3. EventsDetail class.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_detail);
// Other stuff
Events event = (Events) getIntent().getSerializableExtra("object");
}
Hope this will help you.
You can try this :)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(NewActivity.this, EventsDetail.class);
//try type casting Events instance as Serializable :)
Events selectedEvent = eventList[position];
intent.putExtra("selectedEvent",(Serializable)selectedEvent);
startActivity(intent);
}
This will add selected event as an arguement to your intent :) which is responsible for invoking eventdetail activity :)
and in event detail activity :)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Events passedEvent = getIntent().getSerializableExtra("selectedEvent");
TextView detailname = (TextView) findViewById(R.id.detailTitle);
TextView eventDetail = (TextView) findViewById(R.id.detailContent);
TextView eventDate = (TextView) findViewById(R.id.detailDate);
//set the textview values now from the recieved events instance :)
}
All being said :) for the above code to work you must implement implements Serializable to your Event class :)
This is very simple :) just requires you to specify implement Serializable and write setter and getter for all the properties of Events class :) Thats all :)
Here is a link for how to implement serialization :) http://www.vogella.com/tutorials/JavaSerialization/article.html
Hope my answer helped you :) Happy coding buddy :)

onClickListener on a CardView in a RecyclerView created by a Fragment in a Fragment in an Activity

This is a multi-part question.
First Part:
I'm building an app to track local events. Currently, I have a Fragment containing a RecyclerView consisting of CardViews which each represent one event. What I want is to be able to tap a card and replace the Fragment with a new one showing more details about that card's event.
I've searched Google for several hours, but it none of the solutions presented seemed to work when I tried them. Below is the class for the fragment Tab1 which creates the RecyclerView adapter.
public class Tab1 extends Fragment {
//RecyclerView
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
//ProgressDialog
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "removed";
// JSON Node names
private static final String TAG_EVENT = "event";
private static final String TAG_EVENTNAME = "Event Name";
private static final String TAG_LOCATION = "Location";
private static final String TAG_RAINLOCATION = "Rain Location";
private static final String TAG_ORG = "Org";
private static final String TAG_TIME = "Time";
private static final String TAG_RSVP = "RSVP";
// events JSONArray
JSONArray events = null;
private List<Event> eventlist;
private RecyclerView rv;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_2,container,false);
// Calling async task to get json
new GetEvents().execute();
return v;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
mRecyclerView = (RecyclerView) getView().findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
}
private class GetEvents extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
eventlist = new ArrayList<>();
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
events = jsonObj.getJSONArray(TAG_EVENT);
// looping through All Events
for (int i = 0; i < events.length(); i++) {
JSONObject c = events.getJSONObject(i);
String eventName = c.getString(TAG_EVENTNAME);
String location = c.getString(TAG_LOCATION);
String rain = c.getString(TAG_RAINLOCATION);
String org = c.getString(TAG_ORG);
String time = c.getString(TAG_TIME);
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, h:mm a", Locale.US);
SimpleDateFormat parserSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
try {
Date date = parserSDF.parse(time);
time = format.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
String rsvp = c.getString(TAG_RSVP);
eventlist.add(new Event(eventName, time.toUpperCase(), location, R.drawable.pace));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
RVAdapter adapter = new RVAdapter(eventlist);
mRecyclerView.setAdapter(adapter);
}
}
}
And here is the RVAdapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.EventViewHolder> {
public static class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView eventName;
TextView eventTime;
TextView eventLocation;
ImageView orgPhoto;
private ClickListener clickListener;
EventViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
eventName = (TextView)itemView.findViewById(R.id.event_name);
eventTime = (TextView)itemView.findViewById(R.id.event_time);
eventLocation = (TextView)itemView.findViewById(R.id.event_location);
orgPhoto = (ImageView)itemView.findViewById(R.id.org_photo);
itemView.setOnClickListener(this);
}
public interface ClickListener {
/**
* Called when the view is clicked.
*
* #param v view that is clicked
* #param position of the clicked item
*/
public void onClick(View v, int position, String title);
}
/* Setter for listener. */
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public void onClick(View v) {
clickListener.onClick(v, getPosition(), eventName.getText().toString());
}
}
List<Event> events;
RVAdapter(List<Event> events){
this.events = events;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public EventViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_card, viewGroup, false);
EventViewHolder pvh = new EventViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(EventViewHolder EventViewHolder, final int i) {
EventViewHolder.eventName.setText(events.get(i).name);
EventViewHolder.eventTime.setText(events.get(i).time);
EventViewHolder.eventLocation.setText(events.get(i).location);
EventViewHolder.orgPhoto.setImageResource(events.get(i).orgPhoto);
EventViewHolder.setClickListener(new EventViewHolder.ClickListener() {
#Override
public void onClick(View v, int pos, String title) {
//onClick
}
});
}
#Override
public int getItemCount() {
return events.size();
}
}
You can see I've attempted to implement the interface and onClickListener.
Is this the right way? I've tried to test it by making toasts with the name of the Card clicked, but it doesn't appear to have worked, or at least the toast is not showing up.
Second Part:
If this is the correct way and it should be working, where/how do I write the code to replace the fragment with the new one showing more information about the event? Can it go in the Adapter class? The Tab1 fragment is actually inside of another fragment which is inside of an activity. I'd like to replace Tab1's parent fragment.
See if this helps
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.EventViewHolder> {
public static class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView eventName;
TextView eventTime;
TextView eventLocation;
ImageView orgPhoto;
EventViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
eventName = (TextView) itemView.findViewById(R.id.event_name);
eventTime = (TextView) itemView.findViewById(R.id.event_time);
eventLocation = (TextView) itemView.findViewById(R.id.event_location);
orgPhoto = (ImageView) itemView.findViewById(R.id.org_photo);
}
#Override
public void onClick(View view) {
//do stuff
}
}
List<Event> events;
RVAdapter(List<Event> events){
this.events = events;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public EventViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_card, viewGroup, false);
return new EventViewHolder(v);
}
#Override
public void onBindViewHolder(EventViewHolder EventViewHolder, final int i) {
EventViewHolder.eventName.setText(events.get(i).name);
EventViewHolder.eventTime.setText(events.get(i).time);
EventViewHolder.eventLocation.setText(events.get(i).location);
EventViewHolder.orgPhoto.setImageResource(events.get(i).orgPhoto);
}
#Override
public int getItemCount() {
return events.size();
}
}
For the 2nd part of your question. Its better for the ParentActivity hosting both Frag1 & Frag2 to switch the fragment. So say in the ParentActivity, there is a framelayout (R.id.container) that is hosting Frag1.
You can pass the event call back to the activity, and you can do this to replace the fragment in the container
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, Frag2)
.commit();

Categories