Calling my async task class from my oncreate in OpensubcontentActivity, it is executing fine but while calling the same async task class from vivcontentAdapter in onBindViewHolder it is giving null pointer error in progressdialog.
OpensubcontentActivity
public class OpenSubContentActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context = this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}
}
}
}
vivcontentAdapter
In this activity i am calling async task class of opensubcontentactivity.But while calling from here in progress dialog it is giving error in asynctask class getData()
Using -
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
vivcontentAdapter
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String store_objectID = (String) OpenSubContentActivity.info_map.get(position);
if (store_objectID.startsWith("0b")) {
OpenSubContentActivity.top++;
OpenSubContentActivity.stack_info[OpenSubContentActivity.top] = store_objectID; OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
} else {
OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
}
Toast.makeText(context, "Open", Toast.LENGTH_SHORT).show();
}
});
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
}
}
}
}
Error-
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:22:04.228 10385-10385/reva.irving E/AndroidRuntime: FATAL EXCEPTION: main
Process: reva.irving, PID: 10385
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at reva.irving.OpenSubContentActivity$getData.onPreExecute(OpenSubContentActivity.java:103)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:620)
at android.os.AsyncTask.execute(AsyncTask.java:567)
at reva.irving.OpenSubContentActivity.call(OpenSubContentActivity.java:84)
at reva.irving.vivcontentAdapter$1.onClick(vivcontentAdapter.java:59)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
To perform clicks in a Recycler view you need to change your adapter. Add an interface to act as the click listener and implement it in your activity, like so:
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
private OnClickItem clickListener;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
public void setClickListener(OnClickItem listener){
this.listener = listener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
listener.onClickListItem(pos);
}
}
public interface OnClickItem{
void onClickListItem(int position);
}
}
Now in your activity you can catch the cliicks and run the async task:
public class OpenSubContentActivity extends AppCompatActivity implements vivcontentAdapter.OnClickItem{
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context=this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
vivcontentAdapteradapter.setClickListener(this);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void onClickListItem(int position){
new getData().execute();
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}
Related
I am trying to load data from an api online but am having an issue with the views loading. When I try to run the emulator, a blank screen shows up. Any idea why? I am guessing my issue is somewhere within how I am loading the gridview but I have not been able to figure it out.
MainActivity
public class MainActivity extends AppCompatActivity {
String SEARCH_TERM = "popular";
private RecyclerView mRecyclerView;
private MovieAdapter mMovieAdapter;
private GridLayoutManager gridLayoutManager;
private List<Movie> movieData;
/*
API KEY
https://api.themoviedb.org/3/movie/550?api_key=1f5029b7d824dee72f4d4a156dac90ed
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
movieData = new ArrayList<>();
loadMovieData();
}
private void loadMovieData() {
new FetchMovieTask().execute(SEARCH_TERM);
}
public class FetchMovieTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
final String MOVIES_RESULTS = "results";
final String MOVIES_POSTER_IMAGE = "poster_path";
final String MOVIES_TITLE = "title";
final String RELEASE_DATE = "release_date";
URL moviesUrl = NetworkUtils.buildUrl(SEARCH_TERM);
try {
String jsonMoviesResponse = NetworkUtils.getReponseFromHttpUrl(moviesUrl);
JSONObject moviesJson = new JSONObject(jsonMoviesResponse);
JSONArray moviesArray = moviesJson.getJSONArray(MOVIES_RESULTS);
for (int i = 0; i < moviesArray.length(); i++) {
String moviePoster;
String movieTitle;
String movieReleaseDate;
JSONObject movie = moviesArray.getJSONObject(i);
moviePoster = ("http://image.tmdb.org/t/p/w185/" + movie.getString(MOVIES_POSTER_IMAGE));
movieTitle = movie.getString(MOVIES_TITLE);
movieReleaseDate = movie.getString(RELEASE_DATE);
Log.i("MoviteTitle", movieTitle);
Log.i("ReleaseDate", movieReleaseDate);
Log.i("Image", moviePoster);
Movie data = new Movie(movieTitle, movieReleaseDate, moviePoster);
movieData.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
mMovieAdapter.notifyDataSetChanged();
}
}
}
Adapter Class
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieAdapterViewHolder>{
private List<Movie> mMovieData;
private Context context;
public MovieAdapter(Context context, List<Movie> movieData) {
this.context = context;
this.mMovieData = movieData;
}
#Override
public void onBindViewHolder(#NonNull MovieAdapterViewHolder holder, int position) {
holder.mTitleTextView.setText(mMovieData.get(position).getTitle());
holder.mReleaseDateTextView.setText(mMovieData.get(position).getDate());
Picasso.with(context).load(mMovieData.get(position).getMoviePoster()).into(holder.mImageView);
}
#NonNull
#Override
public MovieAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.cardview_item, parent, false);
return new MovieAdapterViewHolder(view);
}
#Override
public int getItemCount() {
if (null == mMovieData)
return 0;
return mMovieData.size();
}
public class MovieAdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mTitleTextView;
public final TextView mReleaseDateTextView;
public final ImageView mImageView;
public MovieAdapterViewHolder(View itemView) {
super(itemView);
mTitleTextView = itemView.findViewById(R.id.title_text_view);
mReleaseDateTextView = itemView.findViewById(R.id.release_date_text_view);
mImageView = itemView.findViewById(R.id.image_data);
}
}
}
Movie Class
public class Movie {
private String Title;
private String Date;
private String MoviePoster;
public Movie(String title, String date, String moviePoster) {
Title = title;
Date = date;
MoviePoster = moviePoster;
}
public Movie() {
}
public String getTitle() {
return Title;
}
public String getDate() {
return Date;
}
public String getMoviePoster() {
return MoviePoster;
}
public void setTitle(String title) {
Title = title;
}
public void setDate(String date) {
Date = date;
}
public void setMoviePoster(String moviePoster) {
MoviePoster = moviePoster;
}
}
Info : Java is all pass by value.
Issue : you are passing empty list reference to adapter and later initialising the list but in adapter it is still null so adapter will never receive the added value in list so do
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
movieData = new ArrayList<>();
//^^^^^^^^^^^^^^^^^^^^^^^^^ do it before
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
loadMovieData();
I have a local database that i want get res id from it(string saving) and show in application, also i have a recycler view and I want after click on items, display image.
public class AdapterApp extends RecyclerView.Adapter<AdapterApp.AdapterViewHolder>{
public static class AdapterViewHolder extends RecyclerView.ViewHolder{
public TextView txtDescription;
public ViewGroup layoutRoot;
public TextView txtTitle;
public ImageView imgDesc;
public AdapterViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDesc);
layoutRoot = (ViewGroup) itemView.findViewById(R.id.layoutRoot);
imgDesc = (ImageView) itemView.findViewById(R.id.imgDesc);
}
}
private ArrayList<StructApp> names = new ArrayList<StructApp>();
public AdapterApp(ArrayList<StructApp> names){
this.names = names;
}
#Override
public AdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = G.inflater.from(viewGroup.getContext()).inflate(R.layout.adapter_app,viewGroup,false);
return new AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(final AdapterViewHolder adapterViewHolder, final int i) {
final StructApp name = names.get(i);
adapterViewHolder.txtTitle.setText(name.title);
adapterViewHolder.layoutRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(G.currentActivity,ActivityDesc.class);
intent.putExtra("description",name.description);
G.currentActivity.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return names.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
database activity:
public class ActivityTitleEngineer extends ActivityEnhanced {
private RecyclerView recyclerView;
private AdapterApp adapter;
private ArrayList<StructApp> applications = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reshte_math);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(G.context);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
adapter = new AdapterApp(G.reshte);
populateFromDatabase();
recyclerView.setAdapter(adapter);
}
public void populateFromDatabase() {
G.reshte.clear();
DataBaseConnection db = new DataBaseConnection(this, "database", 4);
final SQLiteDatabase database = db.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM Reshte ", null);
while (cursor.moveToNext()) {
StructApp application = new StructApp();
application.description = cursor.getString(cursor.getColumnIndex("description"));
application.title = cursor.getString(cursor.getColumnIndex("title"));
application.imgDesc = cursor.getString(cursor.getColumnIndex("img"));
G.reshte.add(application);
}
cursor.close();
}
}
activity of display image:
public class ActivityDesc extends AppCompatActivity {
private TextView txtDesc;
private ImageView imgDesc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reshte_desc);
txtDesc = (TextView) findViewById(R.id.txtDesc);
imgDesc = (ImageView) findViewById(R.id.imgDesc);
Bundle extras = getIntent().getExtras();
if(extras!= null){
String desc = extras.getString("description");
txtDesc.setText(desc);
}
}
}
Try this method :)
StorageReference islandRef = MainGameFragment.storageReference.child("Capture.PNG");
final long ONE_MEGABYTE = 1024 * 1024;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
ByteArrayInputStream imageStream = new ByteArrayInputStream(bytes);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
imageSettings.setImageBitmap(bitmap);
settingsText4.setText("Click to visit site for more information");
settingsText4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "site";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
mProgress.setVisibility(View.GONE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
I have a RecyclerView inside a Fragment within Activity. I need to refresh my RecyclerView from Activity. I added a method inside Fragment which called notifyDatasetChanged to refresh RecyclerView. But notifyDatasetChanged didn't work.
Here is my Fragment.
public class CategoryFragment extends Fragment{
private RecyclerView recyclerView;
private EventsAdapter adapter;
static Context context = null;
private List<Category> categories;
private List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!checkDatabase()){
copyDatabase();
}
context = getActivity();
dbHandler = new ReminderDatabase(context);
fillAllItems();
}
public void fillAllItems(){
categories = dbHandler.getAllCategory();
for(int i=0;i<categories.size();i++){
Category category = categories.get(i);
Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
allItems.add(categoryItem);
List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
for(int j=0;j<events.size();j++){
Event e = events.get(j);
Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
allItems.add(eventItem);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.category_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
adapter = new EventsAdapter(getContext(),allItems);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
public boolean checkDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/";
String filename = "Remind";
File file = new File(path+filename);
Log.d("Database","File exists -> "+file.exists());
return file.exists();
}
public void copyDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
ReminderDatabase dbHandler = new ReminderDatabase(getContext());
dbHandler.getWritableDatabase();
InputStream fin;
OutputStream fout;
byte[] bytes = new byte[1024];
try {
fin = getActivity().getAssets().open("Remind");
fout = new FileOutputStream(path);
int length=0;
while((length = fin.read(bytes))>0){
fout.write(bytes,0,length);
}
fout.flush();
fout.close();
fin.close();
Log.d("Database","successfully copied database");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
}
}
#Override
public void onResume() {
super.onResume();
allItems.clear();
Log.d("TAG","onresume");
fillAllItems();
adapter.notifyDataSetChanged();
}
public void refresh(){
Log.d("c",allItems.size()+"");
allItems.clear();
fillAllItems();
Log.d("c",allItems.size()+"");
adapter.notifyDataSetChanged();
}
}
I called refresh method from MainActivity.
#Override
public void onInserted() {
fragment.refresh();
}
My Adapter is here.
public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;
public EventsAdapter(Context context,List<Item> allItems){
this.context = context;
hideOrShowListener =(HideOrShowListener) context;
this.allItems = allItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType){
case CATEGORY_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
return new CategoryViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
return new EventViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = allItems.get(position);
switch (item.getType()){
case CATEGORY_TYPE:
((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));
((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,false);
}
});
break;
case EVENT_TYPE:
String[] time = item.getTime().trim().split(":");
int hour = Integer.parseInt(time[0]);
((EventViewHolder)holder).tvEventName.setText(item.getTitle());
((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
((EventViewHolder)holder).tvPlace.setText(item.getPlace());
if(item.getDescription().length()==0) {
item.setDescription("No Detail");
}
((EventViewHolder)holder).tvDescription.setText(item.getDescription());
if(item.isShow()){
((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
((EventViewHolder)holder).descriptionLayout.setSelected(true);
((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
((EventViewHolder)holder).eventContainer.setSelected(true);
}else{
((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
((EventViewHolder)holder).descriptionLayout.setSelected(false);
((EventViewHolder)holder).eventContainer.setSelected(false);
((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
}
((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,true);
}
});
break;
}
}
#Override
public int getItemCount() {
Log.d("c",allItems.size()+"");
return allItems.size();
}
#Override
public int getItemViewType(int position) {
if(allItems!=null){
return allItems.get(position).getType();
}
return 0;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder{
private TextView tvCategoryTitle;
private View categoryColorIcon;
private ImageView imgAddEvent;
public CategoryViewHolder(View itemView) {
super(itemView);
tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
}
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout descriptionLayout;
private RelativeLayout eventContainer;
private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
public EventViewHolder(View itemView) {
super(itemView);
descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
eventContainer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(flag){
allItems.get(lastPosition).setShow(false);
}
allItems.get(getAdapterPosition()).setShow(true);
flag = true;
lastPosition = getAdapterPosition();
notifyDataSetChanged();
}
}
public interface HideOrShowListener{
public void setHideOrShow(Item item , boolean isEdit);
}
}
But when I click home button and reenter my application, my RecyclerView refresh. It means that notifyDatasetChanged in onResume method works. But in my refresh method, it doesn't work. How can I do this?
Are you sure this method is being called :
#Override
public void onInserted() {
fragment.refresh();
}
Make sure that you've a correct instance of the fragment. Or you can simply user interface with the refresh() method and implement it in the fragment.
Please I have been trying to display json data from recycler view to another activity but only the textview displays and the image does not. This is my code
public class MainActivity extends AppCompatActivity {
public String content;
public static MainActivity parse(JSONObject object){
MainActivity post=new MainActivity();
post.content = Html.fromHtml(object.optString("content")).toString();
return post;
}
ImageView thumbnail;
TextView title;
private static final String TAG = "RecyclerViewExample";
private SwipeRefreshLayout swipeRefreshLayout;
private List<FeedItem> feedsList;
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
private ProgressBar progressBar;
public MainActivity(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_list);
// Initialize recycler view
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
// Downloading data from below url
final String url = "http://street2view.com/api/get_recent_posts/";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
if (result == 1) {
adapter = new MyRecyclerAdapter(MainActivity.this, feedsList);
mRecyclerView.setAdapter(adapter);
} else {
Toast.makeText(MainActivity.this, "Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (item.getItemId() == R.id.about) {
Intent settingsActivityIntent = new Intent();
settingsActivityIntent.setClass(this, AboutActivity.class);
this.startActivityForResult(settingsActivityIntent, 111);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Quit")
.setMessage("Do you wish to exit the app?")
.setCancelable(false)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
}
public String stripHtmlTags(String html) {
return Html.fromHtml(html).toString();
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
feedsList = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("title"));
item.setContent(post.optString("content"));
item.setdate(post.optString("date"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
JSONArray categories = post.getJSONArray("categories");
if (null != categories && categories.length() > 0) {
JSONObject attachment = categories.getJSONObject(0);
if (categories != null)
item.setCategories(attachment.getString("title"));
}
feedsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and this is the adapter class in which i use to send the data from the recycler view to the second activity
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view,mContext, (ArrayList<FeedItem>) feedItemList);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
//Download image using picasso library
Glide.with(mContext).load(feedItem.getAttachmentUrl())
.error(R.color.list_item_title)
.placeholder(R.color.list_item_title)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText((feedItem.getTitle()));
customViewHolder.textView2.setText(feedItem.getdate());
customViewHolder.categories.setText(feedItem.getCategories());
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView imageView;
protected TextView textView2;
protected TextView textView;
protected TextView content;
protected TextView categories;
public RelativeLayout relativeLayout;
ArrayList<FeedItem> feeditem = new ArrayList<FeedItem>();
Context ctx;
public CustomViewHolder(View view, Context ctx, ArrayList<FeedItem> feeditem) {
super(view);
view.setOnClickListener(this);
this.ctx = ctx;
this.feeditem = feeditem;
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView2 = (TextView) view.findViewById(R.id.date);
this.categories = (TextView) view.findViewById(R.id.categories);
this.textView = (TextView) view.findViewById(R.id.title);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
FeedItem feeditem = this.feeditem.get(position);
Intent intent = new Intent(this.ctx,Main2Activity.class);
intent.putExtra("title",feeditem.getTitle());
intent.putExtra("content",feeditem.getContent());
Html.fromHtml(String.valueOf(intent.putExtra("content",feeditem.getContent()))).toString();
intent.putExtra("thumbnail",feeditem.getAttachmentUrl());
this.ctx.startActivity(intent);
}
}
}
and this is the second activity where i want to display the json data (when i run the application the textview shows but the imageview dosent thanks in advance)
public class Main2Activity extends AppCompatActivity {
ImageView imageView;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView)findViewById(R.id.contentImage);
textView = (TextView)findViewById(R.id.title2);
textView.setText(getIntent().getStringExtra("title"));
imageView.setImageResource(getIntent().getIntExtra("thumbnail", 00));
}}
You can try this
public class Main2Activity extends AppCompatActivity {
ImageView imageView;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView) findViewById(R.id.contentImage);
textView = (TextView) findViewById(R.id.title2);
String title = getIntent().getStringExtra("title");
String thumbnail = getIntent().getStringExtra("thumbnail");
textView.setText(title);
// set image here
Glide.with(this).load(thumbnail)
.into(imageView);
}
}
I've got problem with my ListView. I'm creating new object and add it to the database by clicking button in the first fragment. In the second fragment I've got listview with objects from my database. Everything works fine but listView in the second fragment doesn't refresh - I see new objects only after restarting app. All solutions like : notifyDataSetChanged don't work :/
Here's my adapter from first fragment:
public class ConcertAdapter extendsRecyclerView.Adapter<ConcertAdapter.MyViewHolder> {
private static final String FRAGMENT_TAG = "fragmentTag";
private static final String TAG = ConcertAdapter.class.getSimpleName() ;
private LayoutInflater inflater;
private Context context;
private List<Concert> concertList = new ArrayList<>();
private DatabaseHelper mDatabaseHelper = null;
private int selectedRecordPosition = -1;
private MainActivity mActivity;
public ConcertAdapter(Context context, List<Concert> concerts, MainActivity mainActivity) {
this.inflater = LayoutInflater.from(context);
this.concertList = concerts;
this.context = context;
this.mActivity = mainActivity;
}
public void setListConcert(ArrayList<Concert> concertList) {
this.concertList = concertList;
notifyItemRangeChanged(0, concertList.size());
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.from(parent.getContext()).inflate(R.layout.concert_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final float screenWidthPx = holder.itemView.getResources().getDisplayMetrics().widthPixels;
Concert current = concertList.get(position);
Log.d("mLog", current.getUrl());
holder.mImage.setImageUrl(current.getUrl(), MySingleton.getInstance().getImageLoader());
holder.mImage.getLayoutParams().height = (int) (screenWidthPx * 0.50);
holder.mFav_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
final Concert favConcert = new Concert();
favConcert.setTitle(concertList.get(position).getTitle());
favConcert.setContent(concertList.get(position).getContent());
favConcert.setDate(concertList.get(position).getDate());
favConcert.setUrl(concertList.get(position).getUrl());
try {
final Dao<Concert, Integer> concertDao = getHelper().getConcertDao();
concertDao.create(favConcert);
}catch (SQLException e) {
e.printStackTrace();
}
}
}
});
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date concertDate = new Date();
try {
concertDate = format.parse(current.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
DateTime dt = new DateTime();
DateTime currentDate = dt.withZone(DateTimeZone.forID("Europe/Warsaw"));
int days = Days.daysBetween(new DateTime(currentDate), new DateTime(concertDate)).getDays();
String s = String.valueOf(days);
holder.mDate_btn.setText(s + " dni");
if (s.equals("0")) {
holder.mDate_btn.setText("dziś :)");
}
}
#Override
public int getItemCount() {
return concertList.size();
}
public void setConcerts(List<Concert> concerts) {
concertList = new ArrayList<>(concerts);
}
public void showDisplay(int position) {
Bundle bundle = new Bundle();
bundle.putInt("position", position);
bundle.putString("content", concertList.get(position).getContent());
bundle.putString("date", concertList.get(position).getDate());
bundle.putString("url", concertList.get(position).getUrl());
bundle.putString("title", concertList.get(position).getTitle());
Fragment fragment = new DisplayConcertFragment();
fragment.setArguments(bundle);
mActivity.replaceFragment(fragment);
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public NetworkImageView mImage;
public Button mDate_btn;
public TextView mBubble;
public ToggleButton mFav_btn;
public ImageView mBubbleImage;
private ConcertFragment mConcertFragment;
public MyViewHolder(View itemView) {
super(itemView);
mImage = (NetworkImageView) itemView.findViewById(R.id.concerts_niv);
mDate_btn = (Button) itemView.findViewById(R.id.date_btn);
mImage.setOnClickListener(this);
mFav_btn = (ToggleButton) itemView.findViewById(R.id.fav_btn);
}
#Override
public void onClick(View v) {
showDisplay(getAdapterPosition());
//ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
}
public Concert removeItem(int position) {
final Concert concert = concertList.remove(position);
notifyItemRemoved(position);
return concert;
}
}
private DatabaseHelper getHelper() {
if (mDatabaseHelper == null) {
mDatabaseHelper = OpenHelperManager.getHelper(context,DatabaseHelper.class);
}
return mDatabaseHelper;
}
Here's my second adapter:
public class FavAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
private List mRecords;
private Dao<Concert, Integer> concertDao;
private Button mDateButton;
private NetworkImageView mImage;
public FavAdapter(Context context, int resource, List objects, Dao<Concert, Integer> concertDao) {
super(context, resource, objects);
this.mRecords = objects;
this.concertDao = concertDao;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = mInflater.inflate(R.layout.concert_item, parent, false);
if(mRecords.get(position).getClass().isInstance(new Concert())){
final Concert concert = (Concert) mRecords.get(position);
mImage =((NetworkImageView)convertView.findViewById(R.id.concerts_niv));
mImage.setImageUrl(concert.getUrl(), MySingleton.getInstance().getImageLoader());
final float screenWidthPx = mImage.getResources().getDisplayMetrics().widthPixels;
mImage.getLayoutParams().height = (int) (screenWidthPx * 0.50);
mDateButton = (Button) convertView.findViewById(R.id.date_btn);
Date concertDate = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
concertDate = format.parse(concert.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
DateTime dt = new DateTime();
DateTime currentDate = dt.withZone(DateTimeZone.forID("Europe/Warsaw"));
int days = Days.daysBetween(new DateTime(currentDate), new DateTime(concertDate)).getDays();
String s = String.valueOf(days);
mDateButton.setText(s + " dni");
if (s.equals("0")) {
mDateButton.setText("dziś :)");
}
// ((TextView)convertView.findViewById(R.id.teacher_tv)).setText(studentDetails.teacher.teacherName);
}
return convertView;
}
}
And here's my second fragment with ListView:
public class FavFragment extends Fragment {
private static final String TAG = FavFragment.class.getSimpleName() ;
private DatabaseHelper mDatabaseHelper = null;
private ListView mListView;
private int selectedRecordPosition = -1;
private Dao<Concert, Integer> concertDao;
private List<Concert> concertList;
private MainActivity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fav_layout, container, false);
mListView = (ListView)v.findViewById(R.id.concerts_lv);
mActivity = (MainActivity) getContext();
try {
concertDao = getHelper().getConcertDao();
concertList = concertDao.queryForAll();
FavAdapter adapter = new FavAdapter(getContext(), R.layout.concert_item, concertList, concertDao);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mListView.invalidateViews();
mListView.refreshDrawableState();
} catch (SQLException e) {
e.printStackTrace();
}
Log.e(TAG, "onCreateView notify");
return v;
}
private DatabaseHelper getHelper() {
if (mDatabaseHelper == null) {
mDatabaseHelper = OpenHelperManager.getHelper(getContext(), DatabaseHelper.class);
}
return mDatabaseHelper;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mDatabaseHelper != null) {
OpenHelperManager.releaseHelper();
mDatabaseHelper = null;
}
}
}
Here's my first fragment
public class ConcertFragment extends Fragment implements MyBackPressed {
private static final String FRAGMENT_TAG = "fragmentTag";
private static final String TAG = ConcertFragment.class.getSimpleName() ;
public ProgressBar progress;
private ConcertLoader concertLoader;
private RecyclerView recyclerView;
private Context mContext;
private android.support.v4.app.FragmentManager mFragmentManager;
private MainActivity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
JodaTimeAndroid.init(getContext());
View v = inflater.inflate(R.layout.fragment_concert_layout, container, false);
progress = (ProgressBar) v.findViewById(R.id.progressBar);
recyclerView = (RecyclerView) v.findViewById(R.id.concerts_rv);
concertLoader = new ConcertLoader(ConcertFragment.this);
mActivity = (MainActivity) getContext();
futureConcerts();
return v;
}
public void futureConcerts() {
concertLoader.execute();
getActivity().getWindow().getDecorView().getRootView().setClickable(false);
}
public void notifyAboutListCreation(List<Concert> res) {
ConcertAdapter adapter = new ConcertAdapter(getActivity().getApplicationContext(), res, mActivity);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
progress.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
getActivity().finish();
}
}
I had similar problems a while ago. Are you triggering any UI updates from non-UI threads? Maybe from within listeners? Try using the following code where the UI updates are triggered.
runOnUiThread(new Runnable(){
#Override
public void run(){
...
adapter.notifyDataSetChanged();
mListView.invalidateViews();
mListView.refreshDrawableState();
...
}
});
Personally, I now have started to wrap any problematic code blocks in a generic try-catch block that catches Exception and see if there are any exceptions I migh thave overseen (using logcat on terminal with tag filter).
(Cannot comment yet, so answering in this way)