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
Related
Everything works, but after I check the log it shows:
"E/RecyclerView: No adapter attached; skipping layout ".
My home fragment code:
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
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.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
I saw another question similar to this, that said to attach the adapter before running other threads but I don't believe I have any other threads running in this activity.
You start a new thread in this line:
new LoadLatestNews().execute(Constant.URL_LATEST);
and it is executed before control reaches:
recyclerView.setAdapter(adapterRecent);
This however should not be the problem you have since AsyncTask publishes to the UIThread.
Instead you should set an empty adapter in onCreateView and update it with adapterRecent.notifyDataSetChanged(); once you have loaded your data.
I have a ListView fragment that has the option to save specific table values. You can click a button to toggle the table to only show saved values. When the toggle is active instead of saving you have the option to delete values. I have noticed however that while the delete will delete the value permanently so long as the app is open, If i close the app and reopen it, the value will reappear. Also if I delete the app and reinstall this same value reappears. I'm not sure how this value is getting added in and why it refuses to go. Debugging shows me saving the correct values in SharedPreferences but that does not stay.
EDIT: After some more testing it appears that the first item saved in the specific SharedPreferences remains permanently saved. It cannot be removed and all other values saved will not remain there.
Fragment:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.os.StrictMode;
import com.tble.brgo.HTMLPull;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.text.TextUtils;
import java.util.HashSet;
import java.util.Set;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Websites#newInstance} factory method to
* create an instance of this fragment.
*/
public class Websites extends Fragment implements SearchView.OnQueryTextListener, displayInterface {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private SearchView mSearchView;
private ListView mListView;
public Boolean toggle = false;
public ArrayList<InfoArticle> mData = new ArrayList<InfoArticle>();
public StandardCellAdapter mAdapter;
public ArrayList<InfoArticle> fDataSet = new ArrayList<InfoArticle>();
public Websites webTable;
public Websites() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment Websites.
*/
// TODO: Rename and change types and number of parameters
public static Websites newInstance() {
Websites fragment = new Websites();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toggle = false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_websites, container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<InfoArticle> data = new ArrayList<InfoArticle>();
webTable = this;
try {
data = getData();
} catch (IOException e) {
e.printStackTrace();
}
mListView = (ListView) view.findViewById(R.id.WebsiteTable);
final StandardCellAdapter adapter = new StandardCellAdapter(getActivity(), data, 1,this);
fDataSet = data;
mData = data;
mListView.setAdapter(adapter);
mAdapter = adapter;
mSearchView = (SearchView) view.findViewById(R.id.searchView);
mListView.setTextFilterEnabled(true);
FloatingActionButton myFab = (FloatingActionButton) view.findViewById(R.id.dataToggle);
myFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggleView();
}
});
setupSearchView();
final SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.webRefresh);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
try {
mData = getData();
mAdapter = new StandardCellAdapter(getContext(), mData, 1,webTable);
mListView.setAdapter(mAdapter);
} catch (IOException e) {
e.printStackTrace();
}
swipeLayout.setRefreshing(false);
}
});
return view;
}
private void setupSearchView() {
mSearchView.setOnQueryTextListener(this);
mSearchView.setIconifiedByDefault(true);
}
private ArrayList<InfoArticle> getData() throws IOException {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
int school = sharedPref.getInt("School", 14273);
HTMLPull Connection = new HTMLPull();
Connection.getStaff(school);
Connection.Results.remove(0);
return Connection.Results;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText);
}
return true;
}
public ArrayList<InfoArticle> toData(ArrayList<String> t, ArrayList<String> d) {
ArrayList<InfoArticle> temp = new ArrayList<InfoArticle>();
if (t.size() == 0) {
temp.add(new InfoArticle("Slide to Save Teachers", "google.com"));
} else {
for (int i = 0; i < t.size(); i++) {
temp.add(new InfoArticle(t.get(i), d.get(i)));
}
}
return temp;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private void toggleView(){
if (!toggle) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
HashSet<String> defv = new HashSet<String>();
ArrayList<String> teachers = new ArrayList<String>(sharedPref.getStringSet("teachPref", defv));
ArrayList<String> links = new ArrayList<String>(sharedPref.getStringSet("linkPref", defv));
mAdapter = new StandardCellAdapter(getContext(), toData(teachers, links),2,this);
mListView.setAdapter(mAdapter);
toggle = true;
} else {
mAdapter = new StandardCellAdapter(getContext(), mData, 1,this);
mListView.setAdapter(mAdapter);
toggle = false;
}
}
/**public void displayWebpage(int position){
if (toggle == true) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(mAdapter.getItem(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
} else {
if (!mSearchView.isIconified()) {
for (InfoArticle a : fDataSet) {
if (a.title.equals(((InfoArticle) mListView.getAdapter().getItem(position)).title)) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(a.description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
} else {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(fDataSet.get(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
}*/
public void displayWebpage(String Link){
WebsiteDisplay fullView = WebsiteDisplay.newInstance(Link);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
CellAdapter:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.Image;
import android.nfc.Tag;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.view.View;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.graphics.Typeface;
import android.widget.Filterable;
import android.widget.Filter;
import org.w3c.dom.Text;
/**
* Created by Praveen on 8/21/16.
*/
public class StandardCellAdapter extends ArrayAdapter<InfoArticle> implements Filterable {
public ArrayList<InfoArticle> orig;
public ArrayList<InfoArticle> Teachers;
public SwipeRevealLayout swipeV;
public TextView deleteButton;
public TextView saveButton;
public int tableType;
public displayInterface activity;
public Context ct;
public StandardCellAdapter(Context context, ArrayList<InfoArticle> titles, int tableType, displayInterface inter) {
super(context, 0, titles);
this.Teachers = titles;
this.tableType = tableType;
saveButton = new TextView(context);
deleteButton = new TextView(context);
activity = inter;
ct = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String title = getItem(position).title;
String desc = getItem(position).description;
Holder TagHolder = null;
TextView Ctitle;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
if (tableType == 0) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.nclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
else if(tableType == 1){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.scSwipe);
saveButton = (TextView)convertView.findViewById(R.id.saveButton);
TagHolder.Save = saveButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
else{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.tclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.tcSwipe);
deleteButton = (TextView) convertView.findViewById(R.id.deleteButton);
TagHolder.Delete = deleteButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
}
else {
TagHolder = (Holder) convertView.getTag();
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
if(tableType == 1) {
TagHolder.Save.setTag(position);
TagHolder.Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTeacher((int)v.getTag());
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
else if(tableType == 2) {
TagHolder.Delete.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteTeacher((int)v.getTag());
if(Teachers.size() == 0)
Teachers.add(new InfoArticle("Slide to Save Teachers", "google.com"));
notifyDataSetChanged();
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
Typeface customFont = Typeface.SERIF;
Ctitle.setTypeface(customFont);
Ctitle.setText(title);
return convertView;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<InfoArticle> results = new ArrayList<InfoArticle>();
if (orig == null)
orig = Teachers;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final InfoArticle g : orig) {
if (g.title.toLowerCase()
.contains(constraint.toString().toLowerCase())) {
results.add(g);
}
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
Teachers = (ArrayList<InfoArticle>)results.values;
notifyDataSetChanged();
}
};
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public ArrayList<InfoArticle> toIA(ArrayList<String> data){
ArrayList<InfoArticle> converted = new ArrayList<InfoArticle>();
for(String a: data)
{
converted.add(new InfoArticle(a,""));
}
return converted;
}
#Override
public int getCount() {
return Teachers.size();
}
#Override
public InfoArticle getItem(int position) {
return Teachers.get(position);
}
public void saveTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
teach.add(Teachers.get(position).title);
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
link.add(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
new AlertDialog.Builder(getContext())
.setTitle("Teacher Saved")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(true);
}
private void deleteTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
teach.remove(Teachers.get(position).title);
link.remove(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
HashSet<String> defv = new HashSet<String>();
Teachers.remove(position);
new AlertDialog.Builder(getContext())
.setTitle("Teacher Deleted")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(false);
}
class Holder{
TextView Delete;
TextView Save;
TextView Cell;
}
}
I have an app that uses RecyclerView. When user selects "Add New Row" from the options menu, I output a test message to the screen, and some values get appended to two different ArrayLists. That part is working great, as I have confirmed these values are successfully added by looking at the ArrayList values using the debugger.
Anyhow I am not able to get the RecyclerView to redraw the screen and show the new information. My attempt to redraw / update the screen is by using this code (line 78 of MainActivity.java):
//call notify data set changed method for the adapter
adapter.notifyDataSetChanged();
Maybe I am not calling notifyDataSetChanged on the same adapter that actually is used for RecycleView??
Here is the complete code for MainActivity.java (see options menu code at end):
package com.joshbgold.ironmax;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int ADD_ROW = 1; //used for case statement statement to select menu item
private RecyclerView recyclerView;
public Exercises exercises = new Exercises();
public ExerciseRow adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
assert getSupportActionBar() != null;
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.barbell);
actionBar.setTitle(" " + "Iron Max");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//ExerciseRow adapter = new ExerciseRow(this);
adapter = new ExerciseRow(this);
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/* MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_row, menu);
return super.onCreateOptionsMenu(menu);*/
menu.add(0, ADD_ROW, 0, "Add New Row");
menu.getItem(0).setIcon(R.drawable.plus);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setIcon(R.drawable.plus);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int length;
switch (item.getItemId()) {
case 1:
Toast msg = Toast.makeText(MainActivity.this, "Test code for adding an exercise", Toast.LENGTH_LONG);
msg.show();
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
length = exercises.getExercisesArrayLength();
//call notify data set changed method for the adapter
adapter.notifyItemInserted(length - 1);
adapter.notifyDataSetChanged();
return super.onOptionsItemSelected(item);
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is Exercises.java:
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
public class Exercises extends AppCompatActivity {
public ArrayList<String> exercisesArrayList = new ArrayList<>(); //stores all the lifts
private ArrayList<Integer> personalBestsArrayList = new ArrayList<>(); //stores personal bests in pounds
public ArrayList<String> getExercisesArray() { //returns the whole exercises arraylist
return exercisesArrayList;
}
public ArrayList<Integer> getPersonalBests() { //returns the whole personal bests arraylist
return personalBestsArrayList;
}
public String getExercise(int position) { //returns individual exercise from array
return exercisesArrayList.get(position);
}
public void addExercise(String exercise) {
exercisesArrayList.add(exercise);
}
public void removeExercise(int position) {
exercisesArrayList.remove(position);
}
public void editExercise(int position, String exercise) {
exercisesArrayList.set(position, exercise);
}
public int getExercisesArrayLength() {
return exercisesArrayList.size();
}
public Integer getPersonalBest(int position) { //returns individual personal best from array
return personalBestsArrayList.get(position);
}
public void addPersonalBest(int personalBest) {
personalBestsArrayList.add(personalBest);
}
public void removePersonalBest(int position) {
personalBestsArrayList.remove(position);
}
public void editPersonalBest(int position, int personalBest) {
personalBestsArrayList.set(position, personalBest);
}
public Exercises() {} //constructor
}
Here is ExerciseRow.java:
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class ExerciseRow extends RecyclerView.Adapter<ExerciseRow.ExerciseViewHolder> {
String exerciseName = "burpee";
String exercisePR = "100"; // user's personal record for this exercise in pounds
private Context context;
Exercises exercises = new Exercises();
public ExerciseRow(Context context) {
this.context = context;
}
#Override
public ExerciseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.exercise_list_item, parent, false);
return new ExerciseViewHolder(view);
}
#Override
public void onBindViewHolder(ExerciseViewHolder holder, int position) {
ArrayList<String> exercisesArray = exercises.getExercisesArray();
holder.bindExercises(exercisesArray.get(position));
}
#Override
public int getItemCount() {
return exercises.getExercisesArrayLength();
}
public class ExerciseViewHolder extends RecyclerView.ViewHolder {
public TextView exerciseNameTextView;
public TextView personalRecordTextView;
public ImageView edit_Icon;
public ImageView percentages_Icon;
public ImageView trash_Icon;
public ImageView plus_icon;
public ImageView facebook_icon;
public ImageView twitter_icon;
public ExerciseViewHolder(View itemView) {
super(itemView);
exerciseNameTextView = (TextView) itemView.findViewById(R.id.list_item_exercise_textview);
personalRecordTextView = (TextView) itemView.findViewById(R.id.list_item_amount_textview);
edit_Icon = (ImageView) itemView.findViewById(R.id.list_item_pencil);
percentages_Icon = (ImageView) itemView.findViewById(R.id.list_item_percent);
trash_Icon = (ImageView) itemView.findViewById(R.id.list_item_trash);
plus_icon = (ImageView) itemView.findViewById(R.id.list_item_plus);
facebook_icon = (ImageView) itemView.findViewById(R.id.list_item_facebook);
twitter_icon = (ImageView) itemView.findViewById(R.id.list_item_twitter);
View.OnClickListener plus = new View.OnClickListener() {
#Override
public void onClick(View view) {
// allow user to add a new exercise and personal best
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
notifyDataSetChanged();
}
};
View.OnClickListener edit = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be edited.", Toast.LENGTH_LONG).show();
}
else{
editRow(position); //edit the row at the current position
notifyDataSetChanged();
}
}
};
View.OnClickListener percentages = new View.OnClickListener() {
#Override
public void onClick(View view) {
//get exercise name
exerciseName = exerciseNameTextView.getText().toString();
exercisePR = personalRecordTextView.getText().toString();
//show percentages layout
startPercentagesActivity(exerciseName, exercisePR);
}
};
View.OnClickListener trash = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be deleted.", Toast.LENGTH_LONG).show();
} else {
exercises.removeExercise(position);
exercises.removePersonalBest(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, exercises.getExercisesArrayLength());
}
}
};
plus_icon.setOnClickListener(plus);
edit_Icon.setOnClickListener(edit);
percentages_Icon.setOnClickListener(percentages);
trash_Icon.setOnClickListener(trash);
}
public void bindExercises(String exercises) {
Exercises exercisesObject = new Exercises();
exerciseNameTextView.setText(exercisesObject.getExercise(getAdapterPosition()));
personalRecordTextView.setText((exercisesObject.getPersonalBest(getAdapterPosition())).toString() + " pounds");
}
}
private void startPercentagesActivity(String some_exercise, String personal_record) {
Intent intent = new Intent(context, PercentagesActivity.class);
intent.putExtra("exerciseName", some_exercise);
intent.putExtra("personalRecord", personal_record);
context.startActivity(intent);
}
protected void editRow(final int position) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final View textEntryView = layoutInflater.inflate(R.layout.text_entry, null);
final EditText liftName = (EditText) textEntryView.findViewById(R.id.liftNameEditText);
final EditText PersonalBestInPounds = (EditText) textEntryView.findViewById(R.id.personalBestEditText);
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setIcon(R.mipmap.barbell)
.setTitle("Please make your changes:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//retrieve the user's input
String lift = liftName.getText().toString();
int personalBest = Integer.parseInt(PersonalBestInPounds.getText().toString());
//save the user's input to the appropriate arrays
exercises.editExercise(position, lift);
exercises.editPersonalBest(position, personalBest);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
}
}
If you have read this far, I give you credit! Please understand I am completely new to RecyclerView, so whatever error(s) I have made could be something quite simple even.
The issue is that you have two different instances of ExercisesOne in MainActivity and another in ExerciseRow You are adding the data to the wrong one.
A few other things that may help you along your way.
Exercises Should not extend AppCompatActivity (or really anything as far as I can tell)
You should avoid saving a reference to the context (as you are doing in Exercises) it can great memory issues. Instead try one of the following.
A. Use the context to get the LayoutInflater in the constructor
B. Call parent.getContext() in onCreateViewHolder
I am having problem with fragments.I am developing an app like 360 security and i am having problem implementing fragments ,getting "Binary XML file line #1: Error inflating class fragment".
Here is my xml file.I have tried every solution please help me.
Thanks in advance.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_list"
android:name="sabby.completesecurity.MainListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ItemListActivity"
tools:layout="#android:layout/list_content" />
This is my activity file:
package sabby.completesecurity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.ImageView;
import sabby.completesecurity.R;
public class MainActivityCache extends FragmentActivity implements sabby.completesecurity.MainCallbacks {
private boolean mIsDualPane;
private boolean mIsArtShowed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cache);
mIsDualPane = findViewById(R.id.item_detail_container) != null;
//Show an art when no fragment is showed, we make sure no detail fragment is present.
if (mIsDualPane && getFragmentManager().findFragmentByTag(sabby.completesecurity.DetailFragment.FRAGMENT_TAG) == null) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
((FrameLayout) findViewById(R.id.item_detail_container)).addView(imageView);
mIsArtShowed = true;
}
}
#Override
public void onItemSelected(String packageName) {
if (mIsDualPane) {
//Hide art when a fragment is showed.
if (mIsArtShowed) {
((FrameLayout) findViewById(R.id.item_detail_container)).removeAllViews();
mIsArtShowed = false;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.item_detail_container, DetailFragment.getInstance(packageName), DetailFragment.FRAGMENT_TAG)
.commit();
} else {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(DetailFragment.EXTRA_PACKAGE_NAME, packageName);
startActivity(intent);
}
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(receiver, getIntentFilter());
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
private void showAboutDialog() {
new AlertDialog.Builder(this)
.setTitle("About")
.setView(getLayoutInflater().inflate(R.layout.about_dialog_message, null))
.setNegativeButton(android.R.string.ok, null)
.show();
}
/**
* Used to update the list if a package is added or removed.
*/
private IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addDataScheme("package");
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
return filter;
}
enter code here
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
MainListFragment mainListFragment = (MainListFragment) getFragmentManager().findFragmentById(R.id.item_list);
if (mainListFragment != null)
mainListFragment.loadList();
}
};
}
MainListFragment.java
package sabby.completesecurity;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.Formatter;
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.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.Spinner;
import android.widget.TextView;
import sabby.completesecurity.utils.Utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MainListFragment extends ListFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
private static final int SORT_NAME = 0;
private static final int SORT_PKG = 1;
private static final int SORT_DOMAIN = 2;
private static final int SORT_INSTALLATION = 3;
private static final int SORT_SIZE = 4;
private static final String INSTANCE_STATE_SORT_BY = "sort_by";
private Adapter mAdapter;
private List<Item> mItemList = new ArrayList<Item>();
private int mOnSizeFinishedItemCount;
private PackageManager mPackageManager;
private ProgressDialog mProgressDialog;
private LayoutInflater mLayoutInflater;
private MainCallbacks mCallbacks;
private Context mContext;
private Async mAsyncLoader;
private Spinner mSpinner;
private boolean mSpinnerListenerAuthorized;
private SimpleDateFormat mSimpleDateFormat;
private int mSortBy = 0;
class Item {
ApplicationInfo applicationInfo;
String label;
Long date;
Long size = -1L;
}
private int mColorGrey1;
private int mColorGrey2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.loading_apps);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
//Used to prevent message not showing later
mProgressDialog.setMessage("");
mPackageManager = mContext.getPackageManager();
mSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
mColorGrey1 = getResources().getColor(R.color.grey_1);
mColorGrey2 = getResources().getColor(R.color.grey_2);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayShowCustomEnabled(true);
mSpinner = new Spinner(actionBar.getThemedContext());
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(actionBar.getThemedContext(),
R.array.sort_spinner_items, android.R.layout.simple_list_item_1);
mSpinner.setAdapter(spinnerAdapter);
mSpinnerListenerAuthorized = false;
mSpinner.setOnItemSelectedListener(this);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
actionBar.setCustomView(mSpinner, layoutParams);
if (savedInstanceState != null)
setSortBy(savedInstanceState.getInt(INSTANCE_STATE_SORT_BY, -1), false);
}
#Override
public void onStart() {
super.onStart();
mSpinner.setSelection(mSortBy);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(INSTANCE_STATE_SORT_BY, mSortBy);
}
private void onTaskEnded(List<Item> list) {
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager().findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
retainedFragment.setList(list);
mItemList = list;
mAdapter.notifyDataSetChanged();
if (getListView().getAdapter() == null)
setListAdapter(mAdapter);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setOnItemClickListener(this);
getListView().setFastScrollEnabled(true);
mAdapter = new Adapter();
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager()
.findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
if (retainedFragment == null) {
retainedFragment = new RetainedFragment();
getFragmentManager()
.beginTransaction()
.add(retainedFragment, RetainedFragment.FRAGMENT_TAG)
.commit();
}
if (retainedFragment.getList() != null) {
onTaskEnded(retainedFragment.getList());
mOnSizeFinishedItemCount = mItemList.size();
//Notify spinner that size sort is available
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
} else
loadList();
}
public void loadList() {
mAsyncLoader = new Async();
mAsyncLoader.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (MainCallbacks) activity;
mContext = activity;
mLayoutInflater = activity.getLayoutInflater();
}
#Override
public void onDetach() {
super.onDetach();
if (mAsyncLoader != null)
mAsyncLoader.cancel(true);
mCallbacks = null;
mContext = null;
mLayoutInflater = null;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (mCallbacks != null)
mCallbacks.onItemSelected(mItemList.get(i).applicationInfo.packageName);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_main_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
loadList();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (mSpinnerListenerAuthorized)
setSortBy(i, true);
mSpinnerListenerAuthorized = true;
}
/**
* Sort main list if provided value is valid.
* #param sort Must be one of SORT_*
* #param checkViews Set if views have to be updated, eg. when restoring state, views aren't
* created yet, so value must be false
*/
public void setSortBy(int sort, boolean checkViews) {
if (sort >= SORT_NAME && sort <= SORT_SIZE) {
mSortBy = sort;
if (checkViews) {
checkFastScroll();
sortApplicationList(mItemList, mSortBy);
mAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
private void checkFastScroll() {
getListView().setFastScrollEnabled(mSortBy == SORT_NAME);
}
public void sortApplicationList(List<Item> list, final int sortBy) {
Collections.sort(list, new Comparator<Item>() {
#Override
public int compare(Item item1, Item item2) {
switch (sortBy) {
case SORT_NAME:
return item1.label.compareTo(item2.label);
case SORT_PKG:
return item1.applicationInfo.packageName.compareTo(item2.applicationInfo.packageName);
case SORT_DOMAIN:
boolean isSystem1 = (item1.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
boolean isSystem2 = (item2.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
return Utils.compareBooleans(isSystem1, isSystem2);
case SORT_INSTALLATION:
//Sort in decreasing order
return -item1.date.compareTo(item2.date);
case SORT_SIZE:
return -item1.size.compareTo(item2.size);
default:
return 0;
}
}
});
}
/**
* This method is called by each item when it has finished retrieving its size
* When all items have finished, we set size sort available in spinner, and invalidate
* main list to display sizes in UI.
*/
private void onItemFinishedSizeProcess() {
mOnSizeFinishedItemCount ++;
if (mOnSizeFinishedItemCount == mItemList.size()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
mAdapter.notifyDataSetChanged();
}
});
}
}
class Adapter extends BaseAdapter implements SectionIndexer {
class ViewHolder {
ImageView icon;
TextView label;
TextView packageName;
TextView version;
TextView isSystemApp;
TextView date;
TextView size;
IconAsyncTask iconLoader;
}
String sections = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#Override
public int getCount() {
return mItemList.size();
}
#Override
public Object getItem(int i) {
return mItemList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = mLayoutInflater.inflate(R.layout.main_list_item, null);
holder = new ViewHolder();
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.label = (TextView) view.findViewById(R.id.label);
holder.packageName = (TextView) view.findViewById(R.id.packageName);
holder.version = (TextView) view.findViewById(R.id.version);
holder.isSystemApp = (TextView) view.findViewById(R.id.isSystem);
holder.date = (TextView) view.findViewById(R.id.date);
holder.size = (TextView) view.findViewById(R.id.size);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
holder.iconLoader.cancel(true);
}
view.setBackgroundColor(i % 2 == 0 ? mColorGrey2 : mColorGrey1);
Item item = mItemList.get(i);
ApplicationInfo info = item.applicationInfo;
try {
PackageInfo packageInfo = mPackageManager.getPackageInfo(info.packageName, 0);
holder.version.setText(packageInfo.versionName);
Date date = new Date(packageInfo.firstInstallTime);
holder.date.setText(mSimpleDateFormat.format(date));
} catch (PackageManager.NameNotFoundException e) {
//Do nothing
}
holder.iconLoader = new IconAsyncTask(holder.icon, info);
holder.iconLoader.execute();
holder.label.setText(info.loadLabel(mPackageManager));
holder.packageName.setText(info.packageName);
boolean isSystemApp = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
holder.isSystemApp.setText(isSystemApp ? getString(R.string.system) : getString(R.string.user));
if (item.size != -1L)
holder.size.setText(Formatter.formatFileSize(getActivity(), item.size));
return view;
}
#Override
public int getPositionForSection(int section) {
for (int i = 0; i < this.getCount(); i++) {
String item = mItemList.get(i).label;
if (item.charAt(0) == sections.charAt(section))
return i;
}
return 0;
}
#Override
public int getSectionForPosition(int i) {
return 0;
}
#Override
public Object[] getSections() {
String[] sectionsArr = new String[sections.length()];
for (int i = 0; i < sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);
return sectionsArr;
}
class IconAsyncTask extends AsyncTask<Void, Integer, Drawable> {
ImageView imageView;
ApplicationInfo info;
IconAsyncTask(ImageView imageView, ApplicationInfo info) {
this.imageView = imageView;
this.info = info;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
imageView.setVisibility(View.INVISIBLE);
}
#Override
protected Drawable doInBackground(Void... voids) {
if (!isCancelled())
return info.loadIcon(mPackageManager);
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
super.onPostExecute(drawable);
imageView.setImageDrawable(drawable);
imageView.setVisibility(View.VISIBLE);
}
}
}
class SpinnerAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResId;
private String[] mItems;
public SpinnerAdapter(Context themedContext, int arrayResId, int layoutResId) {
mContext = themedContext;
mItems = themedContext.getResources().getStringArray(arrayResId);
mLayoutResId = layoutResId;
}
#Override
public int getCount() {
return mItems.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
//It make no sense to implement recycled view system because there is only 5 items in list
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = View.inflate(mContext, mLayoutResId, null);
if (view instanceof TextView)
((TextView) view).setText(mItems[i]);
return view;
}
/**
* Set sort_by_size item disabled if all items haven't retrieved them size.
*/
#Override
public boolean isEnabled(int position) {
return position != SORT_SIZE || mItemList != null && mOnSizeFinishedItemCount == mItemList.size();
}
}
class Async extends AsyncTask<Void, Async.Progress, List<Item>> {
class Progress {
String label;
int totalSize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected List<Item> doInBackground(Void... voids) {
List<ApplicationInfo> applicationInfos = mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Progress progress = new Progress();
progress.totalSize = applicationInfos.size();
List<Item> itemList = new ArrayList<Item>(applicationInfos.size());
mOnSizeFinishedItemCount = 0;
for (ApplicationInfo applicationInfo : applicationInfos) {
if (isCancelled())
break;
Item item = new Item();
item.applicationInfo = applicationInfo;
String label = applicationInfo.loadLabel(mPackageManager).toString();
item.label = label;
try {
item.date = mPackageManager.getPackageInfo(applicationInfo.packageName, 0).firstInstallTime;
} catch (PackageManager.NameNotFoundException e) {
item.date = 0L;
}
itemList.add(item);
getItemSize(item);
progress.label = label;
publishProgress(progress);
}
sortApplicationList(itemList, mSortBy);
return itemList;
}
private void getItemSize(final Item item) {
try {
Method getPackageSizeInfo = mPackageManager.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(mPackageManager, item.applicationInfo.packageName, new IPackageStatsObserver.Stub() {
#Override
public void onGetStatsCompleted(final PackageStats pStats, boolean succeeded)
throws RemoteException {
if (succeeded)
item.size = pStats.codeSize + pStats.cacheSize + pStats.dataSize
+ pStats.externalCodeSize + pStats.externalCacheSize + pStats.externalDataSize
+ pStats.externalMediaSize + pStats.externalObbSize;
else
item.size = -1L;
onItemFinishedSizeProcess();
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (IllegalAccessException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (InvocationTargetException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
}
}
#Override
protected void onProgressUpdate(Progress... values) {
super.onProgressUpdate(values);
Progress progress = values[0];
mProgressDialog.setMessage(progress.label);
if (mProgressDialog.getMax() == 100)
mProgressDialog.setMax(progress.totalSize);
mProgressDialog.incrementProgressBy(1);
}
#Override
protected void onPostExecute(List<Item> list) {
super.onPostExecute(list);
mProgressDialog.hide();
onTaskEnded(list);
}
#Override
protected void onCancelled(List<Item> list) {
super.onCancelled(list);
mProgressDialog.hide();
}
}
}
In the xml that you have posted,replace the TAG <Fragment> with <LinearLayout> or <RelativeLayout> and inside this you simply show what you want to display in you UI
Make sure you extend Fragment class in you fragment activity
Could you post the code for your fragment? The problem could be with your import statements. You have 'import android.support.v4.app.FragmentActivity'. Do you have 'import android.support.v4.app.Fragment' in your fragment file?
I'm making a parse json app and i've got an issue !
I've got these codes :
Temps.java :
package model;
public class Temps {
private String direction;
private String ligne;
private String temps;
public Temps() {
}
public Temps(String direction, String ligne, String temps) {
this.direction = direction;
this.ligne = ligne;
this.temps = temps;
}
public String getDirection() {
return direction;
}
public void setDirection(String thumbnailUrl) {
this.direction = thumbnailUrl;
}
public String getTemps() {
return temps;
}
public void setTemps(String temps) {
this.temps = temps;
}
public String getLigne() {
return ligne;
}
public void setLigne(String ligne) {
this.ligne = ligne;
}
}
TempsActivity.java :
package activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
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.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.pierre.tan.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import adapter.CustomListAdapterTemps;
import app.AppController;
import model.Temps;
public class TempsActivity extends ActionBarActivity {
private Toolbar mToolbar;
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private List<Temps> directionList = new ArrayList<Temps>();
private ListView listView2;
private CustomListAdapterTemps adapter;
private SwipeRefreshLayout swipeLayout;
private Menu menu;
private MenuInflater inflater;
HashMap<String, String> lieumap = new HashMap<String, String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_temps, container, false);
// Inflate the layout for this fragment
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
System.out.println(intent.getExtras().getString("text") + " Test Test ");
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(getParent(), directionList);
listView2.setAdapter(adapter);
// Showing progress dialog before making http request
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Toast.makeText(getApplication(), "Rechargement...", Toast.LENGTH_SHORT).show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
swipeLayout.setRefreshing(false);
}
});
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_search) {
String title = getString(R.string.app_name);
Fragment fragment = null;
fragment = new ArretsFragment();
title = "Rechercher";
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temps);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(this, directionList);
listView2.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
}
And CustomListViewAdapterTemps.java :
package adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.example.pierre.tan.R;
import java.util.List;
import app.AppController;
import model.Temps;
public class CustomListAdapterTemps extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Temps> directionItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterTemps(Activity activity, List<Temps> directionItems) {
this.activity = activity;
this.directionItems = directionItems;
}
#Override
public int getCount() {
return directionItems.size();
}
#Override
public Object getItem(int location) {
return directionItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rowtemps, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView direction = (TextView) convertView.findViewById(R.id.direction);
TextView ligne = (TextView) convertView.findViewById(R.id.ligne);
TextView temps = (TextView) convertView.findViewById(R.id.temps);
// getting movie data for the row
Temps m = directionItems.get(position);
// title
direction.setText(m.getDirection());
ligne.setText(m.getLigne());
temps.setText(m.getTemps());
return convertView;
}
}
I don't understand why I get a Blank ListView because the url json work and in the console we can see just the json Request with the data. If someone can help me it would be very nice!
That's because your directionList is empty. In your loops, where you parse JSON, you're creating your Temps object:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
but you're not adding them to your directionsList. Add this line just after the above:
directionList.add(temps);
Hi i think that you are not adding your response to the list, please try this:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
directionList.add(temps);