ViewPager, FragmentStatePagerAdapter, ListFragment separate list data for each Fragment - java

I have a ViewPager with a dynamic number of pages in it. Each of these pages needs to read from a db and display the dataset for that page.
I compare the currently selected pages title with the first value in the db "username" to check if the data is relevant for that page.
My fragments though dont display the data correctly. Im trying to set an arrayAdapter in the onCreateView, but its not called on the creation of each fragment. In my test case, I have three fragments, user1, user2, user3. onCreateView is called on user1 originally, then is only called again when I swipe back to user2, and never again for user1 or user3.
I need to be able to set the arrayAdapter for each fragment specifically because each one will have a different array of values to display.
PagerAdapter
public class ExamplePagerAdapter extends FragmentStatePagerAdapter implements TitleProvider{
private Map<Integer, UserFragment> mPageReferenceMap = new HashMap<Integer, UserFragment>();
public ExamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return user;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new UserFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public String getTitle(int pos) {
return "#"+users[pos].getName();
}
#Override
public void destroyItem(View container, int position, Object object) {
mPageReferenceMap.remove(Integer.valueOf(position));
}
}
UserFragment
public class UserFragment extends ListFragment {
Context ctx;
View v;
Button mAddEntry;
static int p;
static ArrayList<String> entryArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ctx = container.getContext();
if (v != null)
return v;
v = inflater.inflate(R.layout.user_fragment, container, false);
mAddEntry = (Button) v.findViewById(R.id.entry_b);
mAddEntry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putInt("pos", p);
Intent mi = new Intent(v.getContext(), EntryAdd.class);
mi.putExtras(b);
startActivity(mi);
}
});
updateUserFrag();
return v;
}
public void updateUserFrag () {
entryArray = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
final DBAdapter db = new DBAdapter(ctx);
db.open();
Cursor c = db.getAllEntries();
try {
while (c.moveToNext()) {
if (c.getString(0).equals(MainActivity.users[p].getName())) {
sb.append(c.getString(1));
entryArray.add(sb.toString());
}
}
} catch (Exception e) {}
c.close();
db.close();
ArrayAdapter<String> a = new ArrayAdapter<String>(ctx, android.R.layout.simple_list_item_1, entryArray);
setListAdapter(a);
}
}
Basically, I just need a method I can use to give each fragment its data when its created. onCreateView() doesnt get called for each fragment, so thats no use for me.
UPDATE
I think I've almost got it, but I cant figure out this last part. Im using TitlePageIndicators onPageSelected method to send data to my fragment handler.
TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager, 0);
indicator.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Message msg = UserFragment.handy.obtainMessage();
Bundle b = new Bundle();
b.putInt("m", 0);
b.putInt("p", position);
b.putStringArrayList("e", updateUserFrag(position));
msg.setData(b);
UserFragment.handy.handleMessage(msg);
}
Handler
static Handler handy = new Handler() {
public void handleMessage(Message msg) {
int p = msg.getData().getInt("p");
int m = msg.getData().getInt("m");
ArrayList<String> e = msg.getData().getStringArrayList("e");
switch (m) {
case 0:
Log.d("HANDLER", Integer.toString(p));
for (int i=0;i<e.size();i++) {
//Log.d("ENTRY", e.get(i));
}
break;
}
}
};
The problem is that by the time the handler is called, the Arrayadapter has already been set, and I can find a way to trigger a refresh of that data.

#Override
public void onPageSelected(int position) {
Message msg = UserFragment.handy.obtainMessage();
Bundle b = new Bundle();
b.putInt("m", 0);
b.putInt("p", position);
b.putStringArrayList("e", updateUserFrag(position));
msg.setData(b);
UserFragment.handy.handleMessage(msg);
}
public ArrayList<String> updateUserFrag (int p) {
entryArray = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAllEntries();
try {
while (c.moveToNext()) {
if (c.getString(0).equals(users[p].getName())) {
sb.append(c.getString(1));
entryArray.add(sb.toString());
}
}
} catch (Exception e) {}
c.close();
db.close();
return entryArray;
}
UserFragment
public class UserFragment extends ListFragment {
Context ctx;
View v;
Button mAddEntry;
static int p;
static ArrayList<String> entryArray;
static ArrayAdapter<String> a;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ctx = container.getContext();
if (v != null)
return v;
v = inflater.inflate(R.layout.user_fragment, container, false);
mAddEntry = (Button) v.findViewById(R.id.entry_b);
mAddEntry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putInt("pos", p);
Intent mi = new Intent(v.getContext(), EntryAdd.class);
mi.putExtras(b);
startActivity(mi);
}
});
updateUserFrag(p);
return v;
}
public void updateUserFrag (int p) {
entryArray = new ArrayList<String>();
a = new ArrayAdapter<String>(ctx, android.R.layout.simple_list_item_1, entryArray);
setListAdapter(a);
}
static Handler handy = new Handler() {
public void handleMessage(Message msg) {
int p = msg.getData().getInt("p");
int m = msg.getData().getInt("m");
ArrayList<String> e = msg.getData().getStringArrayList("e");
switch (m) {
case 0:
Log.d("HANDLER", Integer.toString(p));
entryArray.clear();
for (int i=0;i<e.size();i++) {
entryArray.add(e.get(i));
}
a.notifyDataSetChanged();
break;
}
}
};
}

Related

Viewpager displaying the required details only once and not displaying it a second time when coming back from main screen

I am calling ViewPager(Fragment C) from a ListView(Fragment A). But this only works once. If I move back to my list and select another item , it doesnot move into the listview. It just shows a blank layout of fragment c.
Below is the code for Fragment A:
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{
ListView list;
Communicator communicator;
ArrayList<Book> book_a;
ArrayList<String> book_titles;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);
savedInstanceState = getArguments();
if (getArguments() != null) {
// savedInstanceState = getArguments();
book_a = (ArrayList<Book>) getArguments().getSerializable("bookarray");
book_titles = getList(book_a);
//Log.d("Frag_a:Title",book_a.get(5).getTitle());
list= (ListView) view.findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,book_titles);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
return view;
}
public ArrayList<String> getList(ArrayList<Book> book2){
ArrayList<String> list_titles = new ArrayList<String>();
int size = book2.size();
for(int i=0;i<size;i++){
Book object;
object = book2.get(i);
list_titles.add(object.title);
}
return list_titles;
}
public void setCommunicator(Communicator communicator)
{
this.communicator = communicator;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
communicator.respond(position);
}
public interface Communicator{
public void respond(int index);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof Communicator){
communicator = (Communicator) context;
} else {
throw new RuntimeException(context.toString()+"must implement Communicator");
}
}
#Override
public void onDetach() {
super.onDetach();
communicator = null;
}
}
Below is the code for MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentA.Communicator{
FragmentB f2;
ArrayList<Book> b = new ArrayList<Book>();
FragmentManager manager;
static int flag = 0;
static String search="great";
SearchView sv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (SearchView) findViewById(R.id.searchView);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
flag = 1;
search = query;
getBooks();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
getBooks();
return false;
}
});
getBooks();
/*
manager = getSupportFragmentManager();
f1 = (FragmentA) manager.findFragmentById(R.id.fragment);
f1.setCommunicator(this);*/
}
#Override
public void respond(int index) {
f2 = (FragmentB) manager.findFragmentById(R.id.fragment2);
if(f2!=null && f2.isVisible())
{
f2.changeData(index);
}
else
{
Bundle bundle = new Bundle();
bundle.putInt("index", index);
bundle.putSerializable("bookarray",(ArrayList<Book>)b);
Fragment newFragment = new FragmentC();
newFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
public void afterGetBooks(ArrayList<Book> bks) {
for (Book h : bks) {
b.add(h);
}
manager = getSupportFragmentManager();
Bundle args = new Bundle();
args.putSerializable("bookarray",(ArrayList<Book>)bks);
FragmentA f1 = new FragmentA();
f1.setArguments(args);
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment,f1);
transaction.addToBackStack(null);
transaction.commit();
f1.setCommunicator(this);
}
private void getBooks(){
String url;
if(flag==0){
url = "https://kamorris.com/lab/audlib/booksearch.php/";}
else{
url = "https://kamorris.com/lab/audlib/booksearch.php?search=" + search;
flag=0;
}
//ArrayList<Book> boo;
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://kamorris.com/lab/audlib/booksearch.php/").addConverterFactory(GsonConverterFactory.create()).build();
Book.API api = retrofit.create(Book.API.class);
Call<ArrayList<Book>> call = api.getBooks(url);
call.enqueue(new Callback<ArrayList<Book>>() {
#Override
public void onResponse(Call<ArrayList<Book>> call, Response<ArrayList<Book>> response) {
ArrayList<Book> Books = response.body();
for(Book h: Books){
Log.d("Retro-Title",h.getTitle());
//b.add(h);
}
afterGetBooks(Books);
}
#Override
public void onFailure(Call<ArrayList<Book>> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
Below is the code for Fragment C:
public class FragmentC extends Fragment {
ViewPager vp;
static int list_pos;
FragmentPagerAdapter adapterViewPager;
public static ArrayList<Book> book_c;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_c,container,false);
if(getArguments()!= null){
book_c = (ArrayList<Book>) getArguments().getSerializable("bookarray");
list_pos = getArguments().getInt("index");
}
vp = (ViewPager) view.findViewById(R.id.viewpager);
adapterViewPager = new MyPagerAdapter(getFragmentManager());
vp.setAdapter(adapterViewPager);
return view;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 11;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (list_pos) {
case 0: // Fragment # 0 - This will show FirstFragment
list_pos = position;
return FragmentB.newInstance(book_c,0);
case 1: // Fragment # 0 - This will show FirstFragment different title
list_pos = position;
return FragmentB.newInstance(book_c,1);
case 2: // Fragment # 1 - This will show SecondFragment
list_pos = position;
return FragmentB.newInstance(book_c,2);
case 3: list_pos = position;
return FragmentB.newInstance(book_c,3);
case 4:list_pos = position;
return FragmentB.newInstance(book_c,4);
case 5:list_pos = position;
return FragmentB.newInstance(book_c,5);
case 6:list_pos = position;
return FragmentB.newInstance(book_c,6);
case 7:list_pos = position;
return FragmentB.newInstance(book_c,7);
case 8:list_pos = position;
return FragmentB.newInstance(book_c,8);
case 9:list_pos = position;
return FragmentB.newInstance(book_c,9);
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
}
Also is there a way, where I can start my viewpager from the description of the listitem which I selected.
Also Fragment B is just a text view holder.
I tried to see the control flow with the debugger. But when I try it that way these lines in Fragment C are not working ..
{
book_c = (ArrayList<Book>) getArguments().getSerializable("bookarray");
list_pos = getArguments().getInt("index");
}
vp = (ViewPager) view.findViewById(R.id.viewpager);
adapterViewPager = new MyPagerAdapter(getFragmentManager());
vp.setAdapter(adapterViewPager);
Your fragment has not been destroyed and therefore when it is brought back, onCreateView is not being called. Instead override setUserVisibleHint.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// This is true when your fragment is visible, write code to populate view here
} else {
// This is true when your fragment is hidden.
}
}
The solution i found is to change the Fragment Manager
adapterViewPager = new MyPagerAdapter(getFragmentManager());
to
adapterViewPager = new MyPagerAdapter(getChildFragmentManager());

Pass String[] to another class Android (using intent) [duplicate]

This question already has answers here:
Pass a String from one Activity to another Activity in Android
(7 answers)
Closed 5 years ago.
I am trying to pass through intent a string[] but I am getting an error.
I want to send the "arr" to other class "ImageAdapter" and assign the 'String[] mThumbIds' and 'imageTotal'.
Basically, I am showing a grid view of images and images link are fetching from the MySQL database and assign to the "arr" which is going perfect but I want to pass that String[] to another class and I am getting error and error.
It's a small work but I am new in android please help me out.
MainActivity
public class MainActivity extends AppCompatActivity {
public static final String URL_LOGIN= "http://10.0.2.2/e-stitch/fatchimg.php?apicall=shirt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userLogin();
final GridView gridview = (GridView) findViewById(R.id.gridview);
// gridview.setAdapter(new ImageAdapter(this));
// gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// }
// // Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
//i.putExtra("id", position);
//startActivity(i);
// }
// });
}
private void userLogin() {
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressBar.setVisibility(View.GONE);
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
JSONArray arrJson = obj.getJSONArray("user");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++) {
arr[i] = arrJson.getString(i);
}
Intent intent = new Intent(MainActivity.this, ImageAdapter.class);
intent.putExtra("arr", arr);
startActivity(intent);
//finish();
} else {
//Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("shirt", "shirt");
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public static String[] mThumbIds;
int imageTotal;
Bundle bundle = getIntent().getExtras();
mThumbIds= bundle.getString("arr");
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return imageTotal;
}
public void setitem() {
this.mThumbIds=mThumbIds;
imageTotal = mThumbIds.length;
}
#Override
public String getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(480, 480));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
String url = getItem(position);
Picasso.with(mContext)
.load(url)
.placeholder(R.drawable.loader)
.fit()
.centerCrop().into(imageView);
return imageView;
}
}
you can not send intent from activity to adapter
first send the intent to Activity
Intent intent = new Intent(MainActivity.this, exmaple.class);
Bundle extras = new Bundle();
extras.putStringArray("arr", arr);
intent.putExtras(extras);
startActivity(intent);
in your adapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public static String[] mThumbIds;
int imageTotal;
public ImageAdapter(Context c,String[] mThumbIds) {
mContext = c;
this.mThumbIds= mThumbIds
}
receive the intent from the example Activiy
Bundle bundle = getIntent().getExtras();
String [] mThumbIds= bundle.getStringArray("arr");
ImageAdapter imageAdapter = new ImageAdapter (example.this,mThumbIds);

How to use ParseObjects with a RecyclerView?

I am attempting to pull data from my parse server and display an image and text within a RecyclerView of CardViews. I have encountered a few issues, some of which may not have been corrected appropriately, so please feel free to correct any novice code you find below outside of my two current issues. Finally my two issues are.
The data does not display initially. I have 3 tabs in a ViewPager and I have to swipe over twice in order for it to display. If I'm on tab 1 the data doesn't appear until I swipe to tab 3 and return to tab 1, and vice versa. Because there isn't a tab 4, tab 2 never displays.
The second issue I am currently faced with is that at times the data will not match up. It will have the picture from one row matched with the description from another entity.
Below is my MusicFragment.java
public class MusicFragment extends Fragment {
private ArrayList<String> titles = new ArrayList<>();
private ArrayList<Bitmap> bitmaps = new ArrayList<>();
private ArrayList<String> descriptions = new ArrayList<>();
private boolean notComplete = true;
public MusicFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
RecyclerView musicRecycler = (RecyclerView)inflater.inflate(
R.layout.fragment_music, container, false);
if (notComplete) {
// Get the MusicFragImages class as a reference.
ParseQuery<ParseObject> query = new ParseQuery<>("MusicFragImages");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject object : objects) {
String description = (String) object.get("description");
ParseFile file = (ParseFile) object.get("image");
String title = (String) object.get("title");
titles.add(title);
descriptions.add(description);
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null && data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(bitmap);
}
}
});
}
} else {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
notComplete = false;
}
// Create captioned images and registers it to the adapter.
CaptionedImagesAdapter adapter = new CaptionedImagesAdapter(titles, bitmaps, descriptions);
musicRecycler.setAdapter(adapter);
// Set up the layout.
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
musicRecycler.setLayoutManager(layoutManager);
adapter.setListener(new CaptionedImagesAdapter.Listener() {
public void onClick(int position) {
Intent intent;
switch (position) {
case 0:
intent = new Intent(getActivity(), AudioActivity.class);
getActivity().startActivity(intent);
break;
case 1:
intent = new Intent(getActivity(), VideoActivity.class);
getActivity().startActivity(intent);
break;
}
}
});
return musicRecycler;
}
}
Additionally, here is my CaptionedImagesAdapter
class CaptionedImagesAdapter extends
RecyclerView.Adapter<CaptionedImagesAdapter.ViewHolder> {
private final ArrayList<String> captions;
private final ArrayList<Bitmap> bitmaps;
private final ArrayList<String> descriptions;
private Listener listener;
interface Listener {
void onClick(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final CardView cardView;
public ViewHolder(CardView v) {
super(v);
cardView = v;
}
}
public CaptionedImagesAdapter(ArrayList<String> captions, ArrayList<Bitmap> bitmaps, ArrayList<String> descriptions) {
this.captions = captions;
this.bitmaps = bitmaps;
this.descriptions = descriptions;
}
#Override
public int getItemCount() {
return captions.size();
}
public void setListener(Listener listener) {
this.listener = listener;
}
#Override
public CaptionedImagesAdapter.ViewHolder onCreateViewHolder(
ViewGroup parent, int viewType) {
CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.card_selection_2, parent, false);
return new ViewHolder(cv);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int index = position;
// Creates a CardView
CardView cardView = holder.cardView;
ImageView imageView = cardView.findViewById(R.id.type_image);
imageView.setImageBitmap(bitmaps.get(index));
imageView.setContentDescription(descriptions.get(index));
// Populate the caption.
TextView textView = cardView.findViewById(R.id.type_text);
textView.setText(captions.get(index));
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if (listener != null)
listener.onClick(index);
}
});
}
}
FOR REFERENCE...... if needed MainActivity.java is below
public class MainActivity extends AppCompatActivity {
// Variables for the audio player.
public static MediaPlayer mediaPlayer;
public static int albumId;
public static int currentSong = -1;
public static boolean isPlaying = false;
private static int[] songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Attach the SectionsPageAdapter to the ViewPager
SectionsPageAdapter pagerAdapter = new SectionsPageAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
int currentTab = 0;
pager.setCurrentItem(currentTab);
// Attach the ViewPager to the TabLayout
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
// Starts the player.
player();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the app bar.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.action_contact:
intent = new Intent(MainActivity.this, ContactActivity.class);
startActivity(intent);
return true;
case R.id.action_cart:
intent = new Intent(this, CartActivity.class);
startActivity(intent);
return true;
case R.id.action_member:
intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class SectionsPageAdapter extends FragmentPagerAdapter {
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MusicFragment();
case 1:
return new ArtFragment();
case 2:
return new FashionFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getText(R.string.title_music);
case 1:
return getResources().getText(R.string.title_art);
case 2:
return getResources().getText(R.string.title_fashion);
}
return null;
}
}
private void player() {
/*Create a background thread that will automatically advance to
* the next song, as long as there is a next song.*/
// Get the songs.
songs = AudioData.audio[albumId].getSongs();
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
if (isPlaying) {
if (!(mediaPlayer.isPlaying()) && currentSong < songs.length - 1) {
mediaPlayer.stop();
mediaPlayer.reset();
currentSong++;
mediaPlayer = MediaPlayer.create(MainActivity.this, songs[currentSong]);
mediaPlayer.start();
isPlaying = true;
}
//Set the flag to false at the end of the album.
if (currentSong == songs.length) {
isPlaying = false;
}
}
handler.postDelayed(this, 1000);
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}
}
Thanks again to Harikumar for correcting the first issue. I ended up correcting the second issue with the code below. It was within the enhance for loop.
for (ParseObject object : objects) {
String description = (String) object.get("description");
ParseFile file = (ParseFile) object.get("image");
String title = (String) object.get("title");
Bitmap bitmap;
titles.add(title);
descriptions.add(description);
byte[] data;
try {
data = file.getData();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(bitmap);
adapter.notifyDataSetChanged(); //notify your adapter that data has changed
} catch (ParseException pe) {
Toast.makeText(getContext(), pe.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Data will be updated if you notify your adapter CaptionedImagesAdapter. Try modifying the code to:
public class MusicFragment extends Fragment {
private ArrayList<String> titles = new ArrayList<>();
private ArrayList<Bitmap> bitmaps = new ArrayList<>();
private ArrayList<String> descriptions = new ArrayList<>();
private CaptionedImagesAdapter adapter;
private boolean notComplete = true;
public MusicFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
RecyclerView musicRecycler = (RecyclerView)inflater.inflate(
R.layout.fragment_music, container, false);
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
musicRecycler.setLayoutManager(layoutManager);
adapter = new CaptionedImagesAdapter(titles, bitmaps, descriptions);
musicRecycler.setAdapter(adapter);
if (notComplete) {
// Get the MusicFragImages class as a reference.
ParseQuery<ParseObject> query = new ParseQuery<>("MusicFragImages");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject object : objects) {
String description = (String) object.get("description");
ParseFile file = (ParseFile) object.get("image");
String title = (String) object.get("title");
titles.add(title);
descriptions.add(description);
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null && data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(bitmap);
adapter.notifyDataSetChanged(); //notify your adapter that data has changed
}
}
});
}
} else {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
notComplete = false;
}
adapter.setListener(new CaptionedImagesAdapter.Listener() {
public void onClick(int position) {
Intent intent;
switch (position) {
case 0:
intent = new Intent(getActivity(), AudioActivity.class);
getActivity().startActivity(intent);
break;
case 1:
intent = new Intent(getActivity(), VideoActivity.class);
getActivity().startActivity(intent);
break;
}
}
});
return musicRecycler;
}
}
Here is a small optimization for your 2nd solution: update notifyDataSetChanged() only once after the for loop (put it just outside the for loop). This is better in terms of performance.

Remove reloading of list fragments when back button is pressed

I created a Tabbed Activity where all the list fragments are pro grammatically created when the activity is first opened as you can see based on previously saved data.
public class CcSongBook extends ActionBarActivity implements TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
SharedPreferences vSettings;
SharedPreferences.Editor localEditor;
public SongBookSQLite db = new SongBookSQLite(this, SongBookDatabase.DATABASE, null, SongBookDatabase.VERSION);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sb_book);
vSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
localEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(2);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(this.mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
String[] songbooks = TextUtils.split(vSettings.getString("js_vsb_sbcodes", "NA"), ",");
String[] songbookno = TextUtils.split(vSettings.getString("js_vsb_sbnos", "NA"), ",");
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return songbooks.length-1;
}
#Override
public CharSequence getPageTitle(int position) {
return songbooks[position];
}
public Fragment getItem(int position) {
Bundle data = new Bundle();
data.putInt("songbook", Integer.parseInt(songbookno[position]));
SongBookList sblist = new SongBookList();
sblist.setArguments(data);
return sblist;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sb_fragment, container, false);
return rootView;
}
}
}
then in my other class which is used in list fragments I am basically reading some specific values from my sqlite database based on the bundle data passed on from the base activity:
public class SongBookList extends ListFragment implements LoaderCallbacks<Cursor> {
public SongBookSQLite db;
private String[] My_Text, My_Texti, My_Textii;
List<SongItem> mylist;
ArrayAdapter<String> listAdapter;
SimpleCursorAdapter mCursorAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
db = new SongBookSQLite(getActivity().getBaseContext(), SongBookDatabase.DATABASE, null, SongBookDatabase.VERSION);
Bundle data = this.getArguments();
int curr_songbook = data.getInt("songbook", 1);
mylist = db.getAllSongs(curr_songbook);
List<String> listSongid = new ArrayList<String>();
List<String> listTitle = new ArrayList<String>();
List<String> listContent = new ArrayList<String>();
for (int i = 0; i < mylist.size(); i++) {
listSongid.add(i, Integer.toString(mylist.get(i).getSongid()));
listTitle.add(i, mylist.get(i).getTitle());
listContent.add(i, mylist.get(i).getContent());
}
My_Text = listSongid.toArray(new String[listSongid.size()]);
for (String string : My_Text) { System.out.println(string); }
My_Texti = listTitle.toArray(new String[listTitle.size()]);
for (String stringi : My_Texti) { System.out.println(stringi);}
My_Textii = listContent.toArray(new String[listContent.size()]);
for (String stringii : My_Textii) { System.out.println(stringii); }
setListAdapter(new CustomSongList(getActivity(), My_Text, My_Texti, My_Textii));
return super.onCreateView(inflater, container, savedInstanceState);
}
public void onStart() {
super.onStart();
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(getActivity().getApplicationContext(), SongBookView.class);
Uri data = Uri.withAppendedPath(SongBookProvider.CONTENT_URI, String.valueOf(id+1));
myIntent.setData(data);
startActivity(myIntent);
}
});
}
public Loader<Cursor> onCreateLoader(int arg0, Bundle data) {
Uri uri = SongBookProvider.CONTENT_URI;
return new CursorLoader(getContext(), uri, null, null, new String[]{data.getString("query")}, null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
this.mCursorAdapter.swapCursor(c);
}
public void onLoaderReset(Loader<Cursor> loader) {
}
Now when a list item is clicked on any list fragment it opens up in a new activity which is as below:
public class SongBookView extends ActionBarActivity {
TextView mSongCont;
Cursor cursor;
public Uri mUri;
SongBookSQLite db;
SharedPreferences vSettings;
SharedPreferences.Editor localEditor;
String VSB_SETTINGS, FONT_SIZE, CURRENT_SONG;
public int CurrSong, FontSize;
ListView StanzasList;
SongItem currentSong;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song_view);
db = new SongBookSQLite(this, SongBookDatabase.DATABASE, null, SongBookDatabase.VERSION);
StanzasList =(ListView)findViewById(R.id.stanzalist);
vSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
localEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
changeStatusBarColor();
Long rated_me_not = vSettings.getLong("js_vsb_rated_me_not", 0);
Long time_used = (System.currentTimeMillis() - rated_me_not) / 1000;
if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("js_vsb_rate_me", false)) {
if (time_used > 18000 ) {
rateMePlease();
}
}
FontSize = PreferenceManager.getDefaultSharedPreferences(this).getInt("js_vsb_font_size", 15);
mUri = getIntent().getData();
CurrSong = Integer.parseInt(mUri.toString().replaceAll("\\D+", ""));
openCurrentSong();
}
public void openCurrentSong(){
localEditor.putInt("js_vsb_curr_song", CurrSong).commit();
currentSong = db.readSong(CurrSong);
setTitle(currentSong.getTitle());
String[] Stanzas = TextUtils.split(currentSong.getContent(), "`");
CustomSongView adapter = new CustomSongView(this, Stanzas);
StanzasList.setAdapter(adapter);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, CcSongBook.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
The main question here is how do i prevent the main activity from reloading itself all over again because it is happening.
I have already seen when the back button is pressed its like a new intent is initiated. How about you removed the line:
Intent intent = new Intent(this, CcSongBook.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
from the method onBackPressed()
Actually removing the lines below did solve my problem
Intent intent = new Intent(this, CcSongBook.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

invalidateViews() and notifyDataSetChanged() doesnt work for me

i using ListView in fragment. I have one asynctask to download json data from remote server. I try refresh programmatically my displayed adapter/listview in onPostExecute function but it doesn't work for me.
My main activity with three fragments, three listview, three adapter and one async task.
public class ContactsActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
private static List<Item> BackList = new ArrayList<Item>();
private static List<Item> BackList2 = new ArrayList<Item>();
private static List<Item> BackList3 = new ArrayList<Item>();
private static ListView ListView;
private static Context activity;
public static String HASH;
private static final String[] timestamp = {"0"};
private static WeatherAdapter adapter;
private static int fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
Intent myIntent= getIntent();
HASH = myIntent.getStringExtra("HASH");
Log.d("Intent - contactActivity", HASH);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
(new PrefetchData()).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.contacts, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
fragment = position;
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
int index = getArguments().getInt(ARG_SECTION_NUMBER);
fragment = index;
activity = getActivity();
ListView listview1 = (ListView) rootView.findViewById(R.id.listView);
switch(fragment){
case 1:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row, BackList);
listview1.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
Intent rozmowa = new Intent(getActivity(), Incotalk.class);
rozmowa.putExtra("HASH", HASH);
startActivity(rozmowa);
}
});
break;
case 2:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row2, BackList2);
break;
case 3:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row3, BackList3);
break;
}
listview1.setAdapter(adapter);
ListView = listview1;
return rootView;
}
}
/**
* Async Task to make http call
*/
private class PrefetchData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// before making http calls
}
#Override
protected Void doInBackground(Void... arg0) {
final String id = HASH;
final String url = "http://freshfrog.pl/projects/talk.php?user="+id+"&t=" + timestamp[0];
Log.d("BBB","start");
try {
String page = new Communicator().executeHttpGet(url);
JSONObject jsonObject = new JSONObject(page);
timestamp[0] = jsonObject.getString("t");
HASH = jsonObject.getJSONObject("s").getString("hash");
JSONArray oczekujacy = jsonObject.getJSONArray("m");
// wiadomosci
BackList.clear(); // czyści przed odświerzeniem
BackList2.clear();
BackList3.clear();
for (int i=oczekujacy.length()-1; i>0; i--) {
JSONObject actor = oczekujacy.getJSONObject(i);
String message = actor.getString("m");
String hash = actor.getString("n");
String t = actor.getString("t");
int l = BackList.size();
Boolean jest = false;
for(int j=0; j<l; j++){
Item item = BackList.get(j);
if(!item.isSection()){
ContactItem contactItem= (ContactItem) item;
if( (contactItem.hash).equals(hash) ){
jest = true;
break;
}
}
//Log.d("bbb", BackList.get(j).hash);
}
if(!jest && !hash.equals(id)) BackList.add(
new ContactItem(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
message,
hash));
}
// znajomi
BackList2.add(new SectionItem("Otrzymane zaproszenia"));
oczekujacy = jsonObject.getJSONObject("f").getJSONObject("p").getJSONArray("sending");
for (int i=0; i<oczekujacy.length(); i++) {
JSONObject actor = oczekujacy.getJSONObject(i);
String name = actor.getString("name");
String hash = actor.getString("hash");
String avatar = actor.getString("avatar");
BackList2.add(new ContactItem(getBitmapFromURL(avatar) , name, hash) );
}
// szukaj
BackList3.add(new SectionItem("Znajomi"));
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
BackList3.add(new ContactItem(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
name,
phoneNumber) );
}
} catch (Exception e) {
Log.d("BBB", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* gdy skończy */
adapter.notifyDataSetChanged();
ListView listview2 = (ListView) findViewById(R.id.listView);
listview2.invalidateViews();
//Toast.makeText(ContactsActivity.this, "coś przyszło", Toast.LENGTH_SHORT).show();
Log.d("BBB", "powinno sie odswieżyc");
new PrefetchData().execute();
}
}
}
My custom adapter
public class WeatherAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
List<Item> data = null;
private LayoutInflater vi;
public WeatherAdapter(Context context, int layoutResourceId, List<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
SectionHolder holder2 = null;
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
Item i = data.get(position);
if(row == null){
if(!i.isSection()){
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
ContactItem contactItem = (ContactItem)i;
holder.txtTitle.setText(contactItem.title);
holder.imgIcon.setImageBitmap(contactItem.icon);
}else{
row = inflater.inflate(R.layout.listview_header_row, parent, false);
holder2 = new SectionHolder();
holder2.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder2);
SectionItem sectionItem = (SectionItem)i;
holder2.txtTitle.setText(sectionItem.title);
}
}
else
{
if(!i.isSection()){
//holder = (WeatherHolder) row.getTag();
}else{
//holder2 = (SectionHolder) row.getTag();
}
}
return row;
}
public void update(List<Item> newlist) {
Log.d("bbb","aktualizacja listview");
data.clear();
data.addAll(newlist);
this.notifyDataSetChanged();
}
#Override
public void notifyDataSetChanged() // Create this function in your adapter class
{
//notifySetDataChanged()
super.notifyDataSetChanged();
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
static class SectionHolder
{
TextView txtTitle;
}
}
the part of the "if(row == null){" should only contain initializations of the views and the viewHolders.
it shouldn't contain any setting of data to the views.
after this part ( after the "else {...}" ) , you should update the views with the new data .
here's my fix to your code (looks ugly, but should work) :
...
int type=getViewType();
switch(type)
{
case 0:
if(row == null)
{
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
holder = (WeatherHolder) row.getTag();
ContactItem contactItem = (ContactItem)i;
holder.txtTitle.setText(contactItem.title);
holder.imgIcon.setImageBitmap(contactItem.icon);
break;
case 1:
if(row == null)
{
row = inflater.inflate(R.layout.listview_header_row, parent, false);
holder2 = new SectionHolder();
holder2.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder2);
}
else
holder2 = (SectionHolder) row.getTag();
SectionItem sectionItem = (SectionItem)i;
holder2.txtTitle.setText(sectionItem.title);
break;
}
return row;
...
... int getViewType(...) {... return i.isSection()? 1:0;}
... int getViewTypeCount(){return 2;}
btw, you should really watch the lecture "the world of listView" . they have great tips that will make your code much better.
for example, you can use getViewTypeCount , getViewType, getItem, as shown on the API .
to view your code i see that you have started your async execution again on postExcecute
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* gdy skończy */
adapter.notifyDataSetChanged();
ListView listview2 = (ListView) findViewById(R.id.listView);
listview2.invalidateViews();
//Toast.makeText(ContactsActivity.this, "coś przyszło", Toast.LENGTH_SHORT).show();
Log.d("BBB", "powinno sie odswieżyc");
new PrefetchData().execute();
}
also clearing data inside your doBackground
To get changes on your data you should not clear your data just get updates records and notify your adapeter
try to change the method data.addAll(newlist) by using addall(newlist, data);
inside addall method add one by one the list of element. this way it should work.
i had the same problem and i correct it the way i explained.

Categories

Resources