Android String reference to shared preferences cannot be iterated? - java

So I have an ArrayList named locationsList. I also have SharedPreferences that hold a city name which was set in the previous activity which i want to add onto my ArrayList. BUT I want to add it with a ">" at the end of it. So for example
SharedPreferences prefs = getActivity().getSharedPreferences("prefs", 0);
locationsList.add(0, prefs.getString("city", "no city") + ">");
However it does not change!!!. the ">" Isn't added. I even tried adding it when i set the text of the textView.
TextView tv...;
tv.setText(locationsList.get(0) + ">");
I dont understand why it cant change. Obviously the array list is holding a reference to the preferences and that cannot change. But I even tried assigning the preferences to a string variable and then iterating it, it doesn't budge. Can anyone help me
Async in activity
class getLocationsUrl extends AsyncTask<String, String, String> {
ArrayList<String> tempList = new ArrayList<String>();
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("city", prefs.getString("city", "durban")));
JSONParser parser = new JSONParser();
JSONObject json = parser.makeHttpRequest(IMAGE_URL + "fetchlocations.php", "POST",
params);
try {
list = json.getJSONArray("posts");
for(int i = 0; i < list.length(); i++) {
JSONObject c = list.getJSONObject(i);
String location = c.getString("location");
tempList.add(location);
Log.d("async trend", trendList.get(0));
}
Log.d("Got list", imageUrl.get(0) + " " + trendList.get(0));
} catch(JSONException je) {
Log.d("json exception", "json exception");
je.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
locationsList = tempList;
locationsFragment.updateAdapter();
feedFragment.updateHeadingAdapter();
}
}
FeedFragment set up in onCreateView
headingPager = (ViewPager) view.findViewById(R.id.headingPager);
headingList = (ArrayList<String>) NightWatch.locationsList.clone();
added = prefs.getString("city", "makaka");
headingList.add(0, added + ">");
headingAdapter = new CustomHeadingPagerAdapter(getChildFragmentManager());
headingPager.setAdapter(headingAdapter);
FeedFragments CustomHeadingAdapter
public class CustomHeadingPagerAdapter extends FragmentPagerAdapter {
public CustomHeadingPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
return HeadingFragment.newInstance(arg0, headingList);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return headingList.size();
}
}
FeedFragment's updateHeadingAdapter() called from the Async
public void updateHeadingAdapter() {
headingList = (ArrayList<String>) NightWatch.locationsList.clone();
headingList.add(0, (prefs.getString("city", "null") + ">"));
headingAdapter = new CustomHeadingPagerAdapter(getChildFragmentManager());
headingPager.setAdapter(headingAdapter);
}
And finally the HeadingFragment that I return in the adapter.
package info.nightowl.nightowl;
import java.util.ArrayList;
import com.example.nightowl.R;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HeadingFragment extends Fragment{
int position;
Typeface font;
ArrayList<String> list;
SharedPreferences prefs;
static HeadingFragment newInstance(int position, ArrayList<String> list) {
final HeadingFragment f = new HeadingFragment();
Bundle args = new Bundle();
args.putInt("position", position);
args.putStringArrayList("list", list);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
position = getArguments().getInt("position");
list = getArguments().getStringArrayList("list");
prefs = getActivity().getSharedPreferences("prefs", 0);
font = Typeface.createFromAsset(getActivity().getAssets(),
"NotCourierSans.ttf");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.heading_viewpage_layout, null);
TextView tv = (TextView) v.findViewById(R.id.headingText);
if(position == 0) tv.setText(">" + list.get(position) + ">");
else tv.setText(list.get(position) + ">");
tv.setTypeface(font);
tv.setTextColor(Color.YELLOW);
tv.setTextSize(30);
return v;
}
}

I got it. Always remember when iterating to a string text vi you set it to be a single line in the xml so...
android:singleLine="true"
Kind of a dumb mistake really

Related

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

Selecting correct data from list view Android put extra

I have code that sends data to another activity, but when I click on my item click listener I only get data from first item.
Here's code of fist activity's post execute:
protected void onPostExecute(JSONObject objdanejson){
pDialog.dismiss();
try {
android = objdanejson.getJSONArray(TAG_ZAWARTOSC);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
final String akt_tytul = c.getString(TAG_TYTUL);
String akt_skrot = c.getString(TAG_SKROT);
final String akt_tresc = c.getString(TAG_TRESC);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TYTUL, akt_tytul);
map.put(TAG_SKROT, akt_skrot);
Log.d(akt_tytul, "tytul");
Log.d(akt_skrot, "skrot");
Log.d(akt_tresc, "tresc");
oslist.add(map);
lista_aktualnosci = (ListView)findViewById(R.id.lista_aktualnosci);
final ListAdapter adapter = new SimpleAdapter(aktualnosci.this, oslist,
R.layout.aktualnosc_item,
new String[]{TAG_TYTUL, TAG_SKROT}, new int[]{R.id.aktTytul, R.id.aktSkrot});
lista_aktualnosci.setAdapter(adapter);
lista_aktualnosci.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(aktualnosci.this, "Kliknąłeś na " + oslist.get(+position).get("nazwa"),Toast.LENGTH_SHORT).show();
Intent czytaj = new Intent(aktualnosci.this, aktualnosc_czytaj.class);
czytaj.putExtra("tytuł",akt_tytul);
czytaj.putExtra("tresc",akt_tresc);
startActivity(czytaj);
}
});
and this is what I have in second activity:
package pl.webimpuls.wicms;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class aktualnosc_czytaj extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aktualnosc_czytaj);
TextView aktczytaj_tytul = (TextView) findViewById(R.id.aktczytaj_tytul);
TextView aktczytaj_tresc = (TextView) findViewById(R.id.aktczytaj_tresc);
String czytajtytul;
String czytajtresc;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
czytajtytul = null;
czytajtresc = null;
aktczytaj_tytul.setText(czytajtytul);
aktczytaj_tresc.setText(czytajtresc);
} else {
czytajtytul = extras.getString("tytuł");
czytajtresc = extras.getString("tresc");
aktczytaj_tytul.setText(czytajtytul);
aktczytaj_tresc.setText(czytajtresc);
}
} else {
czytajtytul = (String) savedInstanceState.getSerializable("tytuł");
czytajtresc = (String) savedInstanceState.getSerializable("tresc");
aktczytaj_tytul.setText(czytajtytul);
aktczytaj_tresc.setText(czytajtresc);
}
}
}
How can I make it to show data from item that I click?
In second activity you should use Intent instead of Bundle:
Intent intent = getIntent();
czytajtytul = intent.getStringExtra("tytuł");
czytajtresc = intent.getStringExtra("tresc");
You are doing wrong. You don't use bundle if not passing bundle in intent.
You can get data by getIntent().getStringExtra(key).

Android search functionality using listview from JSON file(Hard )

1.My search functionality works fine using edittext,but for example if I type "1" than delete it the listview shows null,how can I make listview shows JSON again after I type something then delete it?
2.If I change to search COUNTRY rather than RANK ,I need to type full character like "INDIA" how can I just type "in" then it can appear INDIA?
thanks
MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String URL="url";
static String FLAG = "flag";
EditText mEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
mEditText = (EditText) findViewById(R.id.inputSearch);
mEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.RANK);
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://ndublog.twomini.com/123.txt.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("url",jsonobject.getString("url"));
map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ListViewAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
public ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
TextView population;
TextView url;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
url=(TextView)itemView.findViewById(R.id.url);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.RANK));
country.setText(resultp.get(MainActivity.COUNTRY));
population.setText(resultp.get(MainActivity.POPULATION));
url.setText(resultp.get(MainActivity.URL));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
intent.putExtra("url",resultp.get(MainActivity.URL));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
Edit this code below,thanks
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String URL="url";
static String FLAG = "flag";
EditText mEditText;
String globalQuery="";
ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
ListViewAdapter globalListAdapter,globalAdapter=null;
public void filteredList()
{
//First of all checks for our globalList is not a null one.
if(globalList!=null)
{
ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
ListViewAdapter globalAdapter = null;
if(!globalQuery.trim().equals(""))
{
boolean isThereAnyThing=false;
for(int i=0;i<globalList.size();i++)
{
//Get the value of globalList that is HashMap indexed at i.
HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
String rank=tempMap.get(MainActivity.RANK);
String country=tempMap.get(MainActivity.COUNTRY);
String population=tempMap.get(MainActivity.POPULATION);
String url=tempMap.get(MainActivity.URL);
String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
{
//If anything matches then it will add to tempList
tempList.add(tempMap);
isThereAnyThing=true;
}
}
//Checks for is there anything matched from the ArrayList with the user type search query
if(isThereAnyThing)
{
//then set the globalAdapter with the new HashMaps tempList
globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
listview.setAdapter(globalAdapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
else
{
//If else set list adapter to null
setListAdapter(null);
}
}
else
{
// Do something when there's no input
if(globalAdapter==null)
{
//If no user inputs then it will list everything in the globalList.
justListAll();
}
else
{
final ListViewAdapter finalGlobalAdapter = globalAdapter;
runOnUiThread(new Runnable()
{
public void run()
{
((ListViewAdapter) finalGlobalAdapter).notifyDataSetChanged();
}
});
}
}
// updating listview
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
mEditText = (EditText) findViewById(R.id.inputSearch);
mEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
// Search
globalQuery=s.toString();
//This method will filter all your categories just calling this method.
filteredList();
} else {
globalQuery="";
//If the text is empty the list all the content of the list adapter
justListAll();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals("")){new DownloadJSON().execute();}
else{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
if (searchString.contains(currentString)) {
//pass the character-sequence instead of currentstring
arrayTemplist.add(arraylist.get(i));
}
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://ndublog.twomini.com/123.txt.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("url",jsonobject.getString("url"));
map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
public void justListAll()
{
ListViewAdapter globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
listview.setAdapter(adapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
}
Thank you for asking the question in a good way as per the SO guidelines.
Iam sure this will solve your question.
//First of all declare a global variables
String globalQuery="";
ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
ListViewAdapter globalListAdapter;
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
// Search
globalQuery=s.toString();
//This method will filter all your categories just calling this method.
filteredList();
} else {
globalQuery="";
//If the text is empty the list all the content of the list adapter
justListAll();
}
}
public void justListAll()
{
globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
listview.setAdapter(adapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
public void filteredList()
{
//First of all checks for our globalList is not a null one.
if(globalList!=null)
{
ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
if(!globalQuery.trim().equals(""))
{
boolean isThereAnyThing=false;
for(int i=0;i<globalList.size();i++)
{
//Get the value of globalList that is HashMap indexed at i.
HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
String rank=tempMap.get(MainActivity.RANK);
String country=tempMap.get(MainActivity.COUNTRY);
String population=tempMap.get(MainActivity.POPULATION);
String url=tempMap.get(MainActivity.URL);
String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
{
//If anything matches then it will add to tempList
tempList.add(tempMap);
isThereAnyThing=true;
}
}
//Checks for is there anything matched from the ArrayList with the user type search query
if(isThereAnyThing)
{
//then set the globalAdapter with the new HashMaps tempList
globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
listview.setAdapter(globalAdapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
else
{
//If else set list adapter to null
setListAdapter(null);
}
}
else
{
// Do something when there's no input
if(globalAdapter==null)
{
//If no user inputs then it will list everything in the globalList.
justListAll();
}
else
{
runOnUiThread(new Runnable()
{
public void run()
{
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
});
}
}
// updating listview
}
}
Only a thing you want to do is populate all the JSON parsed values to the global ArrayList globalList.
Hope it answers the whole question with extra packups.
When you delete the character, the text in the EditText view is null therefore it is looking for null and the list displays null. Make sure you perform a null check before searching through your JSON array.
It looks like you just need to change this line:
String currentString = arraylist.get(i).get(MainActivity.RANK);
to
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
do the following change to your edittext watcher... if the edittext.gettext().tostring().equals("") ...then just execute the asynctask
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals(""))
{
new DownloadJSON().execute();
//this will set you the whole json again to your listview
}
else
{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.RANK);
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
}
and in case of COUNTRY..why its behaving diff...it think you have to match the edittext substring with the arraylist
just replace the following code
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
with
if (searchString.contains(currentString)) {
//pass the character-sequence instead of currentstring
arrayTemplist.add(arraylist.get(i));
}
for COUNTRY search...
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals(""))
{
new DownloadJSON().execute();
//this will set you the whole json again to your listview
}
else
{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
if ( searchString .equalsIgnoreCase(currentString .substring(0,searchString .length()-1))) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
}

Android BaseAdapter only shows correct information once

I'm trying to put together an adapter that will display the number of occurrences in a list. There are two ListViews in a tab host with each being in its own tab. As long as you do not click on the tab that shows the occurrences it will keep up with the data input just fine. The first time you go to view the listview, all of the groups are displayed with the correct amount of occurrences for each; however, from then on it does not want to update properly. At times it will not update at all, re-insert an existing group but still keep the old one.
For example, if I were to put in 10, 20, and 30 the first time I go to view the groups listview I would see:
10 -- 1
20 -- 1
30 -- 1
...but if I were to put in another 10 it would still display the same thing with no update.
When I put something else in like 45 I get:
10 -- 1
20 -- 1
30 -- 1
10 -- 2
I can keep adding other numbers and it will just keep adding in 10 -- 1's or sometimes even more 20's or 30's. If I use debugAll() in the log window it will show that it attempts all of the numbers that I put in, and it will return the correct number of occurences, just the display won't keep up and is displaying more of what is already there.
I have tried putting in several log statements and they show that the information in the adapter is right, just the display is wrong.
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class HashAdapter extends BaseAdapter {
private LinkedHashMap<String, String> mData = new LinkedHashMap<String, String>();
private final ArrayList keyArray = new ArrayList();
private final Context _context;
public HashAdapter (Context context) {
_context = context;
}
#Override
public int getCount() {
return keyArray.size();
}
#Override
public String getItem(int position) {
return mData.get(keyArray.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) { // FIXME
listView = inflater.inflate(R.layout.list_item, null);
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
Log.i("getView Text Is", tile);
} else {
listView = convertView;
}
return listView;
}
public void addNewValue (String key) {
if (mData.containsKey(key)) {
int retrieve = Integer.parseInt(mData.get(key));
mData.put(key, String.valueOf(++retrieve));
} else { // HASH MAP CREATING A NEW KEY WITH VALUE OF 1
mData.put(key, "1");
keyArray.add(0, key);
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void modifyExistingValue (String oldValue, String newValue) {
if (!oldValue.equals(newValue)) {
int newInt = Integer.parseInt(mData.get(oldValue));
if (newInt > 1) {
mData.put(oldValue, String.valueOf(--newInt));
String secondInt = mData.get(newValue);
if (secondInt != null) {
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
} else {
mData.remove(oldValue);
keyArray.remove(oldValue);
mData.put(newValue, "1");
Log.i("Old Value ", oldValue + " Is Gone From HashMap");
}
keyArray.add(0, newValue);
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void removeOccurrence (String oldValue) {
String oldOccurrences = mData.get(oldValue);
if (!oldOccurrences.equals("1")) { // IF THERE ARE ENOUGH REMAINING TO STILL EXIST
int newInt = Integer.parseInt(oldOccurrences);
mData.put(oldValue, String.valueOf(--newInt));
} else { // NOT ENOUGH LEFT...REMOVE IT
mData.remove(oldValue);
keyArray.remove(oldValue);
Log.i("Old Value", oldValue + " Is Gone From HashMap");
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void clear () {
mData.clear();
keyArray.clear();
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void debugValue (String key) {
Log.i("AdapterDebug Value", key + " has " + mData.get(key));
}
public void debugAll () {
int size = keyArray.size();
for (int i = 0; i < size; i++) {
String retrieve = (String) keyArray.get(i);
Log.i("AdapterDebug All", "Attempted " + retrieve + " and retrieved " + mData.get(retrieve));
}
}
}
EDIT:
I figured some one might find the fully working version useful so I'll put this here.
It will keep track of re occurring values. Build off of it, use it as is, I don't care.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
/*
* ARRAY ADAPTER FOR KEEPING TRACK OF REOCCURRING VALUES AND DISPLAYING ON A LISTVIEW
* CREATED BY : COREY WILLIAMS
* 8/13/2014
*
* BeerWare (http://en.wikipedia.org/wiki/Beerware)
* */
class HashAdapter extends BaseAdapter {
private LinkedHashMap<String, String> mData = new LinkedHashMap<String, String>();
private ArrayList keyArray = new ArrayList();
private final Context _context;
public HashAdapter (Context context) {
_context = context;
}
#Override
public int getCount() {
return keyArray.size();
}
#Override
public String getItem(int position) {
return mData.get(keyArray.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
listView = inflater.inflate(R.layout.list_item, null);
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
} else {
listView = convertView;
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
}
return listView;
}
public void addNewValue (String key) {
if (mData.containsKey(key)) {
int retrieve = Integer.parseInt(mData.get(key));
mData.put(key, String.valueOf(++retrieve));
} else { // HASH MAP CREATING A NEW KEY WITH VALUE OF 1
mData.put(key, "1");
keyArray.add(0, key);
}
this.notifyDataSetChanged();
}
public void modifyExistingValue (String oldValue, String newValue) {
if (!oldValue.equals(newValue)) {
int oldAmmount = Integer.parseInt(mData.get(oldValue)); // GET HOW MANY ARE LEFT OF WHAT YOU SELECTED
boolean alreadyHasNewValue = mData.containsKey(newValue);
if (oldAmmount > 1) { // IF THERE IS SOME LEFT
mData.put(oldValue, String.valueOf(--oldAmmount));
if (alreadyHasNewValue) {
String secondInt = mData.get(newValue);
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
} else {
mData.remove(oldValue);
keyArray.remove(oldValue);
if (alreadyHasNewValue) {
String secondInt = mData.get(newValue);
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
}
if (!keyArray.contains(newValue)) {
keyArray.add(0, newValue);
}
}
this.notifyDataSetChanged();
}
public void removeOccurrence (String oldValue) {
String oldOccurrences = mData.get(oldValue);
if (!oldOccurrences.equals("1")) { // IF THERE ARE ENOUGH REMAINING TO STILL EXIST
int newInt = Integer.parseInt(oldOccurrences);
mData.put(oldValue, String.valueOf(--newInt));
} else { // NOT ENOUGH LEFT...REMOVE IT
mData.remove(oldValue);
keyArray.remove(oldValue);
}
this.notifyDataSetChanged();
}
public void clear () {
mData.clear();
keyArray.clear();
this.notifyDataSetChanged();
}
public ArrayList getKeys () {
return keyArray;
}
public void restoreKeys (ArrayList<String> restore) {
keyArray = restore;
this.notifyDataSetChanged();
}
public LinkedHashMap<String, String> getValues () {
return mData;
}
public void restoreValues (LinkedHashMap<String, String> restore) {
mData = restore;
this.notifyDataSetChanged();
}
}
In the "getView" method you must update the content placeholders (TextView(s) in your code) even if "convertView" is not null.
It's because of view recycling system of ListView.
So the updated code could be like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
listView = inflater.inflate(R.layout.list_item, null);
} else {
listView = convertView;
}
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
Log.i("getView Text Is", tile);
return listView;
}

Issue with checkbox checked

i am use this for setting checkbox in listview i have follow all step as per given tutorial, but there are some critical issue with output, is that when i am select first checkbox and scroll down it will change selected item and automatically appear 3rd.
so i think there are something wrong with getview. so please help me out this ....
here is my code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
public class Favorites extends ListActivity {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
ArrayList alAppName;
float[] rate;
boolean[] bSelected;
ArrayList<Comment> alPackagenm;
Drawable[] alIcon;
ViewHolder holder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
for (int i = 0; i < strAr.length; i++) {
System.out.println("strAr[" + i + "] " + strAr[i]);
}
for (String s : strAr) {
list.add(new RowModel(s));
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
}
});
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.ratingBar1.setOnRatingBarChangeListener(l);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
return (row);
}
}
}
I really don't understand your code exactly what you are trying to do. I haven't seen before this you are checking holder == null where as it should be convertView == null. If you have a scrolling issue you can check my blog post
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
...
}
else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
Use Below Code to your MainActivity.java file.
public class ListViewActivity extends Activity {
ListView mLstView1;
Button mBtn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLstView1 = (ListView) findViewById(R.id.mLstView1);
String[] lv_items = { "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil", "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil" };
;
mLstView1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
mLstView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Using a List to hold the IDs, but could use an array.
List<Integer> checkedIDs = new ArrayList<Integer>();
// Get all of the items that have been clicked - either on or
// off
final SparseBooleanArray checkedItems = mLstView1
.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
// And this tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if (isChecked) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// Put the value of the id in our list
checkedIDs.add(position);
System.out.println("Position is:- " + position);
}
}
}
});
}
}

Categories