Can't open fragment from RecyclerView item Click - android

Hi I have a simple app that features a recyclerView with list items (each representing a "Movie" object. The content for the movie list items is generated from an API call (themoviedb.org). I'm trying to open a "detail fragment" by clicking on a recyclerView list item. I want all of the content from the Movie item clicked to appear in the next fragment as well. Right now when I click the list item, nothing happens. No crash, even. I thought I had set up the listener interface correctly, but maybe that's the problem. Can anyone see where I'm going wrong? Thanks in advance.
Here is the Fragment where the RecyclerView (movie list) first appears:
public class ResultsFragment extends Fragment {
private RecyclerView mRecyclerView;
Movie_Results_Adapter results_adapter;
ArrayList<Movie> movieList;
onMovieSelectedListener listener;
public ResultsFragment(){
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout_1, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);
mRecyclerView.setVisibility(View.VISIBLE);
results_adapter = new Movie_Results_Adapter(movieList, listener);
listener = new onMovieSelectedListener() {
#Override
public void onMovieSelected(Movie selectedMovie) {
Intent launchIntent = new Intent(getContext(), MovieDetailActivity.class);
launchIntent.putExtra(MovieDetailActivity.EXTRA_MOVIE, "movie");
Log.d("PaulsApp", selectedMovie + "");
launchIntent.putExtra(MovieDetailActivity.NEW_EXTRA, (Serializable) selectedMovie);
startActivity(launchIntent);
}
};
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(results_adapter);
Log.d("TAGG", "AAAH" + movieList.toString());
return rootView;
}
public void parseJson(String jsonToParse) throws JSONException {
JSONObject responseObject= new JSONObject(jsonToParse);
JSONArray resultsArray = responseObject.getJSONArray("results");
for(int i = 0; i < resultsArray.length(); i++){
JSONObject movie = resultsArray.getJSONObject(i);
String movieName = movie.getString("title");
String movieReleaseDate = movie.getString("release_date");
String movieScore = movie.getString("vote_average");
String moviePopularity = movie.getString("vote_count");
String movieImage = movie.getString("poster_path");
String movieDescription = movie.getString("overview");
Movie movie1 = new Movie(movieName, movieReleaseDate, movieScore, moviePopularity, movieImage, movieDescription);
movieList.add(movie1);
}
}
#Override
public void setArguments(Bundle args) {
movieList = new ArrayList<>();
String arguments = args.getString("JSON_STRING");
try {
parseJson(arguments);
} catch (JSONException e) {
e.printStackTrace();
}
super.setArguments(args);
}
public interface onMovieSelectedListener{
public void onMovieSelected(Movie selectedMovie);
}
}
Here is the RecyclerView Adapter for the "results" fragment:
public class Movie_Results_Adapter extends RecyclerView.Adapter<Movie_Results_Adapter.ResultViewHolder>{
ArrayList<Movie> MovieListArray;
ResultsFragment.onMovieSelectedListener listener;
private Activity mActivity;
public class ResultViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView titleText;
TextView dateText;
TextView scoreText;
TextView popularityText;
ImageView movieImage;
public Movie movie;
public ResultViewHolder(View itemView){
super(itemView);
titleText = (TextView) itemView.findViewById(R.id.movie_title_text);
dateText = (TextView) itemView.findViewById(R.id.movie_date_text);
scoreText = (TextView) itemView.findViewById(R.id.movie_score_text);
popularityText = (TextView) itemView.findViewById(R.id.movie_popularity_text);
movieImage = (ImageView) itemView.findViewById(R.id.movie_image);
}
#Override
public void onClick(View view) {
if (listener != null) {
listener.onMovieSelected(MovieListArray.get(getAdapterPosition()));
Toast.makeText(view.getContext(), "clicked: " + MovieListArray.get(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
}
public Movie_Results_Adapter(ArrayList<Movie> movieList, ResultsFragment.onMovieSelectedListener listener){
MovieListArray = movieList;
this.listener = listener;
}
#Override
public ResultViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_result_list_item, parent, false);
ResultViewHolder vh = new ResultViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ResultViewHolder holder, int position) {
holder.titleText.setText(MovieListArray.get(position).getmTitle());
Log.d("TAGG", MovieListArray.toString());
holder.dateText.setText("Released "+MovieListArray.get(position).getmReleaseYear());
holder.scoreText.setText("TMDB Score: "+MovieListArray.get(position).getmScore());
holder.popularityText.setText(MovieListArray.get(position).getmPopularity()+" votes");
Context context = holder.movieImage.getContext();
Picasso.with(context).load(Constants.TMDB_POSTER+MovieListArray.get(position).getmImage()).into(holder.movieImage);
}
#Override
public int getItemCount() {
return MovieListArray.size();
}
}
Here is the detail fragment (and accompanying activity):
package jetsetpaul.movienerd;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
/**
* Created by pauljoiner on 8/17/16.
*/
public class MovieDetailFragment extends Fragment {
public String movieTitle;
public String movieImage;
public String movieDate;
public String movieDescription;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail_fragment, container, false);
TextView mTitleText = (TextView) rootView.findViewById(R.id.movie_detail_title);
ImageView mMovieImage = (ImageView) rootView.findViewById(R.id.movie_detail_image);
TextView mDateText = (TextView) rootView.findViewById(R.id.movie_detail_release_date);
TextView mDescriptionText = (TextView) rootView.findViewById(R.id.movie_detail_description);
mTitleText.setText(movieTitle);
mDateText.setText(movieDate);
mDescriptionText.setText(movieDescription);
Context context = mMovieImage.getContext();
Picasso.with(context).load(Constants.TMDB_POSTER+movieImage);
return rootView;
}
public void setMovieTitle(String title){
this.movieTitle = title;
}
public void setMovieImage(String image){
this.movieImage = image;
}
public void setMovieDate(String date){
this.movieDate = date;
}
public void setMovieDescription(String description){
this.movieDescription = description;
}
}
Activity:
package jetsetpaul.movienerd;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
/**
* Created by pauljoiner on 8/17/16.
*/
public class MovieDetailActivity extends AppCompatActivity {
public static final String EXTRA_MOVIE = "movie";
public static final String NEW_EXTRA = "movie2";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
Intent i = getIntent();
if(i.hasExtra(NEW_EXTRA)) {
Log.d("PaulsApp", "Had Extra!");
//set the text in my fragment
Movie movie = (Movie) i.getSerializableExtra(NEW_EXTRA);
Fragment newFragment = new MovieDetailFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_fragment, newFragment);
transaction.commit();
((MovieDetailFragment) newFragment).setMovieTitle(movie.getmTitle());
((MovieDetailFragment) newFragment).setMovieImage(movie.getmImage());
((MovieDetailFragment) newFragment).setMovieDate(movie.getmReleaseYear());
((MovieDetailFragment) newFragment).setMovieDescription(movie.getmDescription());
}
}
}
I can post more code if necessary. Thanks again!

Your listener needs to be created before your results_adapter
listener = new onMovieSelectedListener() {
#Override
public void onMovieSelected(Movie selectedMovie) {
Intent launchIntent = new Intent(getContext(), MovieDetailActivity.class);
launchIntent.putExtra(MovieDetailActivity.EXTRA_MOVIE, "movie");
Log.d("PaulsApp", selectedMovie + "");
launchIntent.putExtra(MovieDetailActivity.NEW_EXTRA, (Serializable) selectedMovie);
startActivity(launchIntent);
}
};
results_adapter = new Movie_Results_Adapter(movieList, listener);
To be honest though, it would be best for your fragment to implement the listener (interface) instead of having to create it by using new onMovieSelectedListener().

Related

How to fetch link from json and connect it to button?

I am working with a project and I am trying to fetch some link from a json data and I want to connect the link with a button in my recycleview so that whenever the button is clicked, it'll automatically connet to the respective websites. I gave user permission to interner in Manifest. So, How to connect it?
package com.example.covidcuretemplate1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
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 {
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private ExampleAdapter exampleAdapter;
private ArrayList<ExampleItem> exampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL,false));
exampleList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=*************************";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject article = jsonArray.getJSONObject(i);
if(article.isNull("description") || article.isNull("urlToImage")) {
continue;
}
if(article.getString("description").isEmpty() || article.getString("urlToImage").isEmpty())
continue;
String title = article.getString("title");
String description = article.getString("description");
String date = article.getString("publishedAt");
String imageurl = article.getString("urlToImage");
//How to connect this??????
String newsurl = article.getString("url");
exampleList.add(new ExampleItem(imageurl,title,description,date));
}
exampleAdapter = new ExampleAdapter(MainActivity.this,exampleList);
recyclerView.setAdapter(exampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
My Adapter class, Here can anybody suggest anything in the place of toast? The Toast is working fine !!!
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
public Context mcontext;
public ArrayList<ExampleItem> marrayList;
public ExampleAdapter(Context mcontext, ArrayList<ExampleItem> marrayList) {
this.mcontext = mcontext;
this.marrayList = marrayList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mcontext).inflate(R.layout.card_item,parent,false);
ExampleViewHolder exampleViewHolder = new ExampleViewHolder(view);
return exampleViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem examplItem = marrayList.get(position);
String imageurl = examplItem.getMimgurl();
String title = examplItem.getMtitle();
String description = examplItem.getMdescription();
String date = examplItem.getMdate();
/////////////
final String newsurl = examplItem.getMurl();
////////////
holder.textview_title.setText(title);
holder.textview_description.setText(description);
holder.textview_date.setText(date);
Glide.with(mcontext).load(imageurl).into(holder.imageview_news);
///////////////////////////
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//////////////////////////////////NEED HELP!!!!!!!!!!!!!!!!!!/////////
Toast.makeText(mcontext,newsurl,Toast.LENGTH_LONG).show();
}
});
//////////////////////////
}
#Override
public int getItemCount() {
return marrayList.size();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public ImageView imageview_news;
public TextView textview_title;
public TextView textview_description;
public TextView textview_date;
///////////////////////////
public Button button;
///////////////////////////
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
imageview_news = itemView.findViewById(R.id.imageview_news);
textview_title = itemView.findViewById(R.id.textview_title);
textview_description = itemView.findViewById(R.id.textview_description);
textview_date = itemView.findViewById(R.id.textview_date);
/////////////////////////
button = itemView.findViewById(R.id.button);
////////////////////////
}
}
}
Try to set intent for the website inside the onClickListener. Something like this:
Button button= findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "http://www.YourWebsite.com"; //insert the link you prase
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
You can use this code inside onClickListener to open it in the browser.
Uri uri = Uri.parse(newsurl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

Put 2 columns of recycler view every row

I would like to put 2 columns of recyclerview every row.
Right now my design is like this:
and i would like to put 2 so the scroll is not to long.
I have this view inside a fragment and I use a recyclerview adapter but I have no clue how to tell it to use its parent with, so it can fill the width of the screen. In the fragment I recive a JSON from an online database using an AsyncTask and fill in the recyclerview on the onPostExecute of the AsyncTask.
If anyone has any Idea how i can do it, I can't seem to find this anywhere
Thx!
My recyclerview Adapter:
package com.example.juanfri.seguridadmainactivity;
/**
* Created by jlira on 30/05/2017.
*/
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Juanfri on 29/05/2017.
*/
public class RecyclerAdapterSerie extends RecyclerView.Adapter<RecyclerAdapterSerie.SerieHolder> {
private ArrayList<Serie> mSerie;
#Override
public RecyclerAdapterSerie.SerieHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View inflatedView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recyclerview_card, viewGroup, false);
return new SerieHolder(inflatedView);
}
#Override
public void onBindViewHolder(RecyclerAdapterSerie.SerieHolder holder, int i) {
Serie itemPhoto = mSerie.get(i);
holder.bindPhoto(itemPhoto);
}
#Override
public int getItemCount() {
return mSerie.size();
}
public RecyclerAdapterSerie(ArrayList<Serie> serie) {
mSerie = serie;
}
public static class SerieHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//2
private ImageView mItemImage;
private TextView mItemDate;
private TextView mItemDescription;
private Serie serie;
//3
private static final String PHOTO_KEY = "PHOTO";
//4
public SerieHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.item_image);
mItemDate = (TextView) v.findViewById(R.id.item_date);
mItemDescription = (TextView) v.findViewById(R.id.item_description);
v.setOnClickListener(this);
}
//5
#Override
public void onClick(View v) {
/*Context context = itemView.getContext();
Intent showPhotoIntent = new Intent(context, Pelicula.class);
showPhotoIntent.putExtra(PHOTO_KEY, peli);
context.startActivity(showPhotoIntent);*/
}
public void bindPhoto(Serie mserie) {
serie = mserie;
String Nombre = mserie.getNombreSerie();
if(Nombre.length() >= 25)
{
Nombre = Nombre.substring(0,22);
Nombre = Nombre + "...";
}
Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
mItemDate.setText(Nombre);
mItemDescription.setText(Integer.toString(mserie.getIdTMDB()));
}
}
}
My fragment (where i create the recyclerview)
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
/**
* Created by jlira on 06/06/2017.
*/
public class FragmentoSeriesPelis extends Fragment {
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original/";
private ProgressDialog pDialog;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<Serie> series;
private ArrayList<Pelicula> Pelis;
private RecyclerAdapterSerie mAdapterSerie;
private RecyclerAdapterPelicula mAdapterPeli;
private int pagina;
private String url;
private Button CargarMas;
private String tipo;
private int MaxPag;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.series_pelis_layout, container, false);
view.setTag(TAG);
Bundle args = getArguments();
series = new ArrayList<>();
Pelis = new ArrayList<>();
MaxPag = 2;
pagina = args.getInt("Page");
url = args.getString("url");
tipo = args.getString("Tipo");
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewSerieshoy);
//mLinearLayoutManagerSerie = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
//recyclerViewSerie.setLayoutManager(mLinearLayoutManagerSerie);
//mAdapterSerie = new RecyclerAdapterSerie(seriesHoy);
//recyclerViewSerie.setAdapter(mAdapterSerie);
new GetSeriesHoy().execute();
CargarMas = (Button) view.findViewById(R.id.buttonCargarMas);
CargarMas.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(pagina+1<=MaxPag)
{
pagina++;
new GetSeriesHoy().execute();
}
else
{
Toast.makeText(getActivity(), "No hay mas resultados", Toast.LENGTH_LONG).show();
}
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Series de Hoy");
}
private class GetSeriesHoy 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) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
String aux = url+pagina;
String jsonStr = sh.makeServiceCall(aux);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
MaxPag = jsonObj.getInt("total_pages");
JSONArray contacts = jsonObj.getJSONArray("results");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
int IdSerie = i;
int idTMDB = c.getInt("id");
String nombreSerie;
String poster =URLFOTO + c.getString("poster_path");
if(tipo.equalsIgnoreCase("Series"))
{
nombreSerie = c.getString("name");
Serie nuevo = new Serie();
nuevo.setIdSerie(IdSerie);
nuevo.setNombreSerie(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
series.add(nuevo);
}
else
{
nombreSerie = c.getString("title");
Pelicula nuevo = new Pelicula();
nuevo.setIdPelicula(IdSerie);
nuevo.setNombrePelicula(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
Pelis.add(nuevo);
}
}
} catch (final JSONException e) {
Toast.makeText(getActivity(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
//Aqui Realizar la RecycleView BuildUp
if(tipo.equalsIgnoreCase("Series"))
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterSerie = new RecyclerAdapterSerie(series);
recyclerView.setAdapter(mAdapterSerie);
}else
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterPeli = new RecyclerAdapterPelicula(Pelis);
recyclerView.setAdapter(mAdapterPeli);
}
}
}
}
Replace your LinearLayoutManager for a GridLayoutManager like this:
private GridLayoutManager mGridLayoutManager;
// ...
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
Then you can use it the same way as the LinearLayoutManager.

How to get id of sqlite when recyclerview item clicked?

Here is my doubt when i click recyclerview item need to get task id which i saved in sqlite how can i do this for example when i click recycler view need to pass that value to next page and need update that value how can i do this so far what i have tried is:
public class Task extends Fragment {
private static final String MY_PREFERENCE_KEY = "yogan";
private List<Model_Task_List> model_task_lists;
private RecyclerView recyclerView;
Task_List_Adapter taskadapter;
private RecyclerView.LayoutManager layoutManager;
SharedPreferences sharedPreferences;
private RecyclerView.Adapter adapter;
RequestQueue yog;
String user_id;
AppController app;
RequestQueue queue;
String Url;
Task_DB task_db = null;
Database_SF_APP database_sf_app;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
if (model_task_lists == null) {
model_task_lists = new ArrayList<Model_Task_List>();
}
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
int hour=c.get(Calendar.HOUR_OF_DAY);
String hours=Integer.toString(hour);
database_sf_app = new Database_SF_APP(getActivity().getBaseContext());
int count=database_sf_app.getTaskCount();
sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
user_id = sharedPreferences.getString("user_id", null);
model_task_lists=database_sf_app.getTaskListById(user_id);
taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
recyclerView.setAdapter(taskadapter);
if(taskadapter!=null){
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
}
});
}
queue = Volley.newRequestQueue(getContext());
Url = "http://xxx.xx.x.xx/xxx/GetActivitiesByUserID.svc/getlist/Task/" + user_id +"/" +null+"/"+hours;
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.POST, Url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String server_response = response.toString();
try {
JSONObject json_object = new JSONObject(server_response);
JSONArray json_array = new JSONArray(json_object.getString("TaskResult"));
for (int i = 0; i < json_array.length(); i++) {
Model_Task_List modelobj = new Model_Task_List();
JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
modelobj.setTaskID(json_arrayJSONObject.getInt("TaskID"));
modelobj.setUserName(json_arrayJSONObject.getString("DueDate"));
modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
modelobj.setUserid(json_arrayJSONObject.getString("Owner"));
database_sf_app.insertorUpdate(modelobj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
//Creating request queue
queue.add(jsonObjRequest);
}
//sync operation
//a union b
//a server
//b local storage
//a only - insert local
//b only - send to server
//a = b do nothing
//result
//bind
return view;
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop() {
super.onStop();
}
}
Here is my TaskAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class Task_List_Adapter extends RecyclerView.Adapter<Task_List_Adapter.MyViewHolder> {
private List<Model_Task_List> dataSet;
private Context context;
private static data yog;
Model_Task_List modelTaskList=new Model_Task_List();
public void remove(int position)
{
dataSet.remove(position);
notifyItemRemoved(position);
}
public void edit(int position){
dataSet.set(position, modelTaskList);
notifyItemChanged(position);
}
public void setOnItemClickListener(data listener) {
this.yog = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// Model_Task_List Model_Task_List=new Model_Task_List();
TextView textname;
TextView textaddress;
TextView textphnum;
TextView textdegree;
TextView textemail;
ImageView call;
data datas;
public MyViewHolder(final View itemView) {
super(itemView);
this.textname = (TextView) itemView.findViewById(R.id.subject);
this.textaddress = (TextView) itemView.findViewById(R.id.username);
this.textphnum = (TextView) itemView.findViewById(R.id.status);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yog!=null){
yog.yog(itemView,getLayoutPosition());
}
}
});
// this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public interface data
{
void yog(View v,int position);
}
public Task_List_Adapter(List<Model_Task_List> data,Context context) {
this.dataSet = data;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.task_list_view, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TextView textViewName = holder.textname;
TextView textViewaddress = holder.textaddress;
TextView textViewphnum = holder.textphnum;
TextView textdegree = holder.textdegree;
TextView textemail=holder.textemail;
textViewName.setText("Subject:"+dataSet.get(position).getSubject());
textViewaddress.setText("DueDate"+dataSet.get(position).getUserName());
textViewphnum.setText("Status:"+dataSet.get(position).getTaskStatus());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
IS it right way to get id:
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
Model_Task_List model_task_list=(Model_Task_List)model_task_lists.get(position);
String yog=model_task_list.getSubject().toString();
int yogeshs=model_task_list.getTaskID();
String yogan=Integer.toString(yogeshs);
Toast.makeText(getContext(),yogan,Toast.LENGTH_SHORT).show();
}
});
}
Where i make recyclerview clickable how to get id of sqlite when i click and need to pass the value to next page
The object you are displaying in recyclerview ,
in your case that code must be in TaskAdapter,
put id in that object so when you click on it you will get that object so retrieve ID from that object
clickedObjecj.getId();
defining onClick in the onBindViewHolder is not a good pratice
the correct way is that declare a interface in the adapter class and implement it on the Activity , Using interface we can pass the value
Steps 1:
Decalre Listener for the OnItemClickListener interface
private OnItemClickListener mListener;
Step 2 : declare an interface , this interface will forward our click and data from adapter to our activity
public interface OnItemClickListener {
void onItemClick(int elementId);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Step 3 : define the on click on ViewHolder and pass the id
//Assigning on click listener on the item and passing the ID value of the item
itemView.setOnClickListener(new View.OnClickListener() { // we can handle the click as like we do in normal
#Override
public void onClick(View v) {
if (mListener != null) {
int elementId = dataSet.get(getAdapterPosition()).getTaskID(); // Get the id of the item on that position
mListener.onItemClick(elementId); // we catch the id on the item view then pass it over the interface and then to our activity
}
}
});
Step 4: implement TaskAdapter.OnItemClickListener in the activity
Step 6: onItemClick method you will recive the value
#Override
public void onItemClick(int itemId) {
Log.d(TAG, "onItemClick: "+String.valueOf(itemId));
}
first you have to set Cursor position into clicked one
Ex: Cursor products <- storing a set of data
to set Cursor to clicked position for example a position value from RecyclerView click event
products.moveToPosition(position);
then use getString as usual
String name = products.getString(products.getColumnIndex("NAME"));
hope it may help
Hmm, my problem just change setOnClickListener to setOnLongClickListener
i declare puplic static int posit in my Adapter
Second in onBindViewHolder of Adapter, i call:
holder.layout_item.setOnLongClickListener(new View.OnLongClickListener() { #Override public boolean online(View view) { posit = arrayList.get(position).getId(); return false; } });
Next, on MainActivity, i want delete 1 object in sqlite
Boolean checkDeleteData = phamTuanVan_sqlite.deleteData(PhamTuanVan_Adapter.posit);
hope it may help

notifyDataSetChanged() method not working

I am using a RecyclerView and after a user input I would like to update the RecyclerView. But there simply happens nothing.
The Layout is just refreshed when I reload the whole Fragment again.
My code:
package com.stack.overflow.fragment.Einstellungen;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.stack.overflow.HelperClasses.RecyclerView.DividerItemDecoration;
import com.stack.overflow.HelperClasses.RecyclerView.ItemClickSupport;
import com.stack.overflow.R;
import com.stack.overflow.fragment.Einstellungen.QrCode.FragmentQrCode;
import com.afollestad.materialdialogs.MaterialDialog;
import com.pixplicity.easyprefs.library.Prefs;
import java.util.ArrayList;
import java.util.List;
public class FragmentEinstellungen extends Fragment {
private static final String KEY_STUFE = "Stufe";
private static final String DEFAULT_EINTRAG_STUFE = "keine Stufe ausgewählt";
private RecyclerView mRecyclerView;
private EinstellungenDataAdapter mAdapter;
private static String[] titles = null;
private static String[] titlesStufen = null;
private static String[] titlesKlassen = null;
int callbackDialog;
String stufe = "";
public FragmentEinstellungen(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
titles = getActivity().getResources().getStringArray(R.array.einstellungen);
titlesStufen = getActivity().getResources().getStringArray(R.array.stufenauswahl);
titlesKlassen = getActivity().getResources().getStringArray(R.array.klassenauswahl);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_einstellungen, container, false);
mRecyclerView = (RecyclerView) layout.findViewById(R.id.einstellungenRecyclerView);
mAdapter = new EinstellungenDataAdapter(getActivity(), getData());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
final ItemClickSupport itemClick = ItemClickSupport.addTo(mRecyclerView);
itemClick.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClick(RecyclerView parent, View child, int position, long id) {
//SnackbarManager.show(
// Snackbar.with(getActivity())
// .text("KLICK"));
displayView(0);
}
});
return layout;
}
public static List<EinstellungenItem> getData() {
List<EinstellungenItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
EinstellungenItem navItem = new EinstellungenItem();
navItem.setTitle(titles[i]);
if(i==0){
navItem.setSubtitle("kein gültiger Scan");
} else if(i==1){
navItem.setSubtitle(Prefs.getString(KEY_STUFE, DEFAULT_EINTRAG_STUFE));
}
data.add(navItem);
}
return data;
}
private void displayView(int position) {
switch (position) {
case 0:
break;
case 1:
new MaterialDialog.Builder(getActivity())
.title(R.string.title_dialog_stufe)
.items(R.array.stufenauswahl)
.itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
#Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
callbackDialog = which;
stufe = titlesStufen[which];
if (callbackDialog <= 4) {
new MaterialDialog.Builder(getActivity())
.title(R.string.title_dialog_klasse)
.items(R.array.klassenauswahl)
.itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
#Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
stufe = stufe + titlesKlassen[which];
Prefs.putString(KEY_STUFE, stufe);
mAdapter.notifyDataSetChanged();
return true;
}
})
.positiveText(R.string.choosetext_dialog_klasse)
.show();
} else {
Prefs.putString(KEY_STUFE, stufe);
mAdapter.notifyDataSetChanged();
}
return true;
}
})
.positiveText(R.string.choosetext_dialog_stufe)
.show();
callbackDialog = 0;
break;
default:
break;
}
}
}
Am I doing the refresh at the wrong time?
Your mAdapter uses getData() which returns every time another instance of new ArrayList<>() and when you call the mAdapter.notifyDataSetChanged(); the adapter tries to refresh the old instance of the arrayList but there is no changes.
You need to save your data into a field and update that field like mArrayList.clear() and mArrayList.addAll(getData()).

Android ListView showing only first 4 items on repeat

I have a Fragment called User Management where I collect data from a server and display it in a ListView. It's also refreshable via SwipeRefreshLayout.
What happens is, if I get data on 1-4 users, it displays the data correctly. However, if I get data on more than 4 users, it displays the first 4 correctly, and instead of the fifth, it's the first one again, instead of the 6th, it's the second one and so on and so on.
I've tried everything I could think of, the adapter is getting the data correctly, the ListView is getting the adapter correctly, but for some reason, it peaks at 4 users displayed, and simply repeats them after that (the funny thing is, if I add a user and then refresh, it simply repeats the next user one more time in the list, so it's definitely aware of the change in user number)
Can you help me finding the problem?
The java class:
package com.softwarenation.jetfuel.fragments.userManagement;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.softwarenation.jetfuel.R;
import com.softwarenation.jetfuel.activities.MainActivity;
import com.softwarenation.jetfuel.fragments.Stations;
import com.softwarenation.jetfuel.managers.JetfuelManager;
import com.softwarenation.jetfuel.managers.StatusManager;
import com.softwarenation.jetfuel.managers.UserManager;
import com.softwarenation.jetfuel.utility.Global;
import com.softwarenation.jetfuel.utility.GlobalConnection;
import com.softwarenation.jetfuel.utility.users.User_pictures;
import com.softwarenation.jetfuel.utility.users.Users_mana;
import org.nicktate.projectile.Method;
import org.nicktate.projectile.Projectile;
import org.nicktate.projectile.StringListener;
import java.io.InputStream;
import java.util.ArrayList;
public class UserManagement extends Fragment {
private SwipeRefreshLayout swipeRefreshLayout;
//private View refreshView;
private Global font = new Global();
private ListView listView;
private ArrayList<User_pictures> pictureses = new ArrayList<User_pictures>();
private static boolean isfirst = false;
private PullToRefreshListView pullToRefreshView;
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**---------------------------------------------------------------------------------------------*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_usermanagemnet, container, false);
listView = (ListView)rootView.findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
// refreshView = (View) rootView.findViewById(R.id.swipe);
//First time, we get the data from a server, then only display that data until the user calls for a refresh
if(!StatusManager.getInstance().getUsermStatus()){
UsersTask usersTask = new UsersTask();
usersTask.execute();
}else{
setContent();
}
Button addUser = (Button)rootView.findViewById(R.id.addUser_button);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new AddUser();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
// Set a listener to be invoked when the list should be refreshed.
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.e("start","onRefresh");
new GetDataTask().execute();
}
}
);
/* pullToRefreshView = (PullToRefreshListView)rootView.findViewById(R.id.pull_to_refresh_listview);
pullToRefreshView.bringToFront();
pullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});*/
return rootView;
}
public void setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener){
swipeRefreshLayout.setOnRefreshListener(listener);
}
public boolean isRefreshing(){
return swipeRefreshLayout.isRefreshing();
}
public void setRefreshing(boolean refreshing){
swipeRefreshLayout.setRefreshing(refreshing);
}
public SwipeRefreshLayout getSwipeRefreshLayout(){
return swipeRefreshLayout;
}
//on refresh, get new data from the server
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... voids) {Log.e("start","GetDataTask");
UsersTask usersTask = new UsersTask();
usersTask.execute();
return new String[0];
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
// pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
MainActivity.setBackDisabled(false);
Log.e("GetDataTask","completed");
}
}
private class SampleItem {
public String id;
public String title;
public String username;
public String groupName;
public int userPicture;
public int editPicture;
public int dPicture;
public String activated;
public SampleItem(String id, String title, String username, String groupName, int userPicture, int editPicture, int dPicture, String activated ) {
this.id = id;
this.title = title;
this.username = username;
this.groupName = groupName;
this.userPicture = userPicture;
this.editPicture = editPicture;
this.dPicture = dPicture;
this.activated = activated;
}
}
static class ViewHolder {
private String checkBox;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private RelativeLayout relativeLayout2;
public void setCheckBox(String checkBox) {
this.checkBox = checkBox;
}
public void setLinearLayout(LinearLayout linearLayout) {
this.linearLayout = linearLayout;
}
public void setRelativeLayout(RelativeLayout relativeLayout) {
this.relativeLayout = relativeLayout;
}
public void setRelativeLayout2(RelativeLayout relativeLayout2) {
this.relativeLayout2 = relativeLayout2;
}
public LinearLayout getLinearLayout() {
return linearLayout;
}
public RelativeLayout getRelativeLayout() {
return relativeLayout;
}
public RelativeLayout getRelativeLayout2() {
return relativeLayout2;
}
public RelativeLayout getCheckBox() {
return relativeLayout;
}
}
public class SampleAdapter extends ArrayAdapter<SampleItem> {
final ViewHolder holder = new ViewHolder();
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
ImageView userPicture = (ImageView)convertView.findViewById(R.id.userpicture);
userPicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
TextView title = (TextView)convertView.findViewById(R.id.user_name);
font.setFont(title, 3, getActivity());
title.setText(getItem(position).title);
TextView username = (TextView)convertView.findViewById(R.id.username);
font.setFont(username, 2, getActivity());
username.setText(getItem(position).username);
TextView groupname = (TextView)convertView.findViewById(R.id.groupName);
font.setFont(groupname, 2, getActivity());
groupname.setText(getItem(position).groupName);
ImageView useredit = (ImageView)convertView.findViewById(R.id.editbutton);
useredit.setImageDrawable(getResources().getDrawable(getItem(position).editPicture));
useredit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new EditProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
/**---------------*/
ImageView userdelate = (ImageView)convertView.findViewById(R.id.deletebutton);
userdelate.setImageDrawable(getResources().getDrawable(getItem(position).dPicture));
holder.setLinearLayout((LinearLayout)convertView.findViewById(R.id.lin_show_profile));
//LinearLayout show = (LinearLayout)convertView.findViewById(R.id.lin_show_profile);
holder.getLinearLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new ShowProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
//
holder.setRelativeLayout((RelativeLayout)convertView.findViewById(R.id.delate_user));
//RelativeLayout delete_user = (RelativeLayout)convertView.findViewById(R.id.delate_user);
holder.getRelativeLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogStop("Are you sure?", getItem(position).username, getActivity(), getItem(position).id);
}
});
//
//holder.setCheckBox(getItem(position).activated);
//
/**---------------*/
//Red or Blue background
// RelativeLayout settings = (RelativeLayout)convertView.findViewById(R.id.settingsbutton);
holder.setRelativeLayout2((RelativeLayout) convertView.findViewById(R.id.settingsbutton));
//if(getItem(position).activated.equals("false")) {
if (getItem(position).activated.equals("false")) {
holder.getLinearLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout2().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
}
//holder.setCheckBox(getItem(position).activated);
convertView.setTag(holder);
} else {
convertView.getTag();
}
return convertView;
}
}
public void DialogStop(String title, String message,Context context, final String id){
new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dialog.cancel();
DeleteTask deleteTask = new DeleteTask();
deleteTask.execute(id);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private class DeleteTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
String response = null;
try {
response = new GlobalConnection().DELETE( getString(R.string.apicdeleteuser) + params[0].toString() );
Log.v("response", response + "");
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
Log.v("response", response + "");
}
}
private class UsersTask extends AsyncTask<String, Void, ArrayList<Users_mana>> {
#Override
protected ArrayList<Users_mana> doInBackground(String... strings) {
//Users_mana users = null;
String response = null;
ArrayList<Users_mana> users_manas = null;
try{Log.e("start","GET via GlobalConnection()");
response = new GlobalConnection().GET( getString(R.string.apiusers));
users_manas = new Gson().fromJson(response, new TypeToken<ArrayList<Users_mana>>(){}.getType());
Log.e("start","setUsers_mana");
UserManager.getInstance().setUsers_mana(users_manas);
}catch (Exception e){
Log.e("response error", e.getMessage().toString());
}
return users_manas;
}
#Override
protected void onPostExecute(ArrayList<Users_mana> response) {
if(!response.isEmpty()) {Log.e("start","setContent()");
setContent();
StatusManager.getInstance().setUsermStatus(true);
Log.e("UsermStatus:",String.valueOf(StatusManager.getInstance().getUsermStatus()));
}
super.onPostExecute(response);
}
}
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
/*
private class PicturesTask extends AsyncTask<String, String ,String>{
#Override
protected String doInBackground(String... urls) {
//String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
for(int i = 0; i < urls.length; i++) {
if(UserManager.getInstance().getUsers_mana().get(i).photo != null) {
InputStream in = new java.net.URL(getString(R.string.jetfuel_url ) + UserManager.getInstance().getUsers_mana().get(i).username).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
pictureses.add(new User_pictures(mIcon11, UserManager.getInstance().getUsers_mana().get(i).username, UserManager.getInstance().getUsers_mana().get(i).id));
UserManager.getInstance().setUserPictureses(pictureses);
}
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(!UserManager.getInstance().getUserPictureses().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUserPictureses().size(); i++) {
Log.v("pictures", UserManager.getInstance().getUserPictureses().get(i).picture + "");
}
}
super.onPostExecute(s);
}
}
*/
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
//menu.removeItem(R.id.Station);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Station:
Fragment fragment = new Stations();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**---------------------------------------------------------------------------------------------*/
}
The xml view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue">
<Button
android:id="#+id/addUser_button"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="#string/add_user"
android:background="#drawable/button_yellow_background"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#color/blue"/>
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
Thank you!
There is a huge problem in your SampleAdapter.getView() method.
When you scroll down the View disappearing at the top of the screen is reused to be injected at the bottom. This reused View is the convertView you get as getView parameter.
As you code is, the reused view is injected with the exact same data (because if (convertView == null) { is always false when you scroll).
Images and texts are not updated.
When you scroll down, the element disappearing at the top just appears at the bottom, and so does others...
You should be doing something like:
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
// The ViewHolder constructor should handle the mapping of its views
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here you should only use holder as in:
holder.userpicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
...
}
This method looks strange, and is perhaps suspect. I don't see getUsers_mana() defined anywhere in this sample code, so I don't know if it is the problem or not. For one, you should call that 'UserManager.getInstance().getUsers_mana()' and then 'get(i)' once each and store the results in variables.
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
It is because you are not doing anything in the
else {
convertView.getTag();
}
Check here
Why we should re-assign values for a recycled convertView in getView()
You have to reassign values to the convertView with the data of the 5th roq, 6th row etc. otherwise it still contains the old data
Remove the initialization of holder on the top and just put this line of code in the beginning of getView function.
ViewHolder holder = null;
You need to re initialize holder if its null and you need to update it with latest data if its not null.
See this sample it might help you
https://github.com/erikwt/PullToRefresh-ListView

Categories

Resources