Custom Listview using Base adapter not scrolls fast in Android - android

Hi I am working with android application which is having custom listview. The items in listview around 3000. My problem is after loading items when scrolling it makes outOfMemory Error.
I am using Base Adapter and Each item having One Checkbox and four textviews.
Here is my code. Please let me know the solution.
public class GuestListAdapter extends BaseAdapter implements OnClickListener {
private String strExe;
AlertDialog.Builder builder;
String sId;
String sCheckIn;
String strCheckInResponse;
Context context;
private ArrayList<String> arrayListId;
private ArrayList<String> arrayListFirstName;
private ArrayList<String> arrayListLastName;
private ArrayList<String> arrayListGuests;
private ArrayList<String> arrayCustomOne;
private ArrayList<String> arTempId;
public static ArrayList<Boolean> chickinlist;
public static ArrayList<Integer> arrCheckedItems;
public static ArrayList<Integer> arrUnCheckedItems;
Button btnInfo;
private SQLiteAdapter mySqliteAdapter;
private GuestListScreen myGuestList;
private RelativeLayout views;
private String strAlertValue;
// private AlertDialog alertDialog = null;
private ArrayList<Boolean> checks = new ArrayList<Boolean>();
public GuestListAdapter(Context mcontext, ArrayList<String> arrListid,
ArrayList<String> arrListFN, ArrayList<String> arrListLN,
ArrayList<String> arrListGuest, ArrayList<String> arrTiketID,
ArrayList<String> arrCustOne, ArrayList<Boolean> chicklist) {
clearAdapter();
arrayListId = new ArrayList<String>();
arrayListFirstName = new ArrayList<String>();
arrayListLastName = new ArrayList<String>();
arrayListGuests = new ArrayList<String>();
arrayCustomOne = new ArrayList<String>();
arTempId = new ArrayList<String>();
chickinlist = new ArrayList<Boolean>();
arrCheckedItems = new ArrayList<Integer>();
arrUnCheckedItems = new ArrayList<Integer>();
arrayListId = arrListid;
arrayListFirstName = arrListFN;
arrayListLastName = arrListLN;
arrayListGuests = arrListGuest;
arrayCustomOne = arrCustOne;
arTempId = arrTiketID;
chickinlist = chicklist;
context = mcontext;
mySqliteAdapter = new SQLiteAdapter(context);
for (int i = 0; i < arrayListFirstName.size(); i++) {
checks.add(i, false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayListFirstName.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayListFirstName.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final int pos = position;
views = null;
LayoutInflater layoutInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
views = (RelativeLayout) layoutInflator.inflate(
R.layout.guest_list_item, null);
final CheckBox chk = (CheckBox) views.getChildAt(0);
// Log.d("", "CheckBox Pos "+position);
chk.setId(position);
TextView txtView = (TextView) views.getChildAt(1);
TextView txtView2 = (TextView) views.getChildAt(2);
TextView txtView3 = (TextView) views.getChildAt(3);
final TextView txtView4 = (TextView) views.getChildAt(4);
TextView txtView5 = (TextView) views.getChildAt(6);
txtView5.setId(position);
// Log.d("", "Button Pos "+position);
txtView4.setId(position);
txtView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, InfoScreen.class);
intent.putExtra("IDVALUE", arTempId.get(txtView4.getId()));
intent.putExtra("IDVALUE", arrayListId.get(position));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
for (int dd = 0; dd < arrayListFirstName.size(); dd++) {
if (position == dd) {
// Log.d("", "Passsing arr size " + chickinlist.size());
Boolean result = chickinlist.get(position);
// Log.d("", "After " + result);
if (result == true) {
chk.setChecked(true);
arrCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_checked);
} else {
chk.setChecked(false);
arrUnCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_unchecked);
}
txtView.setText(arrayListFirstName.get(position));
txtView2.setText(arrayListLastName.get(position));
txtView3.setText("(" + arrayListGuests.get(position) + ")");
if (arrayCustomOne.get(position).equalsIgnoreCase("0")
|| arrayCustomOne.get(position).equalsIgnoreCase(null)
|| arrayCustomOne.get(position).equalsIgnoreCase(
"(null)")) {
txtView5.setText("");
} else {
txtView5.setText(arrayCustomOne.get(position));
}
}
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mySqliteAdapter.openToWrite();
sId = arrayListId.get(chk.getId());
// Log.d("Adapter",
// "Checked Temp Id "+arTempId.get(chk.getId()));
if (isChecked) {
chk.setChecked(true);
arrCheckedItems.add(position);
strAlertValue = "1";
sCheckIn = "1";
strExe = "update ticket_details set checkin_status=1 where tempid="
+ arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
if (Util.getInstance(context).isTabletDevice()) {
buttonView
.setBackgroundResource(R.drawable.tablet_list_item_check);
Log.e("Tablet", "Tablet Checked ");
} else {
buttonView
.setBackgroundResource(R.drawable.list_item_checked);
Log.e("Device", "Device Checked ");
}
new CheckInUpdate().execute();
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.create();
builder.setMessage(arrayListFirstName.get(chk.getId())
+ " " + arrayListLastName.get(chk.getId())
+ " has been checked in.");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Intent intentNavGuestList = new Intent(
context, GuestListScreen.class);
intentNavGuestList
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intentNavGuestList);
dialog.dismiss();
}
}).show();
// Log.d("", "ID = " + buttonView.getId());
}
if (!isChecked) {
sCheckIn = "0";
strAlertValue = "0";
strExe = "update ticket_details set checkin_status=0 where tempid="
+ arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
if (Util.getInstance(context).isTabletDevice()) {
buttonView
.setBackgroundResource(R.drawable.tablet_list_item_uncheck);
Log.e("Tablet", "Tablet UnChecked ");
} else {
buttonView
.setBackgroundResource(R.drawable.list_item_unchecked);
Log.e("Device", "Device UnChecked ");
}
new CheckInUpdate().execute();
Intent intentNavGuestList = new Intent(context,
GuestListScreen.class);
intentNavGuestList
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intentNavGuestList);
}
}
});
return views;
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Integer index = (Integer) view.getTag();
boolean state = checks.get(index.intValue());
checks.set(index.intValue(), !state);
}
public void clearAdapter() {
if (arrayListFirstName != null) {
arrayListFirstName.clear();
arrayListId.clear();
arrayListId = null;
arrayListFirstName = null;
arrayListLastName.clear();
arrayListLastName = null;
arrayListGuests.clear();
arrayListGuests = null;
arrayCustomOne.clear();
arrayCustomOne = null;
arTempId.clear();
arTempId = null;
chickinlist.clear();
chickinlist = null;
arrCheckedItems.clear();
arrCheckedItems = null;
arrUnCheckedItems.clear();
arrUnCheckedItems = null;
}
}
}
I also tried with View Holder but still loading slow. Please tell the solution how to solve this.

You need to reuse view paremeter from View getView(final int position, Vie view, ViewGroup parent) and if it's not null, then You don't need to inflate again.
Use ViewHolder pattern;
remove loop for (int dd = 0; dd < arrayListFirstName.size(); dd++) from getView;
Try simplify layout for list items;
Seems arrayListFirstName.size() can be simplified (e.g. use some variable to avoid size() calls)
Do profiling in order to know exactly what is slow downs You scrolling (It might be enough to profike only getView())
Also, check out this video from Google I/O for more details on how to make ListViews in a right way.

Related

Custom listview adapter with a chronometer refreshes when scrolled

I have created a custom listview adapter to fit a button, a custom chronometer and a textview. When i scroll my listview, the rows that are "hidden" refresh themselves and so chronometers, how can i keep chronometers running even if they're hidden?
I am quite new to Android development so i may have done something wrong; I know that listview refresh its rows when scrolled but maybe there's something that i missed to make chronometers running in background
public class MyCustomAdapter extends BaseAdapter {
ArrayList<String> users;
Context context;
LayoutInflater inflater = null;
public MyCustomAdapter(Activity mainActivity, ArrayList<String> usersList) {
// TODO Auto-generated constructor stub
users = usersList;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return users.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return users.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
private class Holder {
TextView tv;
CustomChrono cr;
Button but;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.customized_list_view, null);
holder.tv = (TextView) rowView.findViewById(R.id.names_laps);
holder.cr = (CustomChrono) rowView.findViewById(R.id.chronometer_laps);
holder.but = (Button) rowView.findViewById(R.id.stop_button);
holder.cr.start();
holder.but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//((ListView) parent).performItemClick(v, position, 0);
holder.cr.stop();
stopped = true;
}
});
holder.tv.setText(users.get(position));
rowView.setTag(holder);
return rowView;
}
}
Then I have my activity class where I use this adapter
public class RunnerLaps extends AppCompatActivity {
ListView list;
ArrayList<String> runner_array;
private Map<Runner,String> map = new HashMap<Runner,String>(10);
private boolean isClicked = true;
private boolean isStartedNow = false;
boolean stopped = false;
ArrayList<Runner> arr_runners;
ArrayList<Runner> runners_arrList;
private long previousClickTime1 = 0;
Runner r = null;
String m = "";
SerializableManager serializableManager;
String filename = "myfile";
FileOutputStream outputStream = null;
ObjectOutputStream objectOutputStream = null;
//Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_laps);
Intent i = getIntent();
serializableManager = new SerializableManager();
runner_array = (ArrayList<String>) getIntent().getSerializableExtra("KEY");
ArrayList<Runner> running = getIntent().getExtras().getParcelableArrayList("arr2");
runners_arrList = new ArrayList<Runner>(runner_array.size());
for (String r : runner_array)
{
runners_arrList.add(new Runner(r));
}
for (int f = 0; f < runners_arrList.size();f++)
{
Log.d("Runner: " + f,runners_arrList.get(f).getName());
}
m = getIntent().getExtras().getString("booly");
for (int j = 0; j < runner_array.size(); j++) {
Runner r = new Runner(runner_array.get(j));
map.put(r, runner_array.get(j));
}
if (m!= null)
{
stopped = true;
}
list = (ListView) findViewById(R.id.laps_list);
final MyCustomAdapter adapter = new MyCustomAdapter(RunnerLaps.this,runner_array);
list.setAdapter(adapter);
//addRunners();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomChrono chr = (CustomChrono) view.findViewById(R.id.chronometer_laps);
r = runners_arrList.get(position);
r.setTemp(System.currentTimeMillis());
long temp = r.getTemp();
previousClickTime1 = temp;
if (previousClickTime1 != 0 && previousClickTime1 - temp < 300)
{
if (stopped == true)
{
chr.stop();
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
Intent i = new Intent (RunnerLaps.this,Runner_Display.class);
i.putExtra("key",(Serializable) r);
i.putParcelableArrayListExtra("arr",arr_runners);
for (int h = 0; h < runners_arrList.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
startActivity(i);
}
else
{
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
for (int h = 0; h < runner_array.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
}
}
else
{}
}
});
}
}

How to set listview row clickable only one time in android?

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);
}
}

How to get a button in my custom adapter for my listview to call a phone number

I take in the addresses and information of stores and list then in a listview, by name, address, city/state and phn number. I am trying so that the system will use the phone to call a number. But, i get an activity not found exception.
public static class MyRow
{
String storeName;
String streetAdress;
String location;
String phn;
MyRow(String str1, String str2, String str3, String str4)
{
storeName = str1;
streetAdress = str2;
location = str3;
phn= str4;
}
}
public static class CustomAdapter extends BaseAdapter
{
ArrayList<MyRow> specList;
Context conty;
CustomAdapter(Context c)
{
conty = c;
specList = new ArrayList<Row>();
ArrayList<String> storeName = new ArrayList<String>();
ArrayList<String> streetAdress = new ArrayList<String>();
ArrayList<String> location = new ArrayList<String>();
ArrayList<String> phn= new ArrayList<String>();
for (int i = 0; i < ar.size(); i++)
{
storeName.add(ar.get(i).get(0).toString());
streetAdress.add(ar.get(i).get(2).toString());
location.add(ar.get(i).get(3).toString() + ", "
+ ar.get(i).get(4).toString() + " " + ar.get(i).get(5).toString());
phn.add(ar.get(i).get(7).toString());
}
for (int i = 0; i < ar.size(); i++)
{
specList.add(new MyRow(storeName.get(i), streetAdress.get(i),
location.get(i), phn.get(i)));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return specList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return specList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) conty.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rw = inflater.inflate(R.layout.row, parent, false);
TextView name = (TextView) rw.findViewById(R.id.textView1);
TextView adress = (TextView) rw.findViewById(R.id.textView2);
TextView location = (TextView) rw.findViewById(R.id.textView3);
TextView phn = (TextView) rw.findViewById(R.id.textView4);
final Row temp = specList.get(position);
name.setText(temp.storeName);
adress.setText(temp.streetAdress);
location.setText(temp.location);
phn.setText(" Phone:" + temp.phn);
Button call = (Button) rw.findViewById(R.id.button1);
call.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse(temp.country));
rw.getContext().startActivity(i);//I get an error here stating: Activity not found exception.
}
});
return rw;
}
}
You should use ACTION_DIAL :
Uri uri = Uri.parse("tel:" + number);
Intent i= new Intent(Intent.ACTION_DIAL, uri);
For use ACTION_CALL anyway, you need special permission (android.permission.CALL_PHONE) :
http://developer.android.com/reference/android/content/Intent.html#ACTION_CALL
Note: there will be restrictions on which applications can initiate a call; most applications should use the ACTION_DIAL.

Android ListAdapter not refreshing immediately after delete

In my android application, I have a list in fragment using an adapter which extends ArrayAdapter. Whenever you hold a row item for long you can delete that row by clicking Yes on an alert-dialogue. But when you click Yes, last row seems to be deleted. When you close that fragment and come back on it then the view is fine with proper row deleted. After debugging for so many days I am unable to fix this.Can anyone please figure out whats wrong ?
Thanks in advance.
AdapterClass
public class DuasListAdapter extends ArrayAdapter<String> {
// class variables
private final Context context;// to save context
private final List<String> duas;// to save list of stores
LayoutInflater inflater;// so save layout inflater for the view
public DuasListAdapter(Context ctx, List<String> duasList) {
super(ctx, R.layout.adapter_list_duas, duasList);
context = ctx;// save context
duas = duasList;// save list of stores
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);// save inflater layout
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// if view is not loaded
if (!(convertView instanceof View)) {
convertView = inflater.inflate(R.layout.adapter_list_duas, parent, false);
// load the view from holder class
holder = new ViewHolder(convertView);
// set the tag for future use
convertView.setTag(holder);
}
// if view is loaded
else
// get view from tag
holder = (ViewHolder) convertView.getTag();
holder.duaIndex = position;
convertView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final View view = v;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
ViewHolder holder = (ViewHolder) view.getTag();
int index = holder.duaIndex;
((MainActivity) context).removeItemFromList(index);
Toast.makeText(view.getContext(), "Deleted", Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Delete Dua from Favorites?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return false;
}
});
return convertView;
}
ListFragment
public void removeItemFromList(int index) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
String identifier = versesList[index];
new FavoriteDuas().removeDua(identifier);
updatedData();
}
#Override
public void onResume() {
lvDuaas.setAdapter(duasAdapter);
updatedData();
super.onResume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
lvDuaas.setAdapter(duasAdapter);
updatedData();
super.onPause();
}
public void updatedData() {
boolean keyIsFavSel = new SharedPreferencesSupplication().read(SingletonClass.keyIsFavSelected, false);
if (keyIsFavSel)
new SharedPreferencesSupplication().save(SingletonClass.keyListOfVerses, new SharedPreferencesSupplication().read(SingletonClass.keyFavVerses, "a1"));
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
ArrayList<String> duas = new ArrayList<String>();
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].length() > 0)
duas.add(versesList[i]);
}
duasAdapter.clear();
if (duas.size() > 0) {
for (String object : duas) {
duasAdapter.insert(object, duasAdapter.getCount());
}
}
duasAdapter.notifyDataSetChanged();
}
Delete-Method
public void removeDua(String duaIdentifier) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyFavVerses, "");
String[] versesList = verses.split(",");
int indexFound = -1;
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].equals(duaIdentifier)) {
indexFound = i;
break;
}
}
if (indexFound >= 0) {
verses = "";
for (int i = 0; i < versesList.length; i++) {
if (indexFound != i) {
if (verses.isEmpty())
verses = versesList[i];
else
verses = verses + "," + versesList[i];
}
}
new SharedPreferencesSupplication().save(SingletonClass.keyFavVerses, verses);
}
}
You can try to re-instantiate the duasAdapter
duasAdapter = new DuasListAdapter(your_context_here, duas);
instead of
duasAdapter.clear();
if (duas.size() > 0) {
for (String object : duas) {
duasAdapter.insert(object, duasAdapter.getCount());
}
}
duasAdapter.notifyDataSetChanged();
You are using setOnLongClickListener() on your view, use setOnItemLongClickListener() instead.

How to update the checkbox items position

I am using the check box in ListActivity.I doesn't know how to update the checkbox in server.
Now I came up with the result for checked item is unchecked and save means it will save(or update) the server.But in unchecked item checked means not save(or not update) the server.
Rsvp_EngagementMeals.java:
public class Rsvp_EngagementMeals extends ListActivity
{
#Override
checkstatus=new Hashtable<Integer,String>();
status=new ArrayList<String>();
veg =Rsvp_Meals.veg;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
if (result != null)
{
token = new StringTokenizer2(result, "");
}
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
value.add(Integer.toString(value.size()));
Integer k=null;
table=new Hashtable<Integer,ArrayList<String>>();
itemId = new ArrayList<String>();
str2 = new ArrayList<String>();
str3 = new ArrayList<String>();
stritem = new ArrayList<String>();
vegitems = new ArrayList<String>();
int id=0,c=0,n=value.size();
for(int j=0; j<n; j++)
{
z = value.get(j);
String[] mystring = z.split("<br>");
int arraysize = mystring.length;
for(int a=0; a<arraysize-1;a++)
{
str2.add(mystring[0]);
}
}
for(int g=0; g<str2.size();g++)
{
String name = str2.get(g);
token2 = new StringTokenizer2(name, "|", false);
while (token2.hasMoreTokens())
{
vegitems.add(token2.nextToken());
}
}
for(int x=1;x<vegitems.size();x++)
{
itemId.add(vegitems.get(x));
x=x+1;
stritem.add(vegitems.get(x));
x=x+1;
status.add(vegitems.get(x));
}
setListAdapter(new IconicAdapter(this));
save.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tru = new StringBuffer();
fals = new StringBuffer();
for (int i = 0; i<status.size();i++)
{
if (status.get(i).equals("True"))
tru.append(itemId.get(i)+",");
}
boolean netvalue = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
netvalue = true;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname=abcdefg&occasion=Engagement
"&choice="+tru+"&ownchoice=&category=";
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&")))
{
// alertbox("Success", "saved successfully");
Dialog locationError = new AlertDialog.Builder(Rsvp_EngagementMeals.this)
.setIcon(0)
.setMessage("Meals has been saved sucessfully")
.setTitle("Success")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int id) {
Intent ma = new Intent(
Rsvp_EngagementMeals.this, Rsvp_Meals.class);
startActivity(ma);
finish();
}
}).create();
locationError.show();
} else
alertbox("", result);
} else {
alertbox("Message", "No Internet Connection!");
}
}
});
}// End of On create method
#Override
protected void onListItemClick(ListView parent, View v, int position,long id)
{
super.onListItemClick(parent, v, position, id);
}
public void onClick(View v)
{
System.out.println("On View Click");
}
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter
{
Activity context;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.rsvp_mealsse, stritem);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);
TextView index = (TextView) row.findViewById(R.id.index);
index.setText(String.valueOf(position+1)+".");
TextView label = (TextView) row.findViewById(R.id.title);
label.setText(stritem.get(position));
CheckBox check=(CheckBox)row.findViewById(R.id.check);
check.setId(Integer.parseInt(itemId.get(position)));
if(status.get(position).equals("True"))
check.setChecked(true);
;
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
status.set(ind, String.valueOf(isChecked));
}
});
return (row);
}
}
This is my full code.How to change the status in check box.I want result for when I update the check box its save the server and after I view the list the updated item view my checkbox.
The only bug that i could point was the spelling of false in your if statement:
Change this code:
if(status.get(position).equals("False"))
To this code:
if(status.get(position).equals("false"))
hope this works!

Categories

Resources