I have a listview in which list item's background highlights while a notification arrives but the problem is that when I scroll the list then items changes highlighting. Suppose initially first item was listed when I scroll down then another item highlights. I have also used notifysetdatachanged.
Code for List Activity
public class NewPageActivity extends Fragment{
// this is my notification code when notifcation arrives
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(
"unique_name");
mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
String msg_for_me = intent.getStringExtra("message");
//log our message value
Log.e("TAG", "onReceive: boradcast" + msg_for_me);
if (msg_for_me.contains("&")) {
String msg1[] = msg_for_me.split("&");
if (msg1[0].contains("Waiting for acceptance...")) {
edit.putInt("newTabHighlight", sp.getInt("newTabHighlight", 0) + 1);
edit.putString("newOrder", sp.getString("newOrder", null) + "&" + msg1[1].split("=")[1]);
edit.putInt("reminderTab", sp.getInt("reminderTab", 0) + 1);
edit.putInt("newOrderCount", 1);
edit.commit();
connectToDatabase();
}
}
// code for when get data through web service and set adapter
if(getActivity()!= null) {
adapter = new customadapetr_new(dataModels, getActivity(), NewPageActivity.this);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
setListViewHeightBasedOnChildren(list);
}
}
// code for adapter where background highlights
private void setNewCardBackground(final String Order_id, final RelativeLayout MenuCard, String OrderFlag)
{
Log.e("TAG", "setNewCardBackground: " );
newOrder = sp.getString("newOrder", "null");
if (newOrder.contains("&")) {
newOrderArray = newOrder.split("&");
Log.e("TAG", "setNewCardBackground:order "+newOrderArray);
for (int i = 0; i < newOrderArray.length; i++) {
if (Order_id.equals(newOrderArray[i])) {
MenuCard.setBackgroundResource(R.drawable.highlightedorder);
MenuCard.setPadding(20,10,20,10);
newOrderlength++;
break;
}
// custom adapter get view code
#Override
public View getView(final int position, View vv, ViewGroup parent) {
menuModels= new ArrayList<>();
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
final DataModel data=dataSet.get(position);
if (vv == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
vv = inflater.inflate(R.layout.adapter_listview_newpage_card, parent, false);
viewHolder.rupee=(TextView)vv.findViewById(R.id.rupee);
viewHolder.dateandtime=(TextView)vv.findViewById(R.id.dateandtime);
viewHolder.modeofpayment=(TextView)vv.findViewById(R.id.modeofpayment);
viewHolder.location=(TextView)vv.findViewById(R.id.location);
viewHolder.customerName=(TextView)vv.findViewById(R.id.customerName);
viewHolder.orderId = (TextView)vv.findViewById(R.id.orderId);
viewHolder.order_time = (TextView) vv.findViewById(R.id.order_time);
viewHolder.menucard = (RelativeLayout) vv.findViewById(R.id.menucard);
viewHolder.accept = (ImageView) vv.findViewById(R.id.accept);
viewHolder.statustext = (TextView)vv.findViewById(R.id.statustext);
viewHolder.orderstatus = (TextView) vv.findViewById(R.id.orderstatus);
viewHolder.order_card_layout =(RelativeLayout) vv.findViewById(R.id.order_card_layout);
viewHolder.progressBar = (PlayGifView) vv.findViewById(R.id.progressBar);
viewHolder.progressBar.setImageResource(R.drawable.renewedloader);
viewHolder.showhide =(ImageView) vv.findViewById(R.id.showhide);
viewHolder.comments = (TextView) vv.findViewById(R.id.comments);
viewHolder.expanded_menulist =(ListView) vv.findViewById(R.id.menulist1);
viewHolder.expanded_menulist.setVisibility(View.GONE);
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
height = metrics.heightPixels;
width = metrics.widthPixels;
sp =mContext.getSharedPreferences("afewtaps", Context.MODE_PRIVATE);
face = Typeface.createFromAsset(mContext.getAssets(), "fonts/Nunito-Regular.ttf");
face1 = Typeface.createFromAsset(mContext.getAssets(), "fonts/Rupee_Foradian_2.ttf");
int size = dataSet.size();
String menu=data.getMenu();
viewHolder.listview=(ListView)vv.findViewById(R.id.menulist);
setListViewHeightBasedOnChildren(viewHolder.listview);
String paynt = data.getPaymemt_method();
final String order_id = data.getOrder_id();
final String Order_flag = data.getOrder_flag();
setNewCardBackground(order_id, viewHolder.menucard,Order_flag );
String orderEscalation = data.getOrder_escalated();
setEscalation(viewHolder.statustext, viewHolder.accept, viewHolder.orderstatus, order_id, orderEscalation);
int time = Integer.parseInt(data.getTimer_time());
setTime(time, viewHolder.order_time);
// menucard item
comment_value = data.getOrder_comments();
viewHolder.accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeListItem(viewHolder.order_card_layout, position);
objNewPageActivity.SendOrder(data.getOrder_id());
}
});
viewHolder.customerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCustomerProfile(order_id, mContext);
}
});
try {
JSONArray jsonArray1 = new JSONArray(menu);
String orderMenu[][] = new String[jsonArray1.length()][4];
int j;
for (j = 0; j < jsonArray1.length(); j++) {
menumodel = new MenuItemModel();
JSONObject ob2 = jsonArray1.getJSONObject(j);
// String menu_name, menu_qty, menu_price;
String menu_veg_type = ob2.getString("type");
menumodel.setMenuitem_type(menu_veg_type);
String menu_name = ob2.getString("item");
menumodel.setMenuitem_name(menu_name);
String menu_qty = ob2.getString("qty");
menumodel.setMenuitem_qty(menu_qty);
String menu_price = ob2.getString("price");
menumodel.setMenuitem_price(menu_price);
menuModels.add(menumodel);
}
viewHolder.listview.setAdapter(new MyAdapter(mContext,menuModels));
setListViewHeightBasedOnChildren(viewHolder.listview);
viewHolder.expanded_menulist.setAdapter(new Expanded_Menu_Adapter(mContext,menuModels));
//setListViewHeightBasedOnChildren(viewHolder.expanded_menulist);
}catch (Exception e)
{
}
int menuArrayLenghth = menuModels.size();
if(menuArrayLenghth > 2)
{
viewHolder.showhide.setVisibility(View.VISIBLE);
}
else
{
viewHolder.showhide.setVisibility(View.GONE);
}
result=vv;
vv.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) vv.getTag();
result=vv;
}
lastPosition = position;
viewHolder.dateandtime.setText(data.getOrder_time());
viewHolder.modeofpayment.setText(data.getPaymemt_method());
viewHolder.location.setText(data.getCustomer_location());
// amount
String amounttext = "` " + data.getPrice();
SpannableStringBuilder mySpannable = new SpannableStringBuilder(amounttext);
mySpannable.setSpan(new CustomTypefaceSpan("", face1), 0, 1, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
mySpannable.setSpan(new CustomTypefaceSpan("", face), 2, data.getPrice().length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
viewHolder.rupee.setText(mySpannable);
viewHolder.customerName.setText(data.getCustomer_name());
viewHolder.orderId.setText(data.getOrder_id());
if(!(comment_value.equals("0"))){
viewHolder.comments.setVisibility(View.VISIBLE);
viewHolder.comments.setText(data.getOrder_comments());
}
else
{
viewHolder.comments.setVisibility(View.GONE);
}
viewHolder.showhide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(viewHolder.listview.getVisibility() == View.VISIBLE)
{
viewHolder.expanded_menulist.setVisibility(View.VISIBLE);
viewHolder.listview.setVisibility(View.GONE);
viewHolder.showhide.setImageResource(R.drawable.blackarrrowup);
if(!(comment_value.equals("0"))){
viewHolder.comments.setVisibility(View.VISIBLE);
viewHolder.comments.setText(data.getOrder_comments());
}
else
{
viewHolder.comments.setVisibility(View.GONE);
}
}
else if(viewHolder.expanded_menulist.getVisibility() == View.VISIBLE) {
viewHolder.expanded_menulist.setVisibility(View.GONE);
viewHolder.listview.setVisibility(View.VISIBLE);
viewHolder.showhide.setImageResource(R.drawable.blackarrow);
viewHolder.comments.setVisibility(View.GONE);
}
}
});
return vv;
}
The problem could be caused by Views being recycled by the Adapter: when you scroll down/up the highlighted View gets recycled and used at another position in the ListView. You could set the background color of each View to the default color in your adapter's getView. This way the backround color of the recycled View will be set to back to normal before it's displayed again.
Related
I was working with trafficstats app from the below link:
datastats app github
The above app when run gives traffic data from when the device was booted.
I need the data traffic in the last hour or so.
So is there a way to initialise the counter to 0 by pressing button? So far I am stuck at this:
public class main extends Activity {
private TextView tvSupported, tvDataUsageWiFi, tvDataUsageMobile, tvDataUsageTotal;
private ListView lvApplications;
private long dataUsageTotalLast = 0;
ArrayAdapter < ApplicationItem > adapterApplications;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvSupported = (TextView) findViewById(R.id.tvSupported);
tvDataUsageWiFi = (TextView) findViewById(R.id.tvDataUsageWiFi);
tvDataUsageMobile = (TextView) findViewById(R.id.tvDataUsageMobile);
tvDataUsageTotal = (TextView) findViewById(R.id.tvDataUsageTotal);
if (TrafficStats.getTotalRxBytes() != TrafficStats.UNSUPPORTED && TrafficStats.getTotalTxBytes() != TrafficStats.UNSUPPORTED) {
handler.postDelayed(runnable, 0);
initAdapter();
lvApplications = (ListView) findViewById(R.id.lvInstallApplication);
lvApplications.setAdapter(adapterApplications);
} else {
tvSupported.setVisibility(View.VISIBLE);
}
}
public Handler handler = new Handler();
public Runnable runnable = new Runnable() {
public void run() {
//----------------
final long mob1 = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
final long tot1 = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
//-----------------
Button bres = (Button) findViewById(R.id.resetid);
bres.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mob1 = 0;
}
});
//-----------------
long mobile = mob1;
long total = tot1;
tvDataUsageWiFi.setText("" + (total - mobile) / 1024 + " Kb");
tvDataUsageMobile.setText("" + mobile / 1024 + " Kb");
tvDataUsageTotal.setText("" + total / 1024 + " Kb");
if (dataUsageTotalLast != total) {
dataUsageTotalLast = total;
updateAdapter();
}
handler.postDelayed(runnable, 5000);
}
};
public void initAdapter() {
adapterApplications = new ArrayAdapter < ApplicationItem > (getApplicationContext(), R.layout.item_install_application) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ApplicationItem app = getItem(position);
final View result;
if (convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_install_application, parent, false);
} else {
result = convertView;
}
TextView tvAppName = (TextView) result.findViewById(R.id.tvAppName);
TextView tvAppTraffic = (TextView) result.findViewById(R.id.tvAppTraffic);
// TODO: resize once
final int iconSize = Math.round(32 * getResources().getDisplayMetrics().density);
tvAppName.setCompoundDrawablesWithIntrinsicBounds(
//app.icon,
new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(
((BitmapDrawable) app.getIcon(getApplicationContext().getPackageManager())).getBitmap(), iconSize, iconSize, true)),
null, null, null
);
tvAppName.setText(app.getApplicationLabel(getApplicationContext().getPackageManager()));
tvAppTraffic.setText(Integer.toString(app.getTotalUsageKb()) + " Kb");
return result;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public Filter getFilter() {
return super.getFilter();
}
};
// TODO: resize icon once
for (ApplicationInfo app:
getApplicationContext().getPackageManager().getInstalledApplications(0))
{
ApplicationItem item = ApplicationItem.create(app);
if (item != null) {
adapterApplications.add(item);
}
}
}
public void updateAdapter() {
for (int i = 0, l = adapterApplications.getCount(); i < l; i++) {
ApplicationItem app = adapterApplications.getItem(i);
app.update();
}
adapterApplications.sort(new Comparator < ApplicationItem > () {
#Override
public int compare(ApplicationItem lhs, ApplicationItem rhs) {
return (int)(rhs.getTotalUsageKb() - lhs.getTotalUsageKb());
}
});
adapterApplications.notifyDataSetChanged();
}
}
The above code is the modified snippet from the github link.
i tried by declaring a button inside a runnable , but the variable needs to be declared final which results in the variable being unchangable.
Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}
I have a listView of items.Each item has two separate fragment inside it and gets visible when the item is clicked. Inside a fragment there is another ListView and a button. The button displays a dialog through which ListView inside the fragment gets populated.The problem is when the dialog closes,the parent listview gets refreshed and as a result fragment visibility is gone. I have to click the parent list view item again to see the fragment and its content. I want the Fragment view and its updated content remain viewed after the dialog is dismissed. So someone please help me in it.
The following is my parent listView class:
#SuppressLint("NewApi")
public class Due extends FragmentActivity implements
OutletformAddDialog_due.DonebuttonListener {
TextView headerView;
View tempstore, imagetempstore;
OutletformAddDialog_due selectedOutlet;
Fragment fr;
public BaseAdapter dueadapter;
ListView Duelist;
Boolean DuedetailFlag = false, OrderdetailFlag = false;
TextView DueDetailsRight, DueDetailsTop, DueDetailsBottom,
DueDetailsrightHorizontal, OrderDetailsleft, OrderDetailstop,
OrderDetailsBottom, OrderDetailsleftHorizontal, DueDetailsButton,
OrderDetailsButton, btnDueNav, tvOutletName;
Button DuetoCallCard;
int index;
public int getIndex() {
return index;
}
private String order_id;
private String outlet_id;
private String amount;
private String date;
private int count = 0;
private View lvNavigation;
boolean formDashboard = false;
ArrayList<Payment> dueArray = new ArrayList<Payment>();
ArrayList<DueItem> tempdueArray = new ArrayList<DueItem>();
ArrayList<String> navigationList;
NavigationAdapter adapter;
int prevItem, currentItem;
View btnDuetoCallCard;
private ImageView home;
String stateStore = "";
TextView totalCollectedDue;
TextView orderDueAmmount;
ViewGroup header;
private View clickedHeaderView;
FragmentManager fm;
FragmentTransaction fragmentTransaction;
public String getheaderDueamount() {
return orderDueAmmount.getText().toString();
}
public void setheaderDueamount(String amount) {
orderDueAmmount.setText(amount);
}
// public void setDueList(int position) {
// dueadapter.getItem(position)
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.duea_amount_layout);
DuetoCallCard = (Button) findViewById(R.id.btnDuetoCallCard);
DuetoCallCard.bringToFront();
Duelist = (ListView) findViewById(R.id.due_layout_listView);
tvOutletName = (TextView) findViewById(R.id.textviewoutletname);
home = (ImageView) findViewById(R.id.btndueHome);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(new Intent(Due.this,
MainActivity.class));
intent.putExtra("home", true);
startActivity(intent);
}
});
Bundle b = getIntent().getExtras();
if (b != null) {
formDashboard = getIntent().getExtras().getBoolean("fromDashboard");
}
if (formDashboard) {
// spinRoute.setVisibility(View.VISIBLE);
// spinOutlet.setVisibility(View.VISIBLE);
// Outlet1542
selectedOutlet = new OutletformAddDialog_due();
selectedOutlet.show(getFragmentManager(), "dialog");
} else {
populateArray();
}
btnDuetoCallCard = findViewById(R.id.btnDuetoCallCard);
initArrays();
// for disappearing the big circular button
Duelist.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
// End has been reached
// btnaddOutlet.startAnimation(AnimationUtils.loadAnimation(Outlet_List.this,
// android.R.anim.fade_out));
btnDuetoCallCard.setVisibility(View.GONE);
} else {
// btnaddOutlet.startAnimation(AnimationUtils.loadAnimation(Outlet_List.this,
// android.R.anim.fade_in));
btnDuetoCallCard.setVisibility(View.VISIBLE);
}
if (visibleItemCount == totalItemCount)
btnDuetoCallCard.setVisibility(View.VISIBLE);
}
});
}
void populateArray() {
dueadapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
convertView = inflater.inflate(R.layout.dueamounts_list_item,
null);
// }
TextView orderNo = (TextView) convertView
.findViewById(R.id.tvdueOrderNo);
TextView orderDate = (TextView) convertView
.findViewById(R.id.tvdueDate);
orderDueAmmount = (TextView) convertView
.findViewById(R.id.tvRemainingDueAmmount);
ImageButton imgbtn = (ImageButton) convertView
.findViewById(R.id.dueImageButton);
orderNo.setText("Order "
+ dueArray.get(position).getOrder_id().getId());
orderDate.setText(dueArray.get(position).getDate());
Double dueAmount = dueArray.get(position).getAmount();
orderDueAmmount.setText(formatDoubleValues(dueAmount));
// old way
// orderNo.setText("" + dueArray.get(position).getOrder());
// orderDate.setText(dueArray.get(position).getDate());
// orderAmmount.setText(dueArray.get(position).getAmmount());
header = (ViewGroup) convertView.findViewById(R.id.header);
header.setId(position);
header.setOnClickListener(due_header_clicked);
ViewGroup body = (ViewGroup) convertView
.findViewById(R.id.body);
View Headerparent = (View) header.getParent();
View image = findViewById(R.id.dueImageButton);
View TAB_Orderdetail = body.findViewById(R.id.btnOrderDetails);
View TAB_Duedetail = body.findViewById(R.id.btnDueDetails);
TAB_Orderdetail.setOnClickListener(change_fragment_listener);
TAB_Duedetail.setOnClickListener(change_fragment_listener);
// imgbtn.setOnClickListener(due_header_clicked);
View placeHolder = convertView
.findViewById(R.id.duefragment_placeholder);
int id = 10000 + position;
placeHolder.setId(id);
dueArray.get(position).setPlaceHolder(id);
Payment item = dueArray.get(position);
if (stateStore.equals("" + position)) {
// header.performClick();
body.setVisibility(View.VISIBLE);
header.performClick();
} else {
body.setVisibility(View.GONE);
}
// totalCollectedDue = (TextView) convertView
// .findViewById(R.id.tvTotalCollectedDueAmount);
return convertView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return dueArray.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return dueArray.size();
}
};
Duelist.setAdapter(dueadapter);
dueadapter.notifyDataSetChanged();
Duelist.setDivider(null);
Duelist.setDividerHeight(0);
}
int headerIndex = 0;
// View headerView;
int placeHolder_id = 0;
public OnClickListener due_header_clicked = new OnClickListener() {
#Override
public void onClick(View v) {
onHeaderClicked(v);
clickedHeaderView = v;
}
};
public void onHeaderClicked(View v) {
index = v.getId();
headerIndex = index;
// fr = dueArray.get(index).getDueFragment();
Bundle bundle = new Bundle();
bundle.putInt("index", headerIndex);
fr = tempdueArray.get(index).getDueFragment(headerIndex);
// fr.setArguments(bundle);
// tempdueArray.get(index).setDue_fragment(headerIndex);
Due.this.placeHolder_id = dueArray.get(index).getPlaceHolder();
final Payment item = dueArray.get(index);
// saving the header clicked position for later use
stateStore = "" + v.getId();
View view = (View) v.getParent();
TextView headerDueamount = (TextView) view
.findViewById(R.id.tvRemainingDueAmmount);
headerView = headerDueamount;
DueDetailsRight = (TextView) view.findViewById(R.id.tvduedetialright);
DueDetailsTop = (TextView) view.findViewById(R.id.tvdeudetailstop);
DueDetailsBottom = (TextView) view
.findViewById(R.id.tvdeudetailsBottom1);
DueDetailsrightHorizontal = (TextView) view
.findViewById(R.id.tvDuedetailslefthorizontal);
OrderDetailsBottom = (TextView) view
.findViewById(R.id.tvorderdetailBottom);
OrderDetailstop = (TextView) view.findViewById(R.id.tvorderdetailtop);
OrderDetailsleft = (TextView) view
.findViewById(R.id.tvOrderdetailsleft);
OrderDetailsleftHorizontal = (TextView) view
.findViewById(R.id.tvDuedetailsrighthorizontal);
final View body = view.findViewById(R.id.body);
View image = view.findViewById(R.id.dueImageButton);
View TAB_Orderdetail = body.findViewById(R.id.btnOrderDetails);
View TAB_Duedetail = body.findViewById(R.id.btnDueDetails);
TAB_Orderdetail.setOnClickListener(change_fragment_listener);
TAB_Duedetail.setOnClickListener(change_fragment_listener);
if (body.getVisibility() != View.VISIBLE) {
if (tempstore != null) {
tempstore.setVisibility(View.GONE);
imagetempstore
.setBackgroundResource(R.drawable.ic_due_dropdown_icon);
}
tempstore = body;
imagetempstore = image;
body.setVisibility(View.VISIBLE);
// if (fr == null) {
View test = (View) v.getParent().getParent();
DueDetailsButton = (TextView) test
.findViewById(R.id.btnOrderDetails);
OrderDetailsleft.setVisibility(View.INVISIBLE);
OrderDetailstop.setVisibility(View.INVISIBLE);
DueDetailsBottom.setVisibility(View.INVISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.INVISIBLE);
DueDetailsRight.setVisibility(View.VISIBLE);
DueDetailsTop.setVisibility(View.VISIBLE);
OrderDetailsBottom.setVisibility(View.VISIBLE);
DueDetailsrightHorizontal.setVisibility(View.VISIBLE);
fm = getSupportFragmentManager();
fragmentTransaction = fm.beginTransaction();
// fr = dueArray.get(index).getOrderFragment();
// fragmentTransaction.replace(item.getPlaceHolder(), fr);
// fragmentTransaction.commit();
// fr = dueArray.get(index).getDueFragment();
fr = tempdueArray.get(index).getDueFragment(headerIndex);
fm = getSupportFragmentManager();
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(item.getPlaceHolder(), fr);
fragmentTransaction.commit();
image.setBackgroundResource(R.drawable.ic_expand_icon);
} else {
image.setBackgroundResource(R.drawable.ic_due_dropdown_icon);
body.setVisibility(View.GONE);
}
}
public OnClickListener change_fragment_listener = new OnClickListener() {
#Override
public void onClick(View v) {
changeFargment(v);
}
};
public void changeFargment(View v) {
View test = (View) v.getParent().getParent();
DueDetailsRight = (TextView) test.findViewById(R.id.tvduedetialright);
DueDetailsTop = (TextView) test.findViewById(R.id.tvdeudetailstop);
DueDetailsBottom = (TextView) test
.findViewById(R.id.tvdeudetailsBottom1);
DueDetailsrightHorizontal = (TextView) test
.findViewById(R.id.tvDuedetailslefthorizontal);
OrderDetailsBottom = (TextView) test
.findViewById(R.id.tvorderdetailBottom);
OrderDetailstop = (TextView) test.findViewById(R.id.tvorderdetailtop);
OrderDetailsleft = (TextView) test
.findViewById(R.id.tvOrderdetailsleft);
OrderDetailsleftHorizontal = (TextView) test
.findViewById(R.id.tvDuedetailsrighthorizontal);
DueDetailsButton = (TextView) test.findViewById(R.id.btnDueDetails);
OrderDetailsButton = (TextView) test.findViewById(R.id.btnOrderDetails);
OrderDetailsButton = (TextView) test.findViewById(R.id.btnOrderDetails);
switch (v.getId()) {
case R.id.btnOrderDetails:
DueDetailsButton.setTextColor(Color.parseColor("#8e8f92"));
OrderDetailsButton.setTextColor(Color.parseColor("#050708"));
// Bundle bundle = new Bundle();
// bundle.putInt("index", headerIndex);
// fr = dueArray.get(headerIndex).getOrderFragment();
fr = tempdueArray.get(headerIndex).getOrderFragment(headerIndex);
// fr.setArguments(bundle);
DueDetailsRight.setVisibility(View.INVISIBLE);
DueDetailsTop.setVisibility(View.INVISIBLE);
OrderDetailsBottom.setVisibility(View.INVISIBLE);
DueDetailsrightHorizontal.setVisibility(View.INVISIBLE);
OrderDetailsleft.setVisibility(View.VISIBLE);
OrderDetailstop.setVisibility(View.VISIBLE);
DueDetailsBottom.setVisibility(View.VISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.VISIBLE);
break;
case R.id.btnDueDetails:
OrderDetailsButton.setTextColor(Color.parseColor("#8e8f92"));
DueDetailsButton.setTextColor(Color.parseColor("#050708"));
Bundle bundle = new Bundle();
bundle.putInt("index", headerIndex);
// fr = dueArray.get(headerIndex).getDueFragment();
fr = tempdueArray.get(headerIndex).getDueFragment(headerIndex);
fr.setArguments(bundle);
OrderDetailsleft.setVisibility(View.INVISIBLE);
OrderDetailstop.setVisibility(View.INVISIBLE);
DueDetailsBottom.setVisibility(View.INVISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.INVISIBLE);
DueDetailsRight.setVisibility(View.VISIBLE);
DueDetailsTop.setVisibility(View.VISIBLE);
OrderDetailsBottom.setVisibility(View.VISIBLE);
DueDetailsrightHorizontal.setVisibility(View.VISIBLE);
break;
case R.id.btnCollection:
break;
case R.id.btndueHome:
Intent intent = new Intent(new Intent(Due.this, MainActivity.class));
intent.putExtra("home", true);
startActivity(intent);
break;
}
// DueDetail.total = 0;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(Due.this.placeHolder_id, fr);
fragmentTransaction.commit();
}
public void buttonClickActions(View v) {
startActivity(new Intent(Due.this, CallCard.class));
finish();
}
#Override
public void onDoneButtonClick(DialogFragment dialog, String outlet,
String outletId) {
tvOutletName.setText(outlet);
outlet_id = outletId;
populateArray();
}
List<Payment> dueList;
public void initArrays() {
dueList = Entity.query(Payment.class).executeMulti();
// initializing the arraylist with object values
for (int i = 0; i < dueList.size(); i++) {
dueArray.add(dueList.get(i));
DueItem dt = new DueItem();
// dt.setOrder("order " + dueList.get(i).getOrder_id());
// dt.setDate("21July,2015" + dueList.get(i).getDate());
// dt.setAmmount("BDT" + dueList.get(i).getAmount());
tempdueArray.add(dt);
}
}
public String formatDoubleValues(Double myDouble) {
DecimalFormat myFormat = new DecimalFormat("0.00");
return myFormat.format(myDouble);
}
}
And the following class is one of the fragment class that is updating the fragment ListView and the parent Listview it is in.
public class DueDetail extends Fragment {
BaseAdapter dueDetailAdapter;
ListView dueDetailList;
TextView collectionbtn;
TextView totalInitialDue;
CheckBox cbCash, cbCheque;
private String dueAmmount;
double total, totalremainingDue;
int currentDueOnOrder = 100000;
ArrayList<DueCollection> arrayDueDetail = new ArrayList<DueCollection>();
ArrayList<Payment> arrayPayment = new ArrayList<Payment>();
List<DueCollection> duelist;
List<Payment> paymentlist;
private TextView TotalCollectedDue;
Formater fObj = new Formater();
int currentPositon;
int position;
Due dueActivity;
OrderModel om;
DueCollection odi;
boolean setClicked = false;
public DueDetail(int pos) {
//
duelist = Entity.query(DueCollection.class).executeMulti();
for (int i = 0; i < duelist.size(); i++) {
// if (duelist.get(i).getAmount() != null) {
int postion = duelist.get(i).getPayment_id().getId();
if (postion == pos + 1) {
arrayDueDetail.add(duelist.get(i));
}
}
paymentlist = Entity.query(Payment.class).executeMulti();
for (int i = 0; i < paymentlist.size(); i++) {
arrayPayment.add(paymentlist.get(i));
}
// for calculating the total of collected due in the duedetail
// fragment
for (int i = 0; i < arrayDueDetail.size(); i++) {
if (arrayDueDetail.get(i).getAmount() != null) {
int dueAmount = Integer.parseInt(arrayDueDetail.get(i)
.getAmount());
total += dueAmount;
}
}
//
}
#Override
#Nullable
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.due_amounts_duedetails_history,
container, false);
this.view = view;
dueActivity = (Due) getActivity();
position = dueActivity.getIndex();
DecimalFormat formatter = new DecimalFormat("#,###,###");
totalInitialDue = (TextView) view.findViewById(R.id.tvRemainingDue);
totalInitialDue.setText("BDT "
+ arrayPayment.get(position).getInitialDue());
TotalCollectedDue = (TextView) view
.findViewById(R.id.tvTotalCollectedDueAmount);
String totalduecollection = amountFormatter(total);
TotalCollectedDue.setText("BDT " + totalduecollection);
updateUI();
return view;
}
View view;
public void updateUI() {
if (view == null)
return;
collectionbtn = (TextView) view.findViewById(R.id.btnCollection);
collectionbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog d = new Dialog(getActivity());
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.due_collection_popup);
// d.requestWindowFeature(Window.FEATURE_NO_TITLE);
final EditText et = (EditText) d
.findViewById(R.id.etduecollectionamount);
d.findViewById(R.id.btnCollectionOk).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
dueAmmount = et.getText().toString();
if (dueAmmount != null) {
if (!(dueAmmount.equals(""))) {
int incremental_position = position + 1;
// creating a object of duecollection
odi = new DueCollection();
odi.setAmount(dueAmmount);
SimpleDateFormat sdf = new SimpleDateFormat(
"dd MMMM,yyyy");
String currentDate = sdf
.format(new Date());
odi.setDate(currentDate);
Payment payObj = Entity
.query(Payment.class)
.where("_id='"
+ incremental_position
+ "'").execute();
odi.setPayment_id(payObj);
om = Entity
.query(OrderModel.class)
.where("_id='"
+ incremental_position
+ "'").execute();
odi.setOrder_id(om);
odi.save();
arrayDueDetail.add(odi);
// *** duecollection obj creation ends
// here
total = 0;
dueDetailAdapter.notifyDataSetChanged();
for (int i = 0; i < arrayDueDetail
.size(); i++) {
double dueAmount = Integer
.parseInt(arrayDueDetail
.get(i).getAmount());
total += dueAmount;
}
String DueOnOrder = arrayPayment.get(
position).getInitialDue();
double remainingdue = Double
.parseDouble(DueOnOrder)
- total;
dueActivity.dueArray.get(position)
.setAmount(remainingdue);
dueActivity.dueadapter
.notifyDataSetChanged();
payObj.setAmount(remainingdue);
payObj.setSynced("0");
payObj.save();
// set the total remaining due to the
// header textview
String totalduecollection = amountFormatter(total);
TotalCollectedDue.setText("BDT "
+ totalduecollection);
dueActivity.stateStore = "" + position;
setClicked = true;
}
}
d.dismiss();
}
});
d.show();
d.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// dueActivity.populateArray();
Formater fobJ = new Formater();
DueCollectionAsyncTask dcat = new DueCollectionAsyncTask(
dueActivity, "" + odi.getOrder_id().getId(), ""
+ odi.getPayment_id().getOutlet_id()
.getId(), dueAmmount, fobJ
.getDateinPrefferedFormat());
dcat.execute();
}
});
}
});
// dueActivity.header.performClick();
dueDetailList = (ListView) view.findViewById(R.id.listViewDueDetails);
dueDetailAdapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
convertView = inflater.inflate(
R.layout.due_amounts_duedetails_product_items, null);
// }
TextView dueFragproduct = (TextView) convertView
.findViewById(R.id.tvduefragDate);
TextView dueFragDueCollectionAmmount = (TextView) convertView
.findViewById(R.id.tvduefragProductAmmount);
dueFragproduct.setText(arrayDueDetail.get(position).getDate());
DecimalFormat formatter = new DecimalFormat("#,###,###");
String commaformatedstring = ""
+ arrayDueDetail.get(position).getAmount();
dueFragDueCollectionAmmount.setText("BDT "
+ commaformatedstring);
return convertView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayDueDetail.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayDueDetail.size();
}
};
dueDetailList.setAdapter(dueDetailAdapter);
dueDetailList.setDivider(null);
dueDetailList.setDividerHeight(0);
setListViewHeightBasedOnChildren(dueDetailList);
}
/****
* Method for Setting the Height of the ListView dynamically. Hack to fix
* the issue of not showing all the items of the ListView when placed inside
* a ScrollView
****/
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
public void confirmationDialog(String msg, String title, final Dialog d) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setMessage(msg);
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
d.dismiss();
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
}
});
AlertDialog alertDialog2 = alertDialogBuilder.create();
alertDialog2.show();
Button nbutton = alertDialog2
.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setBackgroundColor(Color.parseColor("#47b96b"));
Button pbutton = alertDialog2
.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(Color.parseColor("#e06165"));
int textViewId = alertDialog2.getContext().getResources()
.getIdentifier("android:id/alertTitle", null, null);
TextView tv = (TextView) alertDialog2.findViewById(textViewId);
tv.setTextColor(getResources().getColor(R.color.coral_blue));
}
public String amountFormatter(double number) {
DecimalFormat formatter = new DecimalFormat("#,###,###");
String totalduecollection = formatter.format(Double.parseDouble(""
+ number));
return totalduecollection;
}
}
The button displays a dialog through which ListView inside the fragment gets populated.
not exactly clear to me. Did you meant inside your dialog you have some action that reflects on the fragment lisview?
have to click the parent list view item again to see the fragment and its content. I want the Fragment view and its updated content remain viewed after the dialog is dismissed
What i understand here u are doing something inside child view fragment that reflects on parent view list item, you are expecting the parent item data to be updated in view and also keeping the view state here u meant to be opened the parent item as it was (when u are updating the something inside fragment or dialog whatever)
My primary answer is you keep somehow keep the position to a member reference of the activity class where you actually setting the parent list in parent item onClick callback.
keep this position and later what you have to is to call a method inside adapter to pass the position to set a perform clic on item view
you may get a hints from this link..
http://blog.wittchen.biz.pl/how-to-highlight-and-click-on-listview-item-in-android-programmatically/
I have selected set of items from my sdcard folder using multi-selection file-chooser.It returns exactly selected values but the selection highlighted items (using colors) are dynamically changed while scrolling list-view..can anybody tell me how to fix it?
Here i have added my file-chooser class and adapter class..
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
private Bundle selectedfiles;
String selectedFileAbspath;
ArrayList<String> images_arr = new ArrayList<String>();
boolean is_multiple;
Button file_upload;
Integer val;
Pattern fileExtnPtrn;;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
is_multiple = this.getIntent().getExtras()
.getBoolean("is_multiple", false);
val = this.getIntent().getExtras()
.getInt("value");
if (is_multiple)
{
setContentView(R.layout.file_chooser_list);
file_upload = (Button) findViewById(R.id.file_upload);
file_upload.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(selectedfiles.size()!=0)
{
Intent i = new Intent();
i.putExtra("selected_files", selectedfiles);
setResult(RESULT_OK, i);
finish();
}
else
{
showDialog("Please Choose Atleast one File");
}
}
});
}
currentDir = new File("/sdcard/");
selectedfiles = new Bundle();
fill(currentDir);
}
private void fill(File f)
{
File[]dirs = f.listFiles();
this.setTitle("Current Dir: "+f.getName());
List<Item>dir = new ArrayList<Item>();
List<Item>fls = new ArrayList<Item>();
try
{
for(File ff: dirs)
{
Date lastModDate = new Date(ff.lastModified());
DateFormat formater = DateFormat.getDateTimeInstance();
String date_modify = formater.format(lastModDate);
if(ff.isDirectory())
{
File[] fbuf = ff.listFiles();
int buf = 0;
if(fbuf != null)
{
buf = fbuf.length;
}
else buf = 0;
String num_item = String.valueOf(buf);
if(buf == 0)
num_item = num_item + " item";
else
num_item = num_item + " items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(),num_item,date_modify,ff.getAbsolutePath(),"directory_icon"));
}
else
{
fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"file_icon"));
}
}
}
catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0,new Item("..","Parent Directory","",f.getParent(),"directory_up"));
adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_view,dir);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon")||o.getImage().equalsIgnoreCase("directory_up")){
currentDir = new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o,v);
}
}
private void onFileClick(Item o,View v)
{
selectedFileAbspath = currentDir.toString() + "/" + o.getName();
RelativeLayout list_item=(RelativeLayout) v;
if(is_multiple)
{
if(validateFileExt(selectedFileAbspath))
{
if (selectedfiles.containsKey(selectedFileAbspath))
{
selectedfiles.remove(selectedFileAbspath);
list_item.setBackgroundColor(getResources().getColor(R.color.white));
}
else
{
selectedfiles.putString(selectedFileAbspath, "1");
list_item.setBackgroundColor(getResources().getColor(R.color.red));
}
}
else
{
showDialog("please select valid image file");
}
}
else
{
if(validateFileExt(selectedFileAbspath))
{
Intent intent = new Intent();
intent.putExtra("GetPath", currentDir.toString());
intent.putExtra("GetFileName", o.getName());
setResult(RESULT_OK, intent);
finish();
}
else
{
Intent intent = new Intent();
setResult(RESULT_CANCELED, intent);
finish();
}
}
}
private boolean validateFileExt(String fileName)
{
fileExtnPtrn = Pattern.compile("([^\\s]+(\\.(?i)(jpg|png))$)");
Matcher mtch = fileExtnPtrn.matcher(fileName);
return mtch.matches();
}
private void showDialog(String string)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(string);
alertDialog.setPositiveButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertDialog.show();
}
}
Adapter class
public class FileArrayAdapter extends ArrayAdapter{
private Context c;
private int id;
private List<Item>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
//convertView = ( RelativeLayout ) inflater.inflate( resource, null );
final Item o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
if(t3!=null)
t3.setText(o.getDate());
}
return v;
}
}
your problem in getItem method in ListAdapter of List
try this adapter) you must determine all elements of each item in your case)
public class FileArrayAdapter extends ArrayAdapter{
private Context c;
private int id;
private List<Item>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
if(t3!=null)
t3.setText(o.getDate());
return v;
}
}
A had a custom ListView recently. Then I had to display all the list items without scrollbar. Following the method to place items in LinearLayout I changed my code but I can't bind onClickListener to new layout. In ListView I used position var to determine what view was touched. But in LinearLayout onClick callback hasn't position parameter.
Here is my BasketActivity.class:
package ru.**.**;
public class BasketActivity extends Activity {
ArrayList<Item> items = new ArrayList<Item>();
SQLiteDatabase database;
Map<String, ?> all;
ItemAdapter adapter;
Item item2delete;
View deletingView;
private SharedPreferences settings;
private SharedPreferences settings2;
private Basket basket;
TextView basketSum;
private int position2delete;
private Map<String, ?> all2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basket);
<..cutted..>
settings = getSharedPreferences("basket", 0);
settings2 = getSharedPreferences("price", 0);
basket = new Basket(settings, settings2);
all = basket.getList();
LinearLayout l1 = (LinearLayout) findViewById(R.id.l1);
MyDBAdapter myDBAdapter = new MyDBAdapter(getBaseContext());
myDBAdapter.open();
Cursor itemCursor = myDBAdapter.getItemsInBasket(all);
while (itemCursor.moveToNext()) {
String[] columns = itemCursor.getColumnNames();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < columns.length; i++) {
sb.append(columns[i]);
}
Item item = new Item();
item.setId(itemCursor.getString(0));
item.setArticul(itemCursor.getString(MyDBSchema.ITEM_ARTICUL));
item.setTitle(itemCursor.getString(MyDBSchema.ITEM_TITLE));
item.setPrice(itemCursor.getInt(MyDBSchema.ITEM_PRICE));
item.setPic80(itemCursor.getString(MyDBSchema.ITEM_PIC80));
item.setPic300(itemCursor.getString(MyDBSchema.ITEM_PIC300));
item.setMessage(itemCursor.getString(MyDBSchema.ITEM_MESSAGE));
item.setColor(itemCursor.getString(MyDBSchema.ITEM_COLOR));
item.setColorpos(itemCursor.getString(MyDBSchema.ITEM_COLORPOS));
items.add(item);
}
itemCursor.close();
myDBAdapter.close();
for (int position=0; position<items.size(); position++) {
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.list_basket, null);
final Item i = items.get(position);
if (i != null) {
Item ei = (Item) i;
final TextView title = (TextView) v.findViewById(R.id.title);
if (title != null) title.setText(ei.title);
final TextView articul = (TextView) v.findViewById(R.id.articul);
if (articul != null) articul.setText(ei.articul);
TextView payed = (TextView) v.findViewById(R.id.payed);
if (payed != null) payed.setVisibility(TextView.GONE);
TextView status = (TextView) v.findViewById(R.id.status);
if (status != null) status.setVisibility(TextView.GONE);
Context context = getBaseContext();
ProgressBar p = new ProgressBar(context);
p.setIndeterminate(true);
Drawable d = p.getIndeterminateDrawable();
WebImageView wiv = (WebImageView) v.findViewById(R.id.pic80);
wiv.setImageWithURL(context, ei.pic80, d);
final TextView price = (TextView) v.findViewById(R.id.price);
if (price != null) price.setText(ei.price_valid);
final TextView quant = (TextView) v.findViewById(R.id.quant);
if (quant != null) {
int q = (Integer) all.get(ei.articul);
if (q > 1) {
quant.setText("x "+q+" шт.");
}
}
}
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
deletingView = v;
int position = 0; //The order number of the view should be here!
Item item = (Item) items.get(position);
item2delete = item;
position2delete = position;
AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
builder.setMessage(getString(R.string.suredelete))
.setCancelable(false)
.setPositiveButton(getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BasketActivity.this.removeItem();
deletingView.setVisibility(View.GONE);
}
})
.setNegativeButton(getString(R.string.no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
l1.addView(v);
}
basketSum = (TextView) findViewById(R.id.basketsum);
basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
+ basket.getBasketPriceValid() + "</b>"));
}
protected void removeItem() {
basket.remove(item2delete);
Context context = getApplicationContext();
CharSequence text = getText(R.string.item_deleted);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
+ basket.getBasketPriceValid() + "</b>"));
items.remove(position2delete);
}
}
My question is how to get view's position at onClick(View v)?
You can use the View's tag;
for (int position=0; position<items.size(); position++) {
v.setTag(position);
}
and in the onClick(View v)
public void onClick(View v) {
int position = 0;
if (v.getTag() instanceof Integer) {
position = (Integer) v.getTag();
}
}
Can you have
v.setTag(items.get(position).getId();
and then in onClick
public void onClick(View v) {
int id= v.getTag();
}