So i have a AsyncTask that pulls data from a Mysql database and displays it, currently this works fine but i need to change the simple adapter to a custom adapter so i can do more with what is displayed. But i'm not sure what i need to change in order to get my custom adapter to work with my AsyncTask.
public class SearchFor extends AppCompatActivity implements View.OnClickListener {
DBManager db;
ListView lv;
myAdapter myAdapter;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> attractionList;
ArrayList<HashMap<String, String>> transportList;
// url to get all attraction list
private static String url_all_attractions = "http://10.0.2.2/TravelApp/get_all_attractions.php";
private static String url_all_transport = "http://10.0.2.2/TravelApp/get_all_transport.php";
// JSON Node names for attraction
private static final String TAG_SUCCESS = "success";
private static final String TAG_ATTRACTION = "attraction";
private static final String TAG_ATTRACTIONID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_TYPE = "Type";
private static final String TAG_LOCATION = "Location";
private static final String TAG_OPENING = "OpeningTime";
private static final String TAG_CLOSING = "ClosingTime";
private static final String TAG_NEARBYSTOP = "NearbyStop";
private static final String TAG_LATITUDE = "Latitude";
private static final String TAG_LONGITUDE = "Longitude";
//JSON Node names for transport
private static final String TAG_TRANSPORT = "transport";
private static final String TAG_TRANSPORTID = "Id";
private static final String TAG_TIME = "Time";
private static final String TAG_NEXTSTOP = "NextStop";
private static final String TAG_PHONENUMBER = "PhoneNumber";
// attraction JSONArray
JSONArray attraction = null;
JSONArray transport = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_for);
db = new DBManager(this);
// Hashmap for ListView
attractionList = new ArrayList<HashMap<String, String>>();
transportList = new ArrayList<HashMap<String, String>>();
lv = (ListView) findViewById(R.id.list_search);
this.registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId()== R.id.list_search ){
this.getMenuInflater().inflate(R.menu.context_menu_more,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menuBookmark:
testAdd();
break;
case R.id.menuDirections:
break;
default:
return super.onContextItemSelected(item);
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, menu);
getMenuInflater().inflate(R.menu.optionsmenu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.go_home){
Intent i = new Intent(getApplicationContext(),QavelNav.class);
startActivity(i);
}
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
if(id == R.id.attractionSub1){
new LoadAllAttractions().execute();
}else if(id == R.id.attractionSub2){
Toast.makeText(getApplicationContext(),"Pubs", Toast.LENGTH_LONG).show();
}else if(id == R.id.attractionSub3){
}else if(id == R.id.attractionSub4){
}else if(id == R.id.transportSub1){
new LoadAllTransport().execute();
}else if(id == R.id.transportSub2){
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
System.out.println(position);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllAttractions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchFor.this);
pDialog.setMessage("Loading attractions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All attraction from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_attractions, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Attractions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// attraction found
// Getting Array of Products
attraction = json.getJSONArray(TAG_ATTRACTION);
// looping through All Products
for (int i = 0; i < attraction.length(); i++) {
JSONObject c = attraction.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ATTRACTIONID);
String name = c.getString(TAG_NAME);
String type = c.getString(TAG_TYPE);
String location = c.getString(TAG_LOCATION);
String opening = c.getString(TAG_OPENING);
String closing = c.getString(TAG_CLOSING);
String nearbyStop1 = c.getString(TAG_NEARBYSTOP);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ATTRACTIONID, id);
map.put(TAG_NAME, name);
map.put(TAG_TYPE, type);
map.put(TAG_LOCATION, location);
map.put(TAG_OPENING,opening);
map.put(TAG_CLOSING,closing);
map.put(TAG_NEARBYSTOP, nearbyStop1);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
attractionList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
final ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
// dismiss the dialog after getting all attraction
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchFor.this, attractionList,
R.layout.list_attractions, new String[]{TAG_ATTRACTIONID,
TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_OPENING,TAG_CLOSING,TAG_NEARBYSTOP,TAG_LATITUDE,TAG_LONGITUDE},
new int[]{R.id.Attractionid, R.id.tvAttractionName, R.id.tvAttractionType, R.id.tvAttractionLocation,R.id.tvAttractionOpening,R.id.tvAttractionClosing,R.id.tvAttractionNearbyStop1});
// updating listview
//myAdapter = new myAdapter(listData);
lv.setAdapter(adapter);
}
});
}
}
class LoadAllTransport extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchFor.this);
pDialog.setMessage("Loading Transport. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All attraction from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_transport, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Transport: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// attraction found
// Getting Array of Products
transport = json.getJSONArray(TAG_TRANSPORT);
// looping through All Products
for (int i = 0; i < transport.length(); i++) {
JSONObject c = transport.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_TRANSPORTID);
String name = c.getString(TAG_NAME);
String type = c.getString(TAG_TYPE);
String location = c.getString(TAG_LOCATION);
String time = c.getString(TAG_TIME);
String nextStop = c.getString(TAG_NEXTSTOP);
String phoneNumber = c.getString(TAG_PHONENUMBER);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TRANSPORTID, id);
map.put(TAG_NAME, name);
map.put(TAG_TYPE, type);
map.put(TAG_LOCATION, location);
map.put(TAG_TIME,time);
map.put(TAG_NEXTSTOP,nextStop);
map.put(TAG_PHONENUMBER, phoneNumber);
// adding HashList to ArrayList
transportList.add(map);
}
}
} 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 attraction
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchFor.this, transportList,
R.layout.list_transport, new String[]{TAG_TRANSPORTID,
TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_TIME,TAG_NEXTSTOP,TAG_PHONENUMBER},
new int[]{R.id.transportid, R.id.tvTransportName, R.id.tvTransportType, R.id.tvTransportLocation,R.id.tvTransportPhone});
// updating listview
lv.setAdapter(adapter);
}
});
}
}
public void testAdd(){
TextView TextName = (TextView)findViewById(R.id.tvAttractionName);
System.out.println(TextName.getText().toString());
}
public void addAttraction(View v){
TextView TextName = (TextView)findViewById(R.id.tvAttractionName);
System.out.println(TextName.getText().toString());
TextView TextType = (TextView) findViewById(R.id.tvAttractionType);
TextView TextLocation = (TextView)findViewById(R.id.tvAttractionLocation);
TextView TextOpening = (TextView)findViewById(R.id.tvAttractionOpening);
TextView TextClosing = (TextView)findViewById(R.id.tvAttractionClosing);
TextView TextNearbyStop = (TextView)findViewById(R.id.tvAttractionNearbyStop1);
ContentValues values = new ContentValues();
values.put(DBManager.ColName,TextName.getText().toString());
values.put(DBManager.ColType,TextType.getText().toString());
values.put(DBManager.ColLocation,TextLocation.getText().toString());
values.put(DBManager.ColOpening,TextOpening.getText().toString());
values.put(DBManager.ColClosing,TextClosing.getText().toString());
values.put(DBManager.ColNearbyStop,TextNearbyStop.getText().toString());
long id = db.Insert("BookmarkAttraction",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
public void addTransport(View v){
TextView TextName = (TextView)findViewById(R.id.tvTransportName);
TextView TextType = (TextView) findViewById(R.id.tvTransportType);
TextView TextLocation = (TextView)findViewById(R.id.tvTransportLocation);
TextView TextPhoneNumber = (TextView)findViewById(R.id.tvTransportPhone);
ContentValues values = new ContentValues();
values.put(DBManager.ColName,TextName.getText().toString());
values.put(DBManager.ColType,TextType.getText().toString());
values.put(DBManager.ColLocation,TextLocation.getText().toString());
values.put(DBManager.ColPhoneNumber,TextPhoneNumber.getText().toString());
long id = db.Insert("BookmarkTransport",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_attractions, null);
final Adapter ac = listItem.get(position);
TextView attractionId = (TextView) myView.findViewById(R.id.Attractionid);
attractionId.setText(ac.ID);
TextView Name = (TextView) myView.findViewById(R.id.tvAttractionName);
Name.setText(ac.Name);
TextView Type = (TextView) myView.findViewById(R.id.tvAttractionType);
Type.setText(ac.Type);
TextView Location = (TextView) myView.findViewById(R.id.tvAttractionLocation);
Location.setText(ac.Location);
TextView Opening = (TextView) myView.findViewById(R.id.tvAttractionOpening);
Opening.setText(ac.Opening);
TextView Closing = (TextView) myView.findViewById(R.id.tvAttractionClosing);
Closing.setText(ac.Closing);
TextView NearbyStop1 = (TextView) myView.findViewById(R.id.tvAttractionNearbyStop1);
NearbyStop1.setText(ac.NearbyStop);
return myView;
}
}
}
The parts of interest are the custom adapter (myAdapter) located at the bottom and the first AsyncTask is what im trying to convert to a custom adapter. The onPostExecute is where the the simple adapter is and probably where i need to reference the custom adapter but need help with this
Seems you're using a single adapter for both of your needs.
Did you think about creating a two Custom Adapter classes for your two AsyncTasks.
Also few suggestions:
1. You can use Loader Callbacks and Cursor loader If you're using AsyncTask for DB fetching.
2. preExecute and postExecute already run on UI thread. So no need of runOnUIThread call there.
3. Use ViewHolder pattern in the Adapters getView method for better optimization.
Related
So I'm showing images in a gridview from a json response.
Each image comes in a json response like:
{poster_path=/u1LHo5ObRZA1r8pzSq0OqQ2qlaU.jpg, vote_average=0.0, title=The Beauty Inside, vote_count=0, overview=Woo-Jin changes into a different person when he wakes up. He falls in love with Yi-Soo., id=338729, release_date=2015-08-20}
poster_path contains the image url.
When the poster_path is null like:
{poster_path=null, vote_average=0.0, title=The Bad Education Movie, vote_count=0, overview=Mr Wickers and his class go on one final school trip after they finish their GCSEs., id=348296, release_date=2015-08-21}
I want to remove this item in my Hashmap if it contains poster_path=null so it doesn't load that data into my gridView.
How can this be done?
Here is my activity which downloads and parses the json response:
public class Upcoming extends android.support.v4.app.Fragment {
private static final String KEY_POSITION = "position";
private static final String TAGG = "TMDB Pop Movies";
private static final String apiKey = "MYKEY";
private static final String tmdbURL = "MYURL";
private static final String TAG_MOVIES = "results";
static final String TAG_ID = "id";
static final String TAG_RELEASE = "release_date";
static final String TAG_TITLE = "title";
static final String TAG_POSTER = "poster_path";
static final String TAG_VOTE_AVG = "vote_average";
static final String TAG_VOTE_COUNT = "vote_count";
static final String TAG_OVERVIEW = "overview";
String NumberOfPage = "&page=1";
ArrayList<HashMap<String, String>> mylist;
JSONObject json = null;
JSONArray results = null;
UpcomingGridViewAdapter adapter;
GridView Gridv;
int numberofpagesshown = 0;
private String position;
private OnFragmentInteractionListener mListener;
public static Upcoming newInstance(int position) {
Upcoming fragment = new Upcoming();
Bundle args = new Bundle();
args.putInt(KEY_POSITION, position);
fragment.setArguments(args);
return fragment;
}
public Upcoming() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
position = getArguments().getString(KEY_POSITION);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View newview = inflater.inflate(R.layout.fragment_upcoming, container, false);
//Initialize with empty data
mylist = new ArrayList<HashMap<String, String>>();
// Start download void
new DownloadJSON().execute();
return newview;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
// Downloading data asynchronously
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... url) {
json = JSONfunctions.getJSONfromURL(tmdbURL + "/3/movie/upcoming"
+ apiKey + NumberOfPage);
try {
// Get the array of movies
results = json.getJSONArray(TAG_MOVIES);
// loop through all the movies
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String poster = r.getString(TAG_POSTER);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
Gridv = (GridView) getActivity().findViewById(R.id.upcoming_gridlayout);
adapter = new UpcomingGridViewAdapter(getActivity(), mylist);
Gridv.setAdapter(adapter);
}
else {
adapter.notifyDataSetChanged();
}
// Attach the listener to the AdapterView onCreate
Gridv.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if (numberofpagesshown == 1) {
NumberOfPage = "&page=2";
new DownloadJSON().execute();
} else if (numberofpagesshown == 2) {
NumberOfPage = "&page=3";
new DownloadJSON().execute();
} else if (numberofpagesshown == 3) {
NumberOfPage = "&page=4";
new DownloadJSON().execute();
} else if (numberofpagesshown == 4) {
NumberOfPage = "&page=5";
new DownloadJSON().execute();
} else if (numberofpagesshown == 5) {
NumberOfPage = "&page=6";
new DownloadJSON().execute();
}
}
});
}
}
}
And finally the gridView Adapter:
public class UpcomingGridViewAdapter extends BaseAdapter {
public boolean pressedMovieItem;
Context context;
ArrayList<HashMap<String, String>> data;
// Will store json data
HashMap<String, String>mylist = new HashMap<>();
public UpcomingGridViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.upcoming_grid_item, parent, false);
}
final ImageView poster = (ImageView) convertView.findViewById(R.id.upcoming_image);
mylist = data.get(position);
final String posterPath = mylist.get("poster_path");
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
final String url = "http://image.tmdb.org/t/p/w185" + posterPath;
if(mylist.get("poster_path") != "null") {
// load image url into poster
Picasso.with(context).load(url).into(poster);
}
else{
// load image url into poster
// Picasso.with(context).load(R.drawable.ic_local_movies_black_24dp).into(poster);
poster.setBackgroundColor(Color.parseColor("#F5F5F5"));
// poster.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
}
Just change you for loop inside doInBackground() like this. It would simply won't add that node in ArrayList
for (int i = 0; i < results.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String poster = r.getString(TAG_POSTER);
if(poster == null || poster.equals(""))
continue;
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}
Made a little modification:
// loop through all the movies
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String poster = r.getString(TAG_POSTER);
if(poster == null || poster.equals("")|| poster.equals("null"))
continue;
else {
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}
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();
}
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:
...
}
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.
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.