Search result displayed twice in list view - android

I would like to display the data from MySql in a listview using a search parameter in my application.
I've succeeded, but the problem I'm having is that every time I push the search button twice, both sets of result data are shown in the ListView, whereas I only want to display the latest set of results.
This is the code I'm using:
public class ListPerusahaan extends ListActivity {
/** Called when the activity is first created. */
private static final String TAG_ID = "id";
private static final String TAG_NAMA = "nama_perusahaan";
private static final String TAG_PEKERJAAN = "pekerjaan";
private static final String TAG_ALAMAT= "alamat";
private static final String TAG_DEADLINE = "deadline";
EditText keyword; Button search; private ProgressDialog pDialog; ArrayList<HashMap<String, String>> DataList; // JSONArray perusahaan = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listperusahaan);
keyword=(EditText)findViewById(R.id.Editsearch);
search=(Button)findViewById(R.id.search);
DataList = new ArrayList<HashMap<String, String>>();
search.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v) {
// TODO Auto-generated method stub
if (keyword.getText().toString().length() == 0 ) {
Toast toast = Toast.makeText(getApplicationContext(),"Please enter your keyword", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else {
new searchData().execute();
}
}
});
}
#SuppressLint("NewApi") public class searchData extends AsyncTask<Void, Void, Void>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListPerusahaan.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> paramemeter = new ArrayList<NameValuePair>();
paramemeter.add(new BasicNameValuePair("keyword", keyword.getText().toString()));
JSONObject json = JSONParser.getJSONFromUrl("http://10.0.2.2/appmysql/dataperusahaan.php", paramemeter);
try{
JSONArray perusahaan = json.getJSONArray("perusahaan");
if (perusahaan != null)
{
for(int i=0;i<perusahaan.length();i++){
// HashMap<String, String> map1 = new HashMap<String, String>();
JSONObject jsonobj = perusahaan.getJSONObject(i);
// Storing each json item in variable
String id = jsonobj.getString(TAG_ID);
String nama_perusahaan = jsonobj.getString(TAG_NAMA);
String pekerjaan = jsonobj.getString(TAG_PEKERJAAN);
String alamat = jsonobj.getString(TAG_ALAMAT);
String deadline = jsonobj.getString(TAG_DEADLINE);
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put(TAG_ID, id);
map1.put(TAG_NAMA, nama_perusahaan);
map1.put(TAG_PEKERJAAN, pekerjaan);
map1.put(TAG_ALAMAT, alamat);
map1.put(TAG_DEADLINE, deadline);
// adding HashList to ArrayList
DataList.add(map1);
}
}
else {
Toast toast= Toast.makeText(getApplicationContext(), "No data found", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
catch(JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ListPerusahaan.this, DataList,R.layout.row,
new String[] { TAG_NAMA, TAG_PEKERJAAN, TAG_ALAMAT, TAG_DEADLINE },
new int[] { R.id.nama_perusahaan, R.id.pekerjaan, R.id.alamat,R.id.deadline});
// updating listview
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(ListPerusahaan.this, "Perusahaan '" + o.get("nama_perusahaan") + "' was clicked.", Toast.LENGTH_SHORT).show();
*/
// getting values from selected ListItem
String nama = ((TextView) view.findViewById(R.id.nama_perusahaan)).getText().toString();
String pekerjaan = ((TextView) view.findViewById(R.id.pekerjaan)).getText().toString();
String alamat = ((TextView) view.findViewById(R.id.alamat)).getText().toString();
String deadline = ((TextView) view.findViewById(R.id.deadline)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), detail_lowongan.class);
in.putExtra(TAG_NAMA, nama);
in.putExtra(TAG_PEKERJAAN, pekerjaan);
in.putExtra(TAG_ALAMAT, alamat);
in.putExtra(TAG_DEADLINE, deadline);
startActivity(in);
}
});
}
});
}
}
}

Edit: in onclick clear DataList
search.setOnClickListener(){
......
DataList.clear(); //in onclick method
}
I am not sure whether you are looking for this or not...but if you don't want to allow duplicates in your list try ....
When the data filled in your list
Set<type> set=new Hashset(yourlist);
ArrayList<type> nodupList=new ArrayList<type>();
noduplist.addAll(set);
using this way it will remove the duplicates in your list
Edit:
Try this
After for loop
Set<HashMap> set=new HashSet(DataList);
ArrayList<HashMap> nodupList=new ArrayList<HashMap>();
nodupList.addAll(set);
DataList.clear();
DataList.addAll(nodupList);
try it may help you

Clear the DataList of the ArrayList type before populating it in the for loop.

Related

How to use listview from different xml layout file

I am working on android ListView and i am getting one issue.I created one list view into the XML file installation.xml and i want to use that list view into my Searchdata.java. so basically what i want that when i click on searchdata button than data is fetched from web service and after parsing, it will saved into the listview.and when i click on Installation View button than new window will be appear where i could see that list data.
SearchData.java
public class SearchData extends Activity {
EditText Keyword;
JSONParser jsonparser = new JSONParser();
ListView Datalist;
HorizontalScrollView VideoDatalist;
ArrayList<HashMap<String, String>> DataList;
ArrayList<HashMap<String, String>> VideoDataList;
JSONArray contacts = null;
private ProgressDialog pDialog;
ImageButton searchdata,InstallationView;
String Keyvalue = new String();
private static final String TAG_InnerText = "InnerText";
private static final String TAG_Title = "Title";
private static final String TAG_URL = "URL";
private static final String TAG_VIDEO_URL = "URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_data);
InstallationView=(ImageButton)findViewById(R.id.InstallationView);
Keyword = (EditText) findViewById(R.id.KeyData);
Datalist=(ListView)findViewById(R.layout.activity_installation);
VideoDatalist=(HorizontalScrollView)findViewById(R.id.Horizontallist);
searchdata=(ImageButton)findViewById(R.id.searchicon);
String Keyvalue = new String();
DataList = new ArrayList<HashMap<String, String>>();
VideoDataList = new ArrayList<HashMap<String, String>>();
searchdata.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ReadData().execute();
}
});
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
startActivity(new Intent(SearchData.this, Installation.class));
}
});
}
public class ReadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchData.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
try{
Keyvalue=Keyword.getText().toString();
String Jsonstr = jsonparser.makeHttpRequest("http://10.47.93.26:8080/Search/api/Search/"+Keyvalue);
try {
if (Jsonstr != null) {
JSONArray jsonObj = new JSONArray (Jsonstr);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String name = c.optString(TAG_Title);
String url = c.optString(TAG_URL);
HashMap<String, String> info = new HashMap<String, String>();
if( !name.isEmpty() )
{
info.put(TAG_Title, name);
}
else
{
info.put(TAG_Title,"User Manual");
}
if(url.contains("youtube"))
{
info.put(TAG_URL, url);
VideoDataList.add(info);
}
else
{
info.put(TAG_URL, url);
DataList.add(info);
}
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
SimpleAdapter adapter = new SimpleAdapter(
SearchData.this, DataList,
R.layout.list_item, new String[]
{
TAG_Title
}, new int[] {
R.id.InnerText });
Datalist.setAdapter(adapter);
}
}
}
web service running and parsing code is running correctly. i am getting error at post method,so can you help me on this.
Error
Call your Installation activity in onClick() method:
And pass your ArrayList data through intent,
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
Intent intent= new Intent(SearchData.this, Installation.class);
intent.putParcelableArrayListExtra("HASH_MAP",DataList);
startActivity(intent);
}
});
In your Installation activity class,set the view in onCreate() and initialize listview from xml file:
setContentView(R.layout.activity_installation);
ListView listView = (ListView)findViwById(R.id.listview);
And try to get the data from intent:
ArrayList<HashMap<String,String>> hashmap_dataList = getIntent.getParcelableArrayListExtra("HASH_MAP");
then do whatever you want with listview and hashmap.
In the onCreate(...) method of your SearchData Activity, the following can never work and will always return 'null' (hence your NullPointerException)...
Datalist=(ListView)findViewById(R.layout.activity_installation);
Calling findViewById(...) will only work for any UI elements which have been inflated when you called setContentView(...). In this case you used R.layout.activity_search_data for your layout file which doesn't contain a ListView with an id of R.layout.activity_installation which is, by the way, a resource id of a layout file and not a resource id of a UI element.
The only way you can do what you need is to put your data as an extra into the Intent you use when you call...
startActivity(new Intent(SearchData.this, Installation.class));
...when the Installation Activity is created it will then need to get the data and create its own adapter.
EDIT: HashMap is Serializable and can be passed as an Intent extra. Pass your DataList HashMap as follows...
Intent i = new Intent(SearchData.this, Installation.class);
i.putExtra("data_list", DataList);
startActivity(i);
In the Installation Activity you can then use...
getIntent().getSerializableExtra("data_list");

Android window leak error in fragment

Hi I am working with android Fragments. I created a progress dialogue while loading json from the server using asynchronous task .But it works fine and some times cause window leak error. I created the dialogue in onPreExcecute method and load contents in doingbackground and dismiss my dialogue in onpost excecute method.I think this is the right way .But why did I cause this window leak error sometimes ?? This is my code .Please help me Thanks in advance :)
public class PendingWork extends Fragment {
ListView lv;
public ProgressDialog pDialog;
EditText inputSearch;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
static ArrayList<HashMap<String, Object>> pendingList = new ArrayList<HashMap<String, Object>>();
SharedPreferences app_pref;
SharedPreferences.Editor appedt;
static JSONArray jArray2 = null;
String picture, complaint_id[],complaint_type[],engine_model[],customer_id[],customer_name[],customer_address[],description[],date[];
// Inbox JSON url
final String PENDING_URL = "myURl";
// ALL JSON node names
private static final String TAG_ID = "cmp_id";
private static final String TAG_TYPE = "cmp_type";
private static final String TAG_ENGINE = "engine";
private static final String TAG_NAME = "cust_name";
private static final String TAG_DATE = "date";
private static final String TAG_DESC = "descriptn";
private String TAG_PIC;
int textlength=0;
//Date strDate;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pending_list, container, false);
inputSearch = (EditText)rootView. findViewById(R.id.inputSearch);
// Hashmap for ListView
HashMap<String, Object> map = new HashMap<String, Object>();
pendingList.clear();
// Loading pending list in Background Thread
new Loadpending().execute();
lv = (ListView)rootView.findViewById(R.id.list);
lv.setTextFilterEnabled(true);
// lv.setBackgroundResource(R.drawable.bg);
app_pref = getActivity().getSharedPreferences("MY_PREF",getActivity().MODE_PRIVATE);
appedt=app_pref.edit();
/*--------------------------------------------------listview click listener------------------------------------------------*/
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> apt, View v, int pos,
long id) {
// TODO Auto-generated method stub
appedt.putString("complt_id", complaint_id[pos]);
// appedt.putString("imei", IMEI_no);
appedt.commit();
Bundle b = new Bundle();
b.putString("type", complaint_type[pos]);
b.putString("id", complaint_id[pos]);
b.putString("date", date[pos]);
b.putString("engine", engine_model[pos]);
b.putString("cus_name", customer_name[pos]);
b.putString("cus_id", customer_id[pos]);
b.putString("cus_addr", customer_address[pos]);
b.putString("desc", description[pos]);
b.putString("flag", "1");
Intent in=new Intent(getActivity(),Pend_Details.class);
in.putExtras(b);
startActivity(in);
}
});
inputSearch.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s,
int start, int count, int after)
{
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = inputSearch.getText().length();
pendingList.clear();
for (int j = 0; j < jArray2.length(); j++)
{
try {
if (textlength <= jArray2.getJSONObject(j).length())
{
if(inputSearch.getText().toString().equalsIgnoreCase((String)((CharSequence) jArray2.getJSONObject(j).getString("complnt_type")).subSequence(0,textlength)) ||
inputSearch.getText().toString().equalsIgnoreCase((String)((CharSequence) jArray2.getJSONObject(j).getString("name")).subSequence(0,textlength)) )
{
SetList(j);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), pendingList,
R.layout.fragment_pending_list_item2, new String[] { TAG_TYPE, TAG_NAME, TAG_DATE},
new int[] { R.id.title,R.id.name, R.id.location});
// updating listview
lv.setAdapter(adapter);
}
});
return rootView;
}
class Loadpending extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pendingList.clear();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Inbox JSON
* */
protected String doInBackground(String... args) {
app_pref=getActivity().getSharedPreferences("MY_PREF", 0);
String tech_id = app_pref.getString("username", "");
jArray2 = jsonParser.ParseJson(PENDING_URL, "GET",tech_id);
//Log.w("Lengh",""+jArray2.length());
complaint_id = new String[jArray2.length()];
complaint_type = new String[jArray2.length()];
engine_model = new String[jArray2.length()];
customer_id = new String[jArray2.length()];
customer_name = new String[jArray2.length()];
customer_address = new String[jArray2.length()];
description = new String[jArray2.length()];
date = new String[jArray2.length()];
pendingList.clear();
for (int i = 0; i < jArray2.length(); i++) {
SetList(i);
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), pendingList,
R.layout.fragment_pending_list_item2, new String[] { TAG_TYPE, TAG_NAME, TAG_DATE},
new int[] { R.id.title,R.id.name, R.id.location });
// updating listview
lv.setAdapter(adapter);
pDialog.dismiss();
}
});
}
}
}
Add this check before show your ProgressDialogue
if(!isCancelled())
{
dialog.show();
}

Calling specific activities in android when listview item is clicked

I want to call a specific Activity when a list item is clicked. Using if statements or case in my ListView click event handler and using String fclass_state variable, I have 4 activities to be called. How do I go about it?
public class OutletsList extends ListActivity{
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
private static final String READ_COMMENTS_URL = "myurl";
// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_OUTLET_NAME = "outlet_name";
private static final String TAG_POSTS = "posts";
private static final String TAG_SPARKLING_CLASSIFICATION = "sparkling_classification";
private static final String TAG_SPARKLING_CHANNEL = "sparkling_channel";
private static final String TAG_CLASS = "class";
// An array of all of our comments
private JSONArray mOutlets = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mOutletsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.outlets_list);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadMathQuestions().execute();
}
/* public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
*/
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content.
mOutletsList = new ArrayList<HashMap<String, String>>();
// Instantiating the json parser J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
//Catcing Exceptions
try {
//Checking the amount of data rows.
mOutlets = json.getJSONArray(TAG_POSTS);
// looping through the database
for (int i = 0; i < mOutlets.length(); i++) {
JSONObject c = mOutlets.getJSONObject(i);
// gets the content of each tag
String outlet = c.getString(TAG_OUTLET_NAME);
String schannel = c.getString(TAG_SPARKLING_CHANNEL);
String spclassification = c.getString(TAG_SPARKLING_CLASSIFICATION);
String cls = c.getString(TAG_CLASS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_OUTLET_NAME, outlet );
map.put(TAG_SPARKLING_CHANNEL, schannel);
map.put(TAG_SPARKLING_CLASSIFICATION, spclassification);
map.put(TAG_CLASS, cls);
// adding HashList to ArrayList
mOutletsList.add(map);
// JSON data parsing completed by hash mappings
// list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet, new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL,
TAG_SPARKLING_CLASSIFICATION, TAG_CLASS}, new int[]
{ R.id.outlet_name, R.id.sparkling_channel, R.id.sparkling_classification,
R.id.cls_state});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String>map = (HashMap<String, String>)parent.getItemAtPosition(position);
String foutname = map.get(TAG_OUTLET_NAME);
String fchannel = map.get(TAG_SPARKLING_CHANNEL);
String fclass = map.get(TAG_SPARKLING_CLASSIFICATION);
String fclass_state = map.get(TAG_CLASS);
Intent i = new Intent(OutletsList.this, GdgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
});
}
public class LoadMathQuestions extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(OutletsList.this);
pDialog.setMessage("Loading outlets please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Use this code as an example to replace where your Intent is created:
Intent i = new Intent();
// Additional Extras
if(fclass_state.equals("GOLD")){
i.setClass(OutletList.this, GoldActivity.class);
// additional extras
} else if(fclass_state.equals("SILVER")){
i.setClass(OutletList.this, SilverActivity.class);
// additional extras
} else if(fclass_state.equals("BRONZE")){
i.setClass(OutletList.this, BronzeActivity.class);
// additional extras
} else {
i.setClass(OutletList.this, UnassignedActivity.class);
// additional extras
}
In your onClick method:
switch(position) {
// first list item selected
case 0:
Intent i = new Intent(OutletsList.this, GdgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
break;
// second list item selected
case 1:
...
}

Android parsed json data and add a search functionality

Sorry for my bad english.I am new to android and i parsed json data into listview,now i want to put on him a search functionality,but i have a problem,when i entered a words in edittext,then in the listview my items are duplicated,and items has been increases,look my code and screen shots.Thanks in advance and any help will be much appreciated.
My Artist Activity:
public class Artists extends Activity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// This is not using now if you want you can remove its all references :)
ArrayList<HashMap<String, String>> albumsList;
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
private LazyAdapterArtist mLazyAdatper = null;
private ArrayList<String> array_sort = new ArrayList<String>();
int textlength = 0;
// albums JSONArray
JSONArray albums = null;
LinearLayout ll_artists_chart;
LinearLayout ll_artists_newrelease;
private EditText etSearch;
private static String URL_ALBUMS = "http://triplevmusic.com/dev/webservice/index.php?op=fetch_artists.json";
// JSON Node names
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private ListView lv = null;
EditText et_artists_searchWord;
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.artists);
lv = (ListView) findViewById(R.id.artist_main_list_id);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Artists.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
/**
* Listview item click listener TrackListActivity will be lauched by
* passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
}
});
ll_artists_chart = (LinearLayout) findViewById(R.id.ll_artists_chart);
ll_artists_newrelease = (LinearLayout) findViewById(R.id.ll_artists_newrelease);
et_artists_searchWord = (EditText) findViewById(R.id.et_artists_searchWord);
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOs, true);
mAdapterDTOs.addAll(list);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
ll_artists_chart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), ChartActivity.class);
startActivity(intent);
// finish();
}
});
ll_artists_newrelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), NewReleases.class);
startActivity(intent);
//finish();
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Artists.this);
pDialog.setMessage("Listing Artists ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
//List<NameValuePair> params = new ArrayList<NameValuePair>();
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_ALBUMS);
// getting JSON string from URL
//String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", params);
// Check your log cat for JSON reponse
Log.i("Albums JSON: ", "> " + json);
try {
//albums = new JSONArray(json);
albums = json.getJSONArray(TAG_CONTACTS);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
/*String EateryThmbnailUrl = c
.getString(TAG_THMBNAIL_URL);*/
// ~\/Uploads\/EateryImages\/\/7\/41283f1f-8e6f-42d4-b3c1-01f990efb428.gif
/*EateryThmbnailUrl = HOST_URL
+ EateryThmbnailUrl.replace("~", "");*/
AdapterDTOArtist adapterDTO = new AdapterDTOArtist();
adapterDTO.setmTag_Id(id);
adapterDTO.setmTag_Name(name);
// adapterDTO.setmImage_URL(EateryThmbnailUrl);
mAdapterDTOs.add(adapterDTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
albumsList.add(map);
}
} else {
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// updating listview
mLazyAdatper = new LazyAdapterArtist(Artists.this,
mAdapterDTOs);
lv.setAdapter(mLazyAdatper);
// mLazyAdatper.setDataSet(mAdapterDTOs);
}
});
}
}
public static List<AdapterDTOArtist> filter(String string,
Iterable<AdapterDTOArtist> iterable, boolean byName) {
if (iterable == null)
return new LinkedList<AdapterDTOArtist>();
else {
List<AdapterDTOArtist> collected = new LinkedList<AdapterDTOArtist>();
Iterator<AdapterDTOArtist> iterator = iterable.iterator();
if (iterator == null)
return collected;
while (iterator.hasNext()) {
AdapterDTOArtist item = iterator.next();
collected.add(item);
}
return collected;
}
}
}
My AdapterDTOArtist class :
public class AdapterDTOArtist {
private String mTag_Id;
private String mTag_Name;
public String getmTag_Name() {
return mTag_Name;
}
public void setmTag_Name(String mTag_Name) {
this.mTag_Name = mTag_Name;
}
public String getmTag_Id() {
return mTag_Id;
}
public void setmTag_Id(String mTag_Id) {
this.mTag_Id = mTag_Id;
}
}
My LazyAdapterArtist class:
public class LazyAdapterArtist extends BaseAdapter {
private Context mContext = null;
private ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
public LazyAdapterArtist(Context context,
ArrayList<AdapterDTOArtist> mAdapterDTOs2) {
// TODO Auto-generated constructor stub
this.mContext = context;
this.mAdapterDTOs = mAdapterDTOs2;
}
public void setDataSet(ArrayList<AdapterDTOArtist> adapterDTOs) {
this.mAdapterDTOs = adapterDTOs;
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mAdapterDTOs.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder mHolder = new ViewHolder();
if (row == null) {
// Cell is inflating for first time
row = LayoutInflater.from(mContext)
.inflate(com.whizpool.triplevmusic.R.layout.row_artists,
null, false);
mHolder.mNameTxt = (TextView) row
.findViewById(com.whizpool.triplevmusic.R.id.tv_row_artists);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
mHolder.mNameTxt.setText(mAdapterDTOs.get(position).getmTag_Name());
return row;
}
static class ViewHolder {
TextView mNameTxt = null;
}
}
when parsed json data into listview my app look like this:
when enter word in edittext field then my app look like this:
I just want,when i entered the word for example i enter "D" then in a listview only those words were display which have starting word is "D".Thanks Alot and again sorry for my english.
The problem is that when you filter the data you add again to mAdapterDTOs list the results you need to clear the list before adding the results. To avoid losing your data you have to keep them in a separate list and when user times nothing show them.
Step 1: Use a field for keeping a backup of your data (just as mAdapterDTOs):
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
ArrayList<AdapterDTOArtist> mAdapterDTOsBackup= null;
Step 2: initialize that field:
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
mAdapterDTOsBackup = new ArrayList<AdapterDTOArtist>();
Step 3: Fill in all your data to the backup set just after parsing:
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// HERE all your code as it is!!!
// Just before return add a set keeping the backup of your data...
// initialize the set just as mAdapterDTOs
mAdapterDTOsBackup.addAll(mAdapterDTOs);
return null;
}
Step 4: When searching filter data from backup set and then add them on the mAdapterDTOs do not forget to clear it before.
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOsBackup, true);
mAdapterDTOs.clear(); // <--- clear the list before add
mAdapterDTOs.addAll(list); // <--- here is the double add if you do not clear before
mLazyAdatper.setDataSet(mAdapterDTOs);// update the adapter data (edit 2)
}
Edit: split answer in steps in order to be more clear the process also added at least one of your line to show where to add each code snippet.

Async Task in android not working

This is a follow up question from my question thread exiting error in android
I created an async task but the values do not show up in the list view....
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{
// TODO Auto-generated method stub
Toast.makeText(this, "u clicked " + listItems.get(position) ,Toast.LENGTH_LONG).show();
}
public void getInfo(){
DownloadInfo task = new DownloadInfo();
task.execute(new String[] { "http://www.vogella.de" });
}
private class DownloadInfo extends AsyncTask<String, Void , ArrayList<String>>{
#Override
protected ArrayList<String> doInBackground(String ... strings) {
ArrayList<String> listItems1;
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems1 = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"URL"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
if ( driver.getString("DATABASE ERROR").equals("False")){
int length = Integer.parseInt( driver.getString("length"));
Log.i(TAG,"length is " + length);
for( int i =0 ; i< length ; i++){
String info = driver.getString(Integer.toString(i));
String[] array = info.split(",");
Log.i(TAG,"array is " + Arrays.toString(array));
Log.i(TAG,"Date "+ array.length);
Log.i(TAG,"DONE WITH THE LOOP");
//listInfo.add(item);
Log.i(TAG,"Date is"+array[0]);
listItems1.add(array[0]);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems1.add("No driver rides created");
}
return listItems1;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.notifyDataSetChanged();
}
}
}
The problem is that the values in the adapter do not get modified...
You initialize your adapter with a empty listItems, after your fill your listItems in AsyncTask. onPostExecute(), your adapter is not get updated, try this:
protected void onPostExecute(ArrayList<String> result) {
listItems = result;
adapter.addAll(ListItems);
adapter.notifyDataSetChanged();
}
Hope that help.
listItems = result; won't work, you need to use :
listItems.clear();
listItems.addAll(result);
If you create another list, your adapter won't know it, because it keeps a reference to the old list (which remains the same).

Categories

Resources