I have made an Image Editor and it works fine. Now, in my recent edits page, I added a feature select multiple items. But, I get a strange behaviour when I refresh the recycler view. See this ->
https://www.veed.io/view/43fa65a4-24e6-44e8-8cea-468ca8c62d7a.
This is my adapter code ->
public class RecentsAdapter extends RecyclerView.Adapter<RecentsAdapter.ViewHolder>{
private List<ImageFile> files;
private final PopupListener popupListener;
RecentItemListeners recentItemListeners;
public Integer selectedItemsCount = 0;
TextView neEditsTV;
public RecentsAdapter(List<ImageFile> files, PopupListener popupListener, RecentItemListeners listeners, TextView neEditsTV) {
this.files = files;
this.popupListener = popupListener;
this.recentItemListeners = listeners;
this.neEditsTV = neEditsTV;
}
public void updateList(List<ImageFile> filesList){
if (files.size() < filesList.size()){
int dif = filesList.size() - files.size();
this.files = filesList;
for (int i = 0; i < dif; i++) {
notifyItemInserted(i);
}
}else if (files.size() > filesList.size()){
for (int i = 0; i < filesList.size(); i++) {
notifyItemChanged(i);
}
notifyDataSetChanged();
notify();
}else {
this.files = filesList;
for (int i = 0; i < filesList.size(); i++) {
notifyItemChanged(i);
}
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(ItemRecentBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
#SuppressLint("NewApi")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(files.get(position));
}
#Override
public int getItemCount() {
return files.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements TinyDBManager.ValueChangeListener {
ItemRecentBinding binding;
boolean mIsSelected = false;
public ViewHolder(#NonNull ItemRecentBinding itemView) {
super(itemView.getRoot());
binding = itemView;
}
#SuppressLint({"ClickableViewAccessibility", "ResourceAsColor"})
#RequiresApi(api = Build.VERSION_CODES.Q)
public void setData(ImageFile file){
TinyDBManager tinyDBManager = TinyDB.getInstance(itemView.getContext());
tinyDBManager.setValueChangeListener(this);
binding.fileName.setText(file.getName());
binding.preview.setImageURI(Uri.parse(file.getPath()));
Log.d("positionChecker",getAdapterPosition() + "");
#SuppressLint("SimpleDateFormat") String datept1 = new SimpleDateFormat("dd/MM/yyyy").format(file.getLastModified());
#SuppressLint("SimpleDateFormat") String datept3 = new SimpleDateFormat("hh:mm:ss a").format(file.getLastModified());
binding.lastEdited.setText(datept1 + " at " + datept3);
binding.option.setOnClickListener(v -> {
ContextThemeWrapper contextWrapper = new ContextThemeWrapper(itemView.getContext(),R.style.Theme_ImageEditor);
PopupMenu menu = new PopupMenu(contextWrapper, binding.option);
menu.inflate(R.menu.recent_item_menu);
menu.setForceShowIcon(true);
menu.show();
menu.setOnDismissListener(menu1 -> popupListener.onPopupClosed());
popupListener.onPopupOpened();
menu.setOnMenuItemClickListener(item -> {
switch (item.getTitle().toString()){
case "Open":
Intent openIntent = new Intent();
openIntent.setAction(Intent.ACTION_VIEW);
openIntent.setDataAndType(Uri.parse(file.getPath()), "image/*");
openIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
itemView.getContext().startActivity(openIntent);
break;
case "Share":
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(file.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
shareIntent.setType("image/*");
itemView.getContext().startActivity(Intent.createChooser(shareIntent, "Share image via..."));
break;
case "Edit":
Intent editIntent = new Intent(itemView.getContext(), ImageEditorActivity.class);
editIntent.putExtra("filePath",file.getPath());
editIntent.putExtra("position",getAdapterPosition());
Toast.makeText(contextWrapper, "" + file.getName(), Toast.LENGTH_SHORT).show();
editIntent.putExtra("name",file.getName());
editIntent.putExtra("new",false);
v.getContext().startActivity(editIntent);
break;
case "Remove from list":
TinyDBManager tinyDB = TinyDB.getInstance(v.getContext());
List<ImageFile> imageFiles = tinyDB.get("files",null);
imageFiles.remove(getAdapterPosition());
files.remove(getAdapterPosition());
tinyDB.put("files",imageFiles);
notifyItemRemoved(getAdapterPosition());
break;
case "Delete":
CustomAlertDialog dialog = new CustomAlertDialog(itemView.getContext(),null);
View.OnClickListener[] clickListeners = new View.OnClickListener[2];
clickListeners[0] = v1 -> dialog.dismiss();
clickListeners[1] = v1 -> {
dialog.dismiss();
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + file.getName();
boolean deleteFile = new File(path).delete();
Log.d("path:",file.getPath());
if (deleteFile)
Toast.makeText(contextWrapper, "success", Toast.LENGTH_SHORT).show();
else Toast.makeText(contextWrapper, "fail", Toast.LENGTH_SHORT).show();
MediaScannerConnection.scanFile(itemView.getContext(), new String[] { Environment.getExternalStorageDirectory().toString() }, null, (path1, uri) -> {
Log.i("ExternalStorage", "Scanned " + path1 + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
});
};
dialog.show(itemView.getContext(), "Delete image","Are you sure you want to delete the image?\nThis action cannot be reverted.", new String[]{"No","Yes"},clickListeners);
}
return true;
});
});
binding.share.setOnClickListener(v -> {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(file.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
shareIntent.setType("image/*");
itemView.getContext().startActivity(Intent.createChooser(shareIntent, "Share image via..."));
});
binding.getRoot().setOnClickListener(v -> {
if (selectedItemsCount != 0) {
if (mIsSelected) {
mIsSelected = false;
selectedItemsCount--;
binding.getRoot().setCardBackgroundColor(Color.WHITE);
binding.lastEdited.setTextColor(Color.GRAY);
binding.fileName.setTextColor(Color.BLACK);
binding.option.setImageTintList(ColorStateList.valueOf(Color.GRAY));
recentItemListeners.onItemClick(getAdapterPosition(), 1, file.getPath(),file);
} else {
recentItemListeners.onItemClick(getAdapterPosition(), 0, file.getPath(),file);
binding.getRoot().setCardBackgroundColor(itemView.getContext().getColor(R.color.primary));
binding.lastEdited.setTextColor(Color.WHITE);
binding.fileName.setTextColor(Color.WHITE);
binding.option.setImageTintList(ColorStateList.valueOf(Color.WHITE));
mIsSelected = true;
selectedItemsCount++;
}
}else {
mIsSelected = false;
binding.getRoot().setCardBackgroundColor(Color.WHITE);
binding.lastEdited.setTextColor(Color.GRAY);
binding.fileName.setTextColor(Color.BLACK);
binding.option.setImageTintList(ColorStateList.valueOf(Color.GRAY));
}
});
binding.getRoot().setOnLongClickListener(v -> {
mIsSelected = true;
binding.getRoot().setCardBackgroundColor(itemView.getContext().getColor(R.color.primary));
binding.lastEdited.setTextColor(Color.WHITE);
binding.fileName.setTextColor(Color.WHITE);
binding.option.setImageTintList(ColorStateList.valueOf(Color.WHITE));
recentItemListeners.onItemLongClick(getAdapterPosition(), file.getPath(), file);
selectedItemsCount++;
return true;
});
}
#Override
public <E> void onValueAdded(String key, E value) {
files = (List<ImageFile>) value;
files.sort(Comparator.comparing(obj -> obj.getLastModified()));
Collections.reverse(files);
notifyDataSetChanged();
neEditsTV.setVisibility(files.size() == 0 ? View.VISIBLE : View.GONE);
}
#Override
public void onKeyRemoved(String key) {
}
#Override
public void onAllKeysRemoved() {
}
}
}
And now my activity interface listener which are passed to the adapter ->
#Override
public void onItemClick(int position, int action, String filePath, ImageFile file) {
if (selectedItems.contains(file) && action == 1) {
selectedItemsCount--;
filePaths.remove(position);
selectedItems.remove(selectedItems.get(position));
if (selectedItemsCount == 0){
binding.toolbar.setTitle(getString(R.string.app_name));
binding.toolbar.getMenu().clear();
binding.toolbar.setNavigationIcon(null);
canUpdate = true;
}else {
binding.toolbar.setTitle("" + selectedItemsCount);
binding.toolbar.getMenu().clear();
binding.toolbar.inflateMenu(R.menu.multi_select_options);
binding.toolbar.setNavigationIcon(R.drawable.left);
canUpdate = false;
}
}else {
selectedItemsCount++;
selectedItems.add(file);
filePaths.add(filePath);
binding.toolbar.setTitle(selectedItemsCount + " Selected");
binding.toolbar.getMenu().clear();
binding.toolbar.inflateMenu(R.menu.multi_select_options);
binding.toolbar.setNavigationIcon(R.drawable.left);
canUpdate = false;
}
}
#Override
public void onItemLongClick(int position, String filePath, ImageFile file) {
if (selectedItems.contains(file)) return;
selectedItemsCount++;
selectedItems.add(file);
filePaths.add(filePath);
binding.toolbar.setTitle(selectedItemsCount + " Selected");
binding.toolbar.getMenu().clear();
binding.toolbar.inflateMenu(R.menu.multi_select_options);
binding.toolbar.setNavigationIcon(R.drawable.left);
canUpdate = false;
}
And my item file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/_65sdp"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="#dimen/_6sdp"
android:padding="#dimen/_10sdp"
app:cardElevation="2dp"
android:layout_marginTop="#dimen/_12sdp"
android:layout_marginHorizontal="#dimen/_6sdp"
android:background="?selectableItemBackground">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="?selectableItemBackground">
<ImageView
android:id="#+id/preview"
android:layout_width="#dimen/_70sdp"
android:layout_height="match_parent"
tools:src="#tools:sample/backgrounds/scenic"
android:scaleType="centerCrop"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="#dimen/_10sdp"
android:paddingVertical="#dimen/_2sdp"
android:gravity="center">
<TextView
android:id="#+id/fileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sample file.png"
style="#style/TextAppearance.AppCompat.Title"
android:gravity="center_vertical"
android:ellipsize="end"
android:maxLines="1"
android:layout_weight="1"/>
<TextView
android:id="#+id/lastEdited"
style="#style/TextAppearance.AppCompat.Subhead"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_vertical"
android:maxLines="1"
android:text="Sample file.png"
android:textColor="#android:color/darker_gray"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/option"
android:layout_width="#dimen/_24sdp"
android:layout_height="0dp"
android:src="#drawable/more_vert"
android:padding="#dimen/_2sdp"
android:background="?selectableItemBackgroundBorderless"
app:tint="#android:color/darker_gray"
android:layout_weight="1"/>
<ImageView
android:id="#+id/share"
android:layout_width="#dimen/_24sdp"
android:layout_height="0dp"
android:src="#drawable/share"
android:padding="#dimen/_2sdp"
android:background="?selectableItemBackgroundBorderless"
app:tint="#android:color/holo_red_light"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
How can I prevent this behaviour?
I am a newbie in android development.In my music player app, whenever I click the play/pause button to pause the song , nothing happens. It seems like the imagebutton is not clickable because nothing happens on touching it. I am not able to pause the song playing. I have tried all possible solutions mentioned on stack overflow still its not working.Can anyone tell me what am I doing wrong ?
XML File :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:weightSum="1">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_bright">
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_weight="2.40"
android:background="#null"
android:paddingLeft="10dp"
android:src="#drawable/btn_previous" />
<ImageButton
android:id="#+id/btnPlay1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:clickable="true"
android:background="#drawable/btn_play" />
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:paddingLeft="230dp"
android:src="#drawable/btn_next" />
</RelativeLayout>
</LinearLayout>
btn_play.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/download4"
android:state_enabled="false" />
<item android:drawable="#drawable/az"
android:state_enabled="true" />
</selector>
PlayListActivity.java :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_list);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv(path);
abc();
}
public void acv(String path) {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path);
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
album.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
artist.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
album.setText("Unknown Album");
artist.setText("Unknown Artist");
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.coverart1);
album = (TextView) findViewById(R.id.Album);
artist = (TextView) findViewById(R.id.artist_name);
}
public void abc(){
ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
btnPlay1.setOnClickListener(
new ImageButton.OnClickListener(){
public void onClick(View v){
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
}
Your Adapter doesnt seen to be in the same LayoutXML, maybe your findViewById(R.id.btnPlay1) are returning null.
Your listener change it to this :
btnPlay1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Act.this, "test click", Toast.LENGTH_SHORT).show();
}
});
Basically this question is an update for this question
Just to rewind again, this is the country_info.xml
<?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="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
android:id="#+id/gambar_saja"
android:layout_width="150dp"
android:layout_height="160dp"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/n1"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/detail_country"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_toRightOf="#+id/gambar_saja"
android:layout_toEndOf="#+id/gambar_saja"
android:orientation="vertical"
android:layout_marginLeft="4dp">
<TextView
android:id="#+id/code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="24sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/code"
android:layout_below="#+id/code"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/continent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_below="#+id/name"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/region"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/continent"
android:layout_below="#+id/continent"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</RelativeLayout>
</RelativeLayout>
and here is cari_studio.xml to populate the country_info into listview (listView1) :
<?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"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/area"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal" >
<TextView
android:id="#+id/isiArea"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="#drawable/text_selector"
android:gravity="center_vertical"
android:paddingBottom="10dp"
android:paddingLeft="35dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:text="#string/area"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="visible"/>
<Spinner
android:id="#+id/textArea"
android:layout_marginRight="15dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/area"
android:textColor="#color/black"
android:inputType="text"
android:textSize="14sp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/list_area_studio"
android:layout_below="#+id/area"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/cari_studio" android:textSize="20sp" />
<EditText android:id="#+id/myFilter" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="#string/studio_hint">
<requestFocus />
</EditText>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="#drawable/navbar_background"
>
<RadioButton
android:id="#+id/btnAll"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_allselector"
android:text="All"
/>
<RadioButton
android:id="#+id/btnPicture"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_pictureselector"
android:text="Pictures"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnVideo"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_videoselector"
android:text="Videos"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnFile"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_fileselector"
android:text="Files"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnMore"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_moreselector"
android:text="More"
android:layout_marginLeft="5dp"
/>
</RadioGroup>
<LinearLayout
android:id="#+id/floatingmenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/laysemitransparentwithborders"
android:orientation="vertical"
android:layout_marginBottom="-4dp"
android:visibility="gone"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Contacts"
android:textColor="#ffffff"
android:textSize="16dp"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ff999999"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Calendar"
android:textColor="#ffffff"
android:textSize="16dp"
/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
and here is the Cari Studio Class to get JSONArray result (use post) and I already success get the result :
public class CariStudio extends Activity{
final Context context = this;
MyCustomAdapter dataAdapter = null;
RadioButton radioButton1, radioButton2, radioButton3, radioButton4, radioButton5;
TextView flexlocationid;
Spinner flexlocation;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> provincelist;
ArrayList<ProvinceModel> province;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cari_studio);
//Generate list View from ArrayList
new DownloadJSON().execute();
addListenerOnButton();
}
public void addListenerOnButton() {
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
radioButton1 = (RadioButton) findViewById(R.id.btnAll);
radioButton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, home.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton2 = (RadioButton) findViewById(R.id.btnPicture);
radioButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariKelas.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton3 = (RadioButton) findViewById(R.id.btnVideo);
radioButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariStudio.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton4 = (RadioButton) findViewById(R.id.btnFile);
radioButton4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, HotStuff.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton5 = (RadioButton) findViewById(R.id.btnMore);
radioButton5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, MyAccount.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
flexlocation = (Spinner) findViewById(R.id.textArea);
flexlocationid = (TextView) findViewById(R.id.isiArea);
}
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
runOnUiThread(new Runnable() {
public void run() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country(studio_name,address, "Website:"+ website,
"Fasilitas:"+ seo_url);
countryList.add(country);
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
});
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the CariStudio Class
province = new ArrayList<ProvinceModel>();
// Create an array to populate the spinner
provincelist = new ArrayList<String>();
// JSON file URL address
final String url_flexlocation = Constant.URI_BASE_FLEXLOCATION;
Utils.log("url_flexlocation: " + url_flexlocation);
try {
// Locate the NodeList name
HttpGet httppost = new HttpGet(url_flexlocation);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Utils.log("data: " + data);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
ProvinceModel worldpop = new ProvinceModel();
worldpop.setId(jsonobject.optString("flex_id"));
worldpop.setProvince(jsonobject.optString("name"));
province.add(worldpop);
// Populate spinner with province names
provincelist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in cari_studio.xml
Spinner mySpinner = (Spinner) findViewById(R.id.textArea);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(CariStudio.this,
R.layout.spinner_white,
provincelist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in cari_studio.xml
TextView flexlocationid = (TextView) findViewById(R.id.isiArea);
// Set the text followed by the position
flexlocationid.setText(province.get(position).getId());
String areaid = flexlocationid.getText().toString();
Utils.log("area id:" + areaid);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(areaid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
private CountryFilter filter;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new CountryFilter();
}
return filter;
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
private class CountryFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<Country> filteredItems = new ArrayList<Country>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
Country country = originalList.get(i);
if(country.toString().toLowerCase().contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}
}
the result that I got from Utils.log("daftar isi studio: " + responseAsText) :
[{"id":"8","studio_name":"Dodi fit","seo_url":"dodi-fit","address":"Komp. Pertanian Blok 5 No 3","postcode":"87473","area_phone":"","phone":"+62876543","area_phone_second":"","phone_second":"+62","website":"sucifir.com","region_id":"12","lokasi_id":"138","booking_window":"7","facebook":"dodifitfb","twitter":"dodifittw","how_to_get_there":"over there, by trun left and right","priority":"5"},{"id":"11","studio_name":"inu fit","seo_url":"inu-fit","address":"","postcode":"","area_phone":"","phone":"+6221324234","area_phone_second":"","phone_second":"","website":"","region_id":"11","lokasi_id":"137","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"5","studio_name":"Vstudio","seo_url":"vstudio","address":"Plaza Indonesia Ground Floor #541","postcode":"","area_phone":"","phone":"+6221453787","area_phone_second":"","phone_second":"","website":"www.jkiij.com","region_id":"12","lokasi_id":"137","booking_window":"0","facebook":"face","twitter":"twy","how_to_get_there":"","priority":"5"},{"id":"7","studio_name":"Infovendor","seo_url":"infovendor","address":"","postcode":"","area_phone":"","phone":"+6221123452","area_phone_second":"","phone_second":"","website":"www.kidsdngf.com","region_id":"12","lokasi_id":"135","booking_window":"1","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"12","studio_name":"Seleb Fitnes One","seo_url":"selebfitnesone-57","address":"Kelapa gading timur no 17","postcode":"","area_phone":"","phone":"+6221453777","area_phone_second":"","phone_second":"","website":"selebfirnes.com","region_id":"12","lokasi_id":"138","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"14","studio_name":"Riri Studio","seo_url":"riristudio-57","address":"Mall Kelapa Gading, Lt 5","postcode":"","area_phone":"","phone":"+6221459325","area_phone_second":"","phone_second":"","website":"riri-riri.com","region_id":"12","lokasi_id":"135","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"19","studio_name":"NF Studio","seo_url":"nf-studio","address":"Ruko Mediterania Blok A4 No 79Jalan Ahmad Yani Kav A5, Kota Bekasi","postcode":"13536","area_phone":"","phone":"+62265111222","area_phone_second":"","phone_second":"","website":"nfstudio.com","region_id":"11","lokasi_id":"137","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"}]
and the result that I got from looping Utils.log("studio_name: " + studio_name) are :
studio_name: Dodi fit
studio_name: inu fit
studio_name: Vstudio
studio_name: Infovendor
studio_name: Seleb Fitnes One
studio_name: Riri Studio
studio_name: NF Studio
It means I already got all of it use looping.
But the problem is the result did not populate into listview (it show as one one last result NF Studio, the other did not appear).
What I need is populate this into 4 texview from country_info (I disable imageview) :
String studio_name, address, website, seo_url
What is the correct code to show/populate that into listview?
Add the values into a List and pass it to the Adapter class of your ListView inside onPostExecute()
You don't need a thread, that's the whole point of async.
List View code is in the for loop
UI code belongs to PostExecute() not doInBackground()
You reinitialized the list inside of the loop
Try like this:
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
private ArrayList<Country> countryList = new ArrayList<Country>();
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
Country country = new Country(studio_name,address, "Website:"+ website,"Fasilitas:"+ seo_url);
countryList.add(country);
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
}
I am trying to use Chris Banes' library Actionbar-PullToRefresh. It can be found here.
I am using Tabs at bottom of screen in my app. as you can see in screen shot.
I read through the sample code. He says that all you have to do is, wrap your refreshable view in a PullToRefreshLayout like this: How do i integrate it into my app.
public class MainActivity extends Activity implements OnTabChangeListener {
private TabHost mTabHost;
public static final String TAB_1 = "Open";
public static final String TAB_2 = "Approved";
public static final String TAB_3 = "Decline";
private int mCurrentTab;
public String result;
Vector<String> msgvector = new Vector<String>();
Vector<String> usernamevector = new Vector<String>();
Vector<String> feedIdvector = new Vector<String>();
Vector<String> userIdvector = new Vector<String>();
ListView listview,listview1,listview2;
private ProgressDialog simpleWaitDialog;
List<Rowfeeds> rowfeedlist;
public String result2;
public String result3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
listview = (ListView)findViewById(R.id.tab_1);
listview1 = (ListView)findViewById(R.id.tab_2);
listview2 = (ListView)findViewById(R.id.tab_3);
new Feedsdata().execute();
setupTabs();
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
}
private class Feedsdata extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
Log.i("doInBackground", "doInBackground");
HttpClient hc = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://192.168.21.74/mynetwork/formapi/top_feeds");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("from", "0"));
nameValuePairs.add(new BasicNameValuePair("to", "10"));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse rp = hc.execute(postMethod);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(rp.getEntity());
Log.v("suggestion_data", "" + result);
JSONArray jsonary = new JSONArray(result);
for (int i = 0; i < jsonary.length(); i++) {
//Log.v("jsonary.length", "" +jsonary.length());
String sr = ""+jsonary.getJSONObject(i);
//Log.v("sr", "" +sr);
JSONObject jobj = new JSONObject(sr);
Log.v("======================", "=================" );
Log.v("feed_id", "" +jobj.getString("feed_id"));
Log.v("feed_message", "" +jobj.getString("feed_message"));
Log.v("user_id", "" +jobj.getString("user_id"));
Log.v("username", "" +jobj.getString("username"));
Log.v("======================", "=================" );
msgvector.add(""+jobj.getString("feed_message").toString().trim());
usernamevector.add("" +jobj.getString("username").toString().trim());
feedIdvector.add("" +jobj.getString("feed_id").toString().trim());
userIdvector.add("" +jobj.getString("user_id").toString().trim());
}
//for (int i = 0; i < feedIdvector.size(); i++) {
//Log.v("feedIdvector", "" +feedIdvector.elementAt(i));
//}
}else{
Log.d("JSON", "StatusCode "+rp.getStatusLine().getStatusCode());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("AsyncTaskException", e.toString());
}
Log.i("popularAsyncTaskException", e.toString());
}
return null;
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(MainActivity.this,"Wait", "Downloading feeds");
}
#Override
protected void onPostExecute(String result) {
rowfeedlist = new ArrayList<Rowfeeds>();
for (int i = 0; i < msgvector.size(); i++) {
Rowfeeds rowfeeds = new Rowfeeds(msgvector.elementAt(i),usernamevector.elementAt(i),feedIdvector.elementAt(i));
rowfeedlist.add(rowfeeds);
}
Customfeedadapter feedadapter = new Customfeedadapter(getApplicationContext(),R.layout.feeds,rowfeedlist
,feedIdvector,userIdvector);
listview.setAdapter(feedadapter);
simpleWaitDialog.dismiss();
}
private void setupTabs() {
mTabHost.setup(); // you must call this before adding your tabs!
mTabHost.addTab(newTab(TAB_1, R.id.tab_1));
mTabHost.addTab(newTab(TAB_2, R.id.tab_2));
mTabHost.addTab(newTab(TAB_3, R.id.tab_3));
}
private TabSpec newTab(String tag, int tabContentId) {
Log.i("tag", tag);//fff498
Log.i("tabContentId", ""+tabContentId);//fff498
TabSpec spec = mTabHost.newTabSpec(tag);
spec.setContent(tabContentId);
if(tag.equalsIgnoreCase("Open")){
spec.setIndicator("", getResources().getDrawable(R.drawable.feed));
spec.setContent(tabContentId);
}else if(tag.equalsIgnoreCase("Approved")){
spec.setIndicator("", getResources().getDrawable(R.drawable.trend));
spec.setContent(tabContentId);
}else if(tag.equalsIgnoreCase("Decline")){
spec.setIndicator("", getResources().getDrawable(R.drawable.popularr));
spec.setContent(tabContentId);
}
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#fff498"));
}
return spec;
}
public void onTabChanged(String tabId) {
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
}
if (TAB_1.equals(tabId)) {
// updateTab(R.id.tab_1);
mCurrentTab = 0;
//Toast.makeText(getApplicationContext(), "1No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
}
if (TAB_2.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 1;
//Toast.makeText(getApplicationContext(), "2No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
//http://192.168.21.74/mynetwork/formapi/trending
//http://192.168.21.74/mynetwork/formapi/popular
}
if (TAB_3.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 2;
// Toast.makeText(getApplicationContext(), "3No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Xml layout:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ListView
android:id="#+id/tab_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/tab_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/tab_3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</FrameLayout>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0" >
</TabWidget>
</LinearLayout>
</TabHost>
Put all your list views in PullToRefreshLayout and give R.id.tab_1 R.id.tab_2 R.id.tab_3 id's to your PullToRefreshLayout instead of ListView
<uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab_1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>
same for rest of the listview
In java inside onCreate of the activity:
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mPullToRefreshLayout= (ListView)findViewById(R.id.tab_1);
mPullToRefreshLayout1 = (ListView)findViewById(R.id.tab_2);
mPullToRefreshLayout2 = (ListView)findViewById(R.id.tab_3);
listview = (ListView)findViewById(R.id.listview1);
listview1 = (ListView)findViewById(R.id.listview2);
listview2 = (ListView)findViewById(R.id.listview3);
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout);
on tab change:
public void onTabChanged(String tabId) {
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
}
if (TAB_1.equals(tabId)) {
// updateTab(R.id.tab_1);
mCurrentTab = 0;
//Toast.makeText(getApplicationContext(), "1No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout);
}
if (TAB_2.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 1;
//Toast.makeText(getApplicationContext(), "2No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
//http://192.168.21.74/mynetwork/formapi/trending
//http://192.168.21.74/mynetwork/formapi/popular
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout1);
}
if (TAB_3.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 2;
// Toast.makeText(getApplicationContext(), "3No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout2);
}
}