Show ListPopupWindow from PopWindow - android

I have a PopupWindow with a button. On I click on the button I want to show a ListPopupWindow but I get
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#439c79f0 is not valid; is your activity running?
and this is my show() method called onClick(). I get the error on the last line
popup.show();
full:
void showList(View view){
final ListPopupWindow popup = new ListPopupWindow(this);
popup.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Category));
popup.setAnchorView(view);
popup.setWidth(ListPopupWindow.WRAP_CONTENT);
popup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
tvCategory.setText(Category[position]);
popup.dismiss();
}
});
popup.show();
}
FulllActivity code:
public class MapSights extends Activity implements OnMapReadyCallback {
ImageView btnPlus, close_add_sight;
PopupWindow pw, add_sg;
PopupMenu popupMenuCategory;
ListPopupWindow listPopupWindow;
int ONE = 1;
TextView tvCategory;
LinearLayout add_sight_btn;
Context context;
String TAG = "MapSights.java";
private static final String[] Category = { "Amphibian",
"Fish", "Reptile", "Bird","Mammal",
"Miriapode", "Insect", "Arachnid","Shellfish",
"Snail", "Shell", "Slime mold","Fungi",
"Plant", "Anemone", "Coral"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_sights);
Log.d(TAG, "onCreate");
context = getApplicationContext();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
LayoutInflater inflater = (LayoutInflater) MapSights.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View pView = inflater.inflate(R.layout.maplusbtnadds, null, false);
View pViewSight = inflater.inflate(R.layout.add_sighting, null, false);
tvCategory = (TextView) pViewSight.findViewById(R.id.txt_category);
pw = new PopupWindow(pView, 450, 650, false);
add_sg = new PopupWindow(pViewSight, 450, 650, false);
btnPlus = (ImageView) findViewById(R.id.plusBtn);
close_add_sight = (ImageView) pView.findViewById(R.id.close_plus);
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pw.showAtLocation(MapSights.this.findViewById(R.id.map), Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
}
});
close_add_sight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pw.dismiss();
}
});
add_sight_btn = (LinearLayout) pView.findViewById(R.id.add_sight_btn);
add_sight_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add_sg.showAtLocation(MapSights.this.findViewById(R.id.map), Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
}
});
tvCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(v);
}
});
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG,"onResume");
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG,"onStart");
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG,"onStop");
}
void showList(View view){
final ListPopupWindow popup = new ListPopupWindow(this);
popup.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Category));
popup.setAnchorView(view);
popup.setWidth(ListPopupWindow.WRAP_CONTENT);
popup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MapSights.this, "Clicked item " + position, Toast.LENGTH_SHORT).show();
tvCategory.setText(Category[position]);
popup.dismiss();
}
});
popup.show();
}
#Override
public void onMapReady(GoogleMap map) {
// map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
map.setMapType(MAP_TYPE_TERRAIN);
}
}

Change final ListPopupWindow popup = new ListPopupWindow(this);
to
final ListPopupWindow popup = new ListPopupWindow(MapSights.this);
Try to check if the activity is finishing before call popup.show(); to avoid Error is your activity running?
if(!isFinishing()) {
popup.show();
}

Related

clicking on a listview item

I have a ListView in my app and each item in the ListView contains a button and item count in it.While clicking on the button in each item, I want to show a dialogue with an EditText to enter new count of the corresponding item and update the item with the value which i get from the dialogue EditText field.
I created dialogue to enter new count on button click, but can't update the value.
My adapter
public class MyAdapter extends BaseAdapter {
#Override
public int getCount() {
return planList.size();
}
#Override
public Object getItem(int position) {
return planList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SalesModel db_data = planList.get(position);
if (convertView == null) {
convertView = View.inflate(getApplicationContext(), R.layout.return_confirm, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
final TextView stock = (TextView) convertView.findViewById(R.id.stock);
TextView amount = (TextView) convertView.findViewById(R.id.amount);
ImageView minus = (ImageView) convertView.findViewById(R.id.minus);
Double count = Double.parseDouble(db_data.getStock());
Double price = Double.parseDouble(db_data.getSprice());
Double s_price = count*price;
String set_amount = s_price.toString();
name.setText(db_data.getName());
stock.setText(db_data.getStock());
amount.setText(set_amount);
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stock_return = ShowDialogue();
Double n_stock = Double.parseDouble(db_data.getStock())-Double.parseDouble(stock_return);
stock.setText(n_stock.toString());
}
});
return convertView;
}
}
Function to show dialogue
public String ShowDialogue(){
String stk_val;
stock_return = "0.0";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
dialog.setCancelable(false);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.popup_reminder, null);
final EditText stk = (EditText)dialogLayout.findViewById(R.id.stock);
Button ok = (Button)dialogLayout.findViewById(R.id.later );
Button close = (Button)dialogLayout.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(stk.getText().toString().trim().isEmpty()){
stk.setError("Enter quantity");
}
else {
stock_return = stk.getText().toString().trim();
}
}
});
dialog.setView(dialogLayout,0,0,0,0);
dialog.show();
return stock_return;
}
you doing something wrong.
Dialog cannot return before you enter ok button.
Try like this :
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stock_return = ShowDialogue(this, position);
}
});
Change dialog to accordance with it like this..
public void ShowDialogue(MyAdapter myAdapter, int position){
String stk_val;
stock_return = "0.0";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
dialog.setCancelable(false);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.popup_reminder, null);
final EditText stk = (EditText)dialogLayout.findViewById(R.id.stock);
Button ok = (Button)dialogLayout.findViewById(R.id.later );
Button close = (Button)dialogLayout.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(stk.getText().toString().trim().isEmpty()){
stk.setError("Enter quantity");
}
else {
planList.get(position).setStock(stk.getText().toString().trim());
dialog.dismiss();
myAdapter.notifyDataSetChanged();
}
}
});
dialog.setView(dialogLayout,0,0,0,0);
dialog.show();
}

CustomAdapter does not show any items in Listview

I want to display user chats from a Firebase List in a ListView with a custom Adapter. But somehow it does not work. I get a response when I try to look at the data in the logcat but when I pass the list to the CustomAdapter it does not display anything in my ListView. What is the issue?
My Adapter:
public class ChatAdapter extends ArrayAdapter<String> {
private Activity context;
private List<Chats> chatsList = new ArrayList<>();
public ChatAdapter(Activity Context, List<Chats> chatsList) {
super(Context, R.layout.abc_main_chat_item);
this.context = Context;
this.chatsList = chatsList;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.abc_main_chat_item, null, true);
TextView tvusername = (TextView) listViewItem.findViewById(R.id.group_name);
TextView tvuid = (TextView) listViewItem.findViewById(R.id.useruid);
TextView tvlastmessage = (TextView) listViewItem.findViewById(R.id.latestMessage);
TextView tvlastmessagetime = (TextView) listViewItem.findViewById(R.id.latestMessageTime);
ImageView ivphoto = (ImageView) listViewItem.findViewById(R.id.profileImg);
tvusername.setText(chatsList.get(position).getUsername());
tvlastmessage.setText(chatsList.get(position).getLastMessage());
tvlastmessagetime.setText(chatsList.get(position).getLastMessageTime());
tvuid.setText(chatsList.get(position).getUseruid());
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(ivphoto);
listViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, Chat_Room.class);
i.putExtra("room_name", chatsList.get(position).getUsername());
i.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(i);
}
});
listViewItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_listview_alertdia_layout);
ArrayList<String> list_of_chats = new ArrayList<>();
final ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list_of_chats);
list_of_chats.add(0, "Chatverlauf mit "+ chatsList.get(position).getUsername()+" löschen?");
list_of_chats.add(1, "Profil von "+chatsList.get(position).getUsername()+" anschauen");
arrayAdapter.notifyDataSetChanged();
final ListView lv = (ListView) dialog.findViewById(R.id.lv);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position2, long id) {
if (position2 == 0) {
dialog.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Chatverlauf mit "+chatsList.get(position).getUsername()+" löschen?")
.setMessage("Du kannst das Löschen nicht rückgängig machen. Bist du dir sicher?")
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(chatsList.get(position).getUseruid()).setValue(null);
FirebaseDatabase.getInstance().getReference().child("chats").child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("messages").child(chatsList.get(position).getUseruid()).setValue(null);
}
}).setCancelable(true)
.show();
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
if (position2 == 1) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
}
});
dialog.show();
return true;
}
});
ivphoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_profile_pic_dialog_layout);
ImageView imageView = (ImageView) dialog.findViewById(R.id.alertImage);
TextView textView = (TextView)dialog.findViewById(R.id.alertdialogtv);
ImageView message = (ImageView)dialog.findViewById(R.id.alertMessage);
ImageView profile = (ImageView)dialog.findViewById(R.id.alertProfile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
dialog.dismiss();
}
});
message.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Chat_Room.class);
intent.putExtra("room_name", chatsList.get(position).getUsername());
intent.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
});
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(imageView);
textView.setText(chatsList.get(position).getUsername());
dialog.setCancelable(true);
dialog.show();
}
});
return listViewItem;
}
...
}
And this is how I get the data for the List:
FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(myUiD).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<chatapp.chatapp2.Chats.Chats> chatsList = new ArrayList<chatapp.chatapp2.Chats.Chats>();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
chatapp.chatapp2.Chats.Chats chats = new chatapp.chatapp2.Chats.Chats();
chats.setUsername(snapshot.child("roomname").getValue().toString());
chats.setPhotoURL(snapshot.child("photoURL").getValue().toString());
chats.setLastMessage(snapshot.child("lastMessage").getValue().toString());
chats.setLastMessageTime(snapshot.child("lastMessageTime").getValue().toString());
chats.setUseruid(snapshot.child("userUiD").getValue().toString());
chatsList.add(chats);
Log.d("CHATS", chats.getUsername());
Log.d("CHATS", chats.getUseruid());
}
ChatAdapter chatAdapter = new ChatAdapter(getActivity(), chatsList);
chatAdapter.notifyDataSetChanged();
listView.setAdapter(chatAdapter);
listView.setVisibility(View.VISIBLE);
}
...
});
I dont really know why it does not worked, but I found the Solution:
You have to override the getCount method like this:
#Override
public int getCount() {
return chatsList == null ? 0 : chatsList.size();
}
I do not know what it does but it works :) :)

Overlay listview at bottom of viewpager and focus on current item

Hello Everyone I am Developing one Gallery app.
I have implemented Gridview and displayed images from server.when click on that image it will open one dialog and dialog contain viewpager and listview at bottom.
According to the viewpager position image it will smooth slide listview also.
Problem:I want to display overlay layer on listview and display only current item focused and other item are looks like blurish.
Here is my code
imagelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
imagdialog = new Dialog(MainActivity.this);
imagdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
imagdialog.setContentView(R.layout.imagelist);
imagdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(final DialogInterface arg0) {
// recreate();
selectedAdapter = new Sadapter(getApplicationContext(), arraylist);
imagelist.setAdapter(selectedAdapter);
}
});
photoid = arraylist.get(i).getId();
Log.v("Photoid111", "" + photoid);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(imagdialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER;
imagdialog.getWindow().setAttributes(lp);
viewpager = (ViewPager) imagdialog.findViewById(R.id.img);
final Button accept = (Button) imagdialog.findViewById(R.id.accept);
final Button reject = (Button) imagdialog.findViewById(R.id.reject);
final EditText cmnts = (EditText) imagdialog.findViewById(R.id.comnt);
ImageView closewin = (ImageView) imagdialog.findViewById(R.id.search_close_btn);
imglist = (RecyclerView) imagdialog.findViewById(R.id.imglist);
LinearLayoutManager sublimationmanager
= new LinearLayoutManager(imagdialog.getContext(), LinearLayoutManager.HORIZONTAL, false);
imglist.setLayoutManager(sublimationmanager);
cmnts.setText("" + arraylist.get(i).getCmnts());
cmnts.setSelection(cmnts.getText().length());
adaptor = new ViewPager_Adaptor(MainActivity.this, arraylist);
viewpager.setAdapter(adaptor);
viewpager.setCurrentItem(i);
img_adaptor = new Image_list(getApplicationContext(), arraylist);
imglist.setAdapter(img_adaptor);
imglist.smoothScrollToPosition(i);
pos = i;
viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
photoid = arraylist.get(position).getId();
Log.v("Photoid", "" + photoid);
cmnts.setText("" + arraylist.get(position).getCmnts());
cmnts.setSelection(cmnts.getText().length());
imglist.smoothScrollToPosition(position);
pos = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
closewin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagdialog.dismiss();
selectedAdapter = new Sadapter(getApplicationContext(), arraylist);
imagelist.setAdapter(selectedAdapter);
}
});
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comments = cmnts.getText().toString();
Log.v("Photoid", "" + photoid);
Log.v("Photoid", "" + comments);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
mdialog = new Dialog(MainActivity.this);
mdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mdialog.setContentView(R.layout.custom_progress_dialog);
mdialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
mdialog.setCancelable(false);
mdialog.show();
new Accept().execute(URL.amateurpath + "Accept");
} else {
if (imagdialog.isShowing())
imagdialog.dismiss();
nonetwork.setVisibility(View.VISIBLE);
main_layout.setVisibility(View.GONE);
noimg.setVisibility(View.GONE);
}
}
});
reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comments = cmnts.getText().toString();
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
mdialog = new Dialog(MainActivity.this);
mdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mdialog.setContentView(R.layout.custom_progress_dialog);
mdialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
mdialog.setCancelable(false);
mdialog.show();
new Reject().execute(URL.amateurpath + "Reject");
} else {
if (imagdialog.isShowing())
imagdialog.dismiss();
nonetwork.setVisibility(View.VISIBLE);
main_layout.setVisibility(View.GONE);
noimg.setVisibility(View.GONE);
}
}
});
imagdialog.show();
}
});
Here is my Viewpager Adaptor
public class ViewPager_Adaptor extends PagerAdapter {
private Context context;
ArrayList<CustomImages> data;
private LayoutInflater layoutInflater;
public ViewPager_Adaptor(Context context, ArrayList<CustomImages> arraylist) {
// TODO Auto-generated constructor stub
this.context = context;
data = arraylist;
Log.d("Abhi", data.toString());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("DATASIZE", String.valueOf(data.size()));
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemview = layoutInflater.inflate(R.layout.viewpager_img, container, false);
final ImageView iimg = (ImageView) itemview.findViewById(R.id.imageview1);
ImageView clockw = (ImageView) itemview.findViewById(R.id.clock);
ImageView anticlockw = (ImageView) itemview.findViewById(R.id.anticlock);
clockw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
iimg.setRotation(iimg.getRotation() + 90);
}
});
anticlockw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
iimg.setRotation(iimg.getRotation() - 90);
}
});
Picasso.with(MainActivity.this).load(data.get(position).getUrl().replaceAll(" ", "%20")).placeholder(R.drawable.temp_img).error(R.drawable.no_media).into(iimg);
iimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intnt = new Intent(MainActivity.this, ImageShow.class);
intnt.putExtra("photo", data.get(position).getPhoto());
intnt.putExtra("url", data.get(position).getUrl());
startActivity(intnt);
}
});
container.addView(itemview);
return itemview;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
And finally Listview adapter is as follows
public class Image_list extends RecyclerView.Adapter<Image_list.MyViewHolder> {
ArrayList<CustomImages> arraylist1;
Context c;
public Image_list(Context c, ArrayList<CustomImages> arraylist) {
this.arraylist1 = arraylist;
this.c = c;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.inflate_image_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Log.v("Position of i", "" + pos);
// if (pos == position) {
// holder.img.setBackgroundResource(R.drawable.border);
// } else {
//
// }
Picasso
.with(this.c)
.load(arraylist1.get(position).getUrl().replaceAll(" ", "%20"))
.placeholder(R.drawable.temp_img) // can also be a drawable
.placeholder(R.drawable.temp_img)
.error(R.drawable.no_media)
.into(holder.img);
}
#Override
public int getItemCount() {
return arraylist1.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView img;
public MyViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.catimg);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition();
viewpager.setCurrentItem(position);
}
});
}
}
}
Problem:I want to display overlay layer on listview and display only current item focused and other item are looks like blurish.
As concern to the problem i managed to slide list according to the viewpager slide but i want to display blurissh image and focus only one image from listview which is displayed in viewpager.
And display image from list at right of screen which is displayed in viewpager
Whenever one item is selected in the viewPager get the position of that item. Save the position of that item in a variable viewPagerPosition in the adapter. Then refresh the adapter by calling notifyDataSetChanged().
In the adapter have a view with certain transparency and make that visible as default.In adapter's onBindViewHolder check
if(position = viewPagerPosition){
transparentView.setVisibility(GONE);
} else{
transparentView.setVisibility(VISIBLE);
}
This should make the current view highlighted and other dimmed. If you want blur then you can use blur with the same condition.

After using file.delete() file is still in phone storage with length zero

When I reopen my app file is present and have length zero.
How to delete it permanently?
I am using the list view to display all song in external storage using Media Store and added delete option to it.
After deleting the file when I reopen my app song file is again in list view but with file length zero.
Please see onClickListener for delete:
public class TracksFragment extends Fragment {
songDetailloader loader = new songDetailloader();
ArrayList<Songs> give = new ArrayList<>();
public int pos = -1;
MediaPlayer mp ;
MusicService musicService;
boolean mBound;
Context context;
public TracksFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.listviewofsongs,container,false);
final ListView listView = (ListView) v.findViewById(R.id.listView);
loader.set(getContext());
give = loader.allsongs();
final ListViewAdapter listViewAdapter = new ListViewAdapter(getContext(),give);
listView.setAdapter(listViewAdapter);
listView.setSelector(R.drawable.selector);
new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getActivity(),MusicService.class);
getActivity().bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
}).start();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d("Uri of ",""+give.get(position).getSonguri());
musicService.setplaylist(give,position);
musicService.setMediaPlayer();
view.setSelected(true);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View v =LayoutInflater.from(getContext()).inflate(R.layout.select_dialog_layout,null);
builder.setView(v);
builder.setTitle(give.get(position).gettitle()+"\n "+give.get(position).getalbum());
builder.create();
final AlertDialog d=builder.show();
//seting click listner.....
TextView play = (TextView) v.findViewById(R.id.dialogplay);
TextView playnext = (TextView) v.findViewById(R.id.dialogplaynext);
TextView queue = (TextView) v.findViewById(R.id.dialogqueue);
TextView fav = (TextView) v.findViewById(R.id.dialogaddtofav);
TextView album = (TextView) v.findViewById(R.id.dialogalbum);
TextView artist = (TextView) v.findViewById(R.id.dialogartist);
TextView playlist = (TextView) v.findViewById(R.id.dialogaddtoplaylsit);
TextView share = (TextView) v.findViewById(R.id.dialogshare);
TextView delete = (TextView) v.findViewById(R.id.dialogdelete);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File f= new File(give.get(position).getSonguri().getLastPathSegment());
Log.d("LENGTH IS",""+f.length());
musicService.setplaylist(give,position);
musicService.setMediaPlayer();
d.dismiss();
}
});
playnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
queue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
DataBaseClass db = new DataBaseClass(getContext());
int i=db.insetintoliked(give.get(position));
if(i==1)
{
Toast.makeText(getContext(),"Added to Favorites",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getContext(),"Already in Favorites",Toast.LENGTH_SHORT).show();
}
});
album.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",give.get(position).getalbum());
i.putExtras(b);
startActivity(i);
}
});
artist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setMessage("Audio '"+give.get(position).gettitle()+"' will be deleted permanently !");
b.setTitle("Delete ?");
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
b.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
loader.deleteSong(getContext(),give.get(position).getPosition());
File f= new File(give.get(position).getSonguri().getPath());
boolean b = f.delete();
Log.d("Is file exist",f.exists()+"");
Log.d("File Length",""+f.length());
Log.d("Return value",""+b);
give.remove(position); // give is Arraylist of Songs(datatype);
listViewAdapter.notifyDataSetChanged();
if(b)
{
Toast.makeText(getContext(),"Deleted",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getContext(),"Fail to Delete",Toast.LENGTH_SHORT).show();
}
}
});
b.create().show();
d.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");`enter code here`
share.putExtra(Intent.EXTRA_STREAM, give.get(position).getSonguri());
startActivity(Intent.createChooser(share, "Share Sound File"));
}
});
return true;
}
});
container.addView(v);
return v;
}
}
LogCat:
01-14 05:19:54.189 18010-18010/com.developmentforfun.mdnafiskhan.mp3player D/Is file exist: false
01-14 05:19:54.190 18010-18010/com.developmentforfun.mdnafiskhan.mp3player D/File Lenth:0
01-14 05:19:54.190 18010-18010/com.developmentforfun.mdnafiskhan.mp3player D/Return value: false

pass data from fragment inside view pager to another activity

i hope you guys can help me. it`s drivin me crazy find the solution...
i already read some question that similar with my problems, but none solved mine.
here`s the problems
1 have 2 activity...
first --> i have activity that contain a view pager which hold 3 tab fragment.
in this first activity i extends with fragmentActivity
and here the code
public class A_BonRokok_Add_Main_Paged extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Header", "Item", "Info"};
MainActivity main = new MainActivity();
FragmentManager manager;
FragmentTransaction transaction;
Dialog alert;
LayoutInflater li;
LinearLayout someLayout;
Button btnSave_dialog;
Button btnCancel_dialog;
public EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_bon_rokok_add_main_paged);
FragmentPagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
getActionBar().setDisplayHomeAsUpEnabled(true);
pager.setOffscreenPageLimit(3);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_print) {
Toast.makeText(this, "print", Toast.LENGTH_SHORT).show();
}
else if (item.getItemId() == R.id.edit_save) {
Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();
}
else{
createDialogConfirm();
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
public void onBackPressed(){
createDialogConfirm();
}
public void createDialogConfirm(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert.show();
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt(ChildFragmentPaged.POSITION_KEY, position);
return ChildFragmentPaged.newInstance(args);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
}
public static A_BonRokok_Add_Main_Paged newInstance() {
return new A_BonRokok_Add_Main_Paged();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.save_print, menu);
return super.onCreateOptionsMenu(menu);
}
}
the first activity manage the tab fragment using class which extends fragment...
here the code
public class ChildFragmentPaged extends Fragment {
public static final String POSITION_KEY = "FragmentPositionKey";
private int position;
View root;
static EditText txtDate, txtGudang;
static RadioGroup btnGroupGudang;
static RadioButton btnGudang1, btnGudang2;
static Button btnNewItem, btnNewItem_Cancel;
private database mySQLiteAdapter;
private A_BonRokok_Item_View view = new A_BonRokok_Item_View();
public ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
AdapterView<?> tempAdt;
int tempPos;
public EditText search;
public ArrayList<bonRokokPagedEntity> list;
public ListViewAdapter adapter;
private databasePaged databasePaged;
public static ChildFragmentPaged newInstance(Bundle args) {
ChildFragmentPaged fragment = new ChildFragmentPaged();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
position = getArguments().getInt(POSITION_KEY);
if(position == 0){
root = inflater.inflate(R.layout.t_bon_rokok_header_paged, container,false);
}if (position == 1) {
root = inflater.inflate(R.layout.t_bon_rokok_item_paged, container, false);
settingTabItem();
} else if (position == 2)
root = inflater.inflate(R.layout.t_bon_rokok_info_paged, container, false);
return root;
}
public void settingTabItem() {
listContent = (ListView) root.findViewById(R.id.vl_tab_paged);
btnNewItem = (Button) root.findViewById(R.id.btnNewItem_paged);
search = (EditText)root.findViewById(R.id.search_paged);
try{
databasePaged = new databasePaged(getActivity());
databasePaged.createDataBase();
}catch(IOException ioe){
throw new Error("Unable to craete database");
}
try{
databasePaged.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
btnNewItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(),A_BonRokok_Item_New_Paged.class);
startActivity(intent);
getActivity().finish();
}
});
list = databasePaged.Getvalue();
adapter = new ListViewAdapter(getActivity(), list);
listContent.setAdapter(adapter);
}
private void updateList() {
cursor.requery();
}
public void createMenu(){
final Cursor cursor = (Cursor) tempAdt.getItemAtPosition(tempPos);
final String header = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.d_global_edit_delete,null, false);
ListView lv = (ListView)contentView.findViewById(R.id.d_globalEditDelete_lvEditDelete);
TextView txtHeader = (TextView)contentView.findViewById(R.id.d_globalEditDelete_lblHeader);
Button btnCancel = (Button)contentView.findViewById(R.id.d_globalEditDelete_btnCancel);
txtHeader.setText(header);
ArrayList<String> tempData = new ArrayList<String>();
tempData.add("Edit");
tempData.add("Delete");
int layoutID = android.R.layout.simple_list_item_1;
ArrayAdapter tempAdapter = new ArrayAdapter<String>(getActivity(), layoutID, tempData);
lv.setAdapter(tempAdapter);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(contentView);
final AlertDialog alert = builder.create();
alert.show();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
if (position == 0){ //Edit Data
passStringValue();
updateList();
Intent intent = new Intent(getActivity(),A_BonRokok_Item_View.class);
intent.putExtra("status", true);
startActivity(intent);
getActivity().finish();
}
else if (position == 1){ //Delete Data
final int item_id = cursor.getInt(cursor.getColumnIndex(database.KEY_ID));
mySQLiteAdapter.delete_byID(item_id);
updateList();
alert.cancel();
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
}
public void passStringValue(){
final String nama_Rokok = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
final String kode_Rokok = "102030";
final String pita_Cukai = cursor.getString(cursor.getColumnIndex(database.SPITACUKAI));
final String jumlah = cursor.getString(cursor.getColumnIndex(database.SJUMLAH));
view.Detail(nama_Rokok, kode_Rokok, pita_Cukai, jumlah);
}
}
and the second --> i have activity that contain an edittext.
here the code
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(contentView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
});
// txtSelop.setOnFocusChangeListener(focusSelopChange);
// txtBungkus.setOnFocusChangeListener(focusBungkusChange);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_save) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
} else {
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save_print, menu);
MenuItem item = menu.findItem(R.id.edit_print);
item.setVisible(false);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
OnClickListener searchClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
createDialogSearch();
}
};
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> hm = (HashMap<String, String>)arg0.getAdapter().getItem(position);
autoCompleteBonRokok.setText(hm.get("kdRokok"));
txtNamaRokok.setText(hm.get("namaRokok"));
}
};
public void onBackPressed(){
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
OnFocusChangeListener focusBalChange = new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean isFocused) {
if(!isFocused){
if(txtBal.length()==0)
bal = 0;
else
bal = Integer.parseInt(txtBal.getText().toString());
splitValue();
}
}
};
public void saveToDatabase() {
}
private void updateList() {
cursor.requery();
}
public void createDialogSearch(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout)li.inflate(R.layout.d_bon_rokok_search_new_item, null);
DialogDummyAutoComplete[] modelItemsDialog;
final ListView lvDialog = (ListView)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_lvSearch);
modelItemsDialog = new DialogDummyAutoComplete[3];
modelItemsDialog [0] = new DialogDummyAutoComplete("1051200", "Supra need 12");
modelItemsDialog [1] = new DialogDummyAutoComplete("1051600", "Supra need 16");
modelItemsDialog [2] = new DialogDummyAutoComplete("1001200", "NY");
DialogAutoCompleteSearchRokok dialogAdapter = new DialogAutoCompleteSearchRokok(this, modelItemsDialog);
lvDialog.setAdapter(dialogAdapter);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.getWindow().getAttributes().height = LayoutParams.WRAP_CONTENT;
alert.show();
btnCancel = (Button)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
String selectedKdRokok = ((TextView)arg1.findViewById(R.id.kdRokok_dialog)).getText().toString();
String selectedNamaRokok = ((TextView)arg1.findViewById(R.id.namaRokok_dialog)).getText().toString();
autoCompleteBonRokok.setText(selectedKdRokok);
txtNamaRokok.setText(selectedNamaRokok);
alert.cancel();
}
});
}
public void splitValue(){
if (txtJumlah.length()==0)
txtJumlah.setText("0,000");
separated = txtJumlah.getText().toString().split(",");
first = separated[0];
second = separated[1];
first = Integer.toString(bal);
txtJumlah.setText(first + "," + second);
txtJumlah.clearFocus();
}
public void createDialogConfirm(){
LayoutInflater li = LayoutInflater.from(this);
LinearLayout someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
Button btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
Button btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.show();
}
}
My question is
how can i pass a value from second activity (contain edittext) to fragment in view pager, because everytime i try to insert using many way, java lang null pointer always become my nightmare...
please help me... thx you so much
Intent.putExtra("YourValueKey", datatobepassed);
on the other activity
Bundle extras = getIntent().getExtras();
if ( extras != null ){
extras.get("YourValueKey")
}

Categories

Resources