Search hashmap for string and remove - android

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

Related

Return button to previous activity with BaseAdapter

I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}

Android studio adding custom adapter to AsyncTask

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.

How to add adapter2 with asynctask inside adapter1

I've this adapter class :
public class NoteFeedListAdapter extends RecyclerView.Adapter<feedItemsHolder>{
private Activity activity;
private LayoutInflater inflater;
private List<NoteFeedItem> feedItems;
private List<CommentModel> commentItems;
private NoteCommentListAdapter adapter;
private RecyclerView mRecyclerView;
ImageLoader imageLoader = NoteAppController.getInstance().getImageLoader();
private static final String URL_LIST_VIEW_COMMENT = "http://url.com";
private int level = 0;
private Context mContext;
public NoteFeedListAdapter(Context context, List<NoteFeedItem> feedItems) {
this.feedItems = feedItems;
this.mContext = context;
}
public feedItemsHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.feed_item, null);
feedItemsHolder mh = new feedItemsHolder(v);
return mh;
}
public void onBindViewHolder(final feedItemsHolder fItemsHolder, final int i) {
final NoteFeedItem item = feedItems.get(i);
fItemsHolder.setLevel(item.getLevel());
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
and Inside onBindViewHolder :
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this code is what I used to call asyntask but result from asynctask cannot be shown in this adapter
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView = new RecyclerView(mContext);
getListViewComments(item.getUserid(), item.getId(),fItemsHolder,i, commentItems, adapter, mRecyclerView);
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView.setAdapter(adapter);
}
});
}
...
} else {
fItemsHolder.mHiddenComment.setVisibility(View.GONE);
fItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
}
if(item.getLevel() == Level.LEVEL_ONE){
level = Level.LEVEL_TWO;
}else if(item.getLevel() == Level.LEVEL_TWO){
level = Level.LEVEL_THREE;
}
}
public int getItemCount() {
return (null != feedItems ? feedItems.size() : 0);
}
private void getListViewComments(final String userid, String id_note,final feedItemsHolder feedItemsHolder, int i, final List<CommentModel> commentItems, final NoteCommentListAdapter adapter, final RecyclerView mRecyclerView) {
class ambilComment extends AsyncTask<String, Void, String> {
ProgressDialog loading;
com.android.personal.asynctask.profileSaveDescription profileSaveDescription = new profileSaveDescription();
String result = "";
InputStream inputStream = null;
#Override
protected void onPreExecute() {
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLoading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("userid", params[0]);
data.put("id_note", params[1]);
String result = profileSaveDescription.sendPostRequest(URL_LIST_VIEW_COMMENT,data);
return result;
}
protected void onPostExecute(String s) {
JSONArray dataJsonArr = null;
if(s.equals(null)){
Toast.makeText(mContext, "Internet Problem.", Toast.LENGTH_SHORT).show();
}else{
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
Toast.makeText(mContext, id_note, Toast.LENGTH_SHORT).show();
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String id_comment = c.getString("id_comment");
String uid = c.getString("userid");
String profile_name = c.getString("profile_name");
String profile_photo = c.getString("profile_photo");
String amount_of_like = c.getString("amount_of_like");
String amount_of_dislike = c.getString("amount_of_dislike");
String amount_of_comment = c.getString("amount_of_comment");
String content_comment = c.getString("content_comment");
String tgl_comment = c.getString("tgl_comment");
String parent_id = c.getString("parent_id");
CommentModel citem = new CommentModel();
citem.setId_note(id_note);
citem.setId_comment(id_comment);
citem.setUserid(uid);
citem.setProfileName(profile_name);
String pPhoto = c.isNull("profile_photo") ? null : c.getString("profile_photo");
citem.setProfile_photo(pPhoto);
citem.setJumlahLove(amount_of_like);
citem.setJumlahNix(amount_of_dislike);
citem.setJumlahComment(amount_of_comment);
citem.setContent_comment(content_comment);
citem.setTimeStamp(tgl_comment);
String prntID = c.isNull("parent_id") ? null : c.getString("parent_id");
citem.setParent_id(prntID);
citem.setLevel(level);
commentItems.add(citem);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
The problem is that I wanna add data from Asynctask and shown on another adapter. But how can i do that? please help. view from another adapter couldn't show with this code.

How to load GridView images with AsyncTask?

I have, below the following fragment that populates a gridview with Bitmaps from URLs. The problem is that I know it's very 'heavy' work and done on the UI Thread so it's slowing the fragment down when loading the grid.
I've read that an AsyncTask is needed to carry out the 'heavy' work in the background but I can't find anything that seems to fit with what I want.
public class HomeFragment extends Fragment {
protected static final String TAG = null;
public HomeFragment(){}
GridView gridView;
private GridViewAdapter gridAdapter;
private SQLiteHandler db;
private SwipeRefreshLayout swipeLayout;
private ProgressDialog pDialog;
GPSTracker gps;
String uid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new SQLiteHandler(getActivity());
gridAdapter = new GridViewAdapter(getActivity(), R.layout.grid_item_layout, getData());
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(true);
uid="1";
String email = db.getFromTable(getActivity(), "email", SQLiteHandler.TABLE_LOGIN, "WHERE _id="+uid);
String from_age = db.getFromTable(getActivity(), "from_age", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String to_age = db.getFromTable(getActivity(), "to_age", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String distance = db.getFromTable(getActivity(), "distance", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String unit = db.getFromTable(getActivity(), "unit", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String men = db.getFromTable(getActivity(), "men", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String women = db.getFromTable(getActivity(), "women", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
fetchUsers(email, from_age, to_age, distance, unit, men, women);
final View rootView = inflater.inflate(R.layout.fragment_home, container, false);
//getActivity().getActionBar().setTitle(R.string.home);
gridView = (GridView) rootView.findViewById(R.id.gridView);
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
ImageView imageView = (ImageView) v.findViewById(R.id.image);
//Create intent
Intent intent = new Intent(getActivity(), DetailsActivity.class);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
intent.putExtra("left", screenLocation[0]).
putExtra("top", screenLocation[1]).
putExtra("width", imageView.getWidth()).
putExtra("height", imageView.getHeight()).
putExtra("uid", item.getUid());
startActivity(intent);
}
});
swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
//my update process
Fragment currentFragment = getFragmentManager().findFragmentByTag("0");
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
}
});
return rootView;
}
// Prepare some dummy data for gridview
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
Cursor cursor = db.getAllRows("*", SQLiteHandler.TABLE_USERS, "");
//Query local DB to initialize settings screen
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
String uid = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_UID));
String name = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_NAME));
String dob = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_DOB));
//String gender = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_GENDER));
String photourl = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_PHOTOURL));
//String distance = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_DISTANCE));
String[] birthdayArr = dob.split("-");
int age = getAge(Integer.parseInt(birthdayArr[0]), Integer.parseInt(birthdayArr[1]), Integer.parseInt(birthdayArr[2]));
Bitmap bitmap = getBitmapFromURL(photourl);
imageItems.add(new ImageItem(bitmap, name+" - " + age, uid));
}
return imageItems;
}
public static Bitmap getBitmapFromURL(String src) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
public int getAge(int year, int month, int day) {
//int nowMonth = now.getMonth()+1;
int nowMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
//int nowYear = now.getYear()+1900;
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
int result = nowYear - year;
if (month > nowMonth) {
result--;
}
else if (month == nowMonth) {
int nowDay = Calendar.getInstance().get(Calendar.DATE);
if (day > nowDay) {
result--;
}
}
return result;
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
Log.i("hideDialog", "called");
if (pDialog.isShowing())
pDialog.dismiss();
}
public void fetchUsers(final String email, final String agefrom, final String ageto, final String distance, final String distanceUnit, final String interested_men, final String interested_wmen){
// Tag used to cancel the request
gps = new GPSTracker(getActivity());
String tag_string_req = "req_login";
pDialog.setMessage("Finding users ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Fetch Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("success");
JSONArray users = jObj.getJSONArray("users");
// Check for error node in json
if (success == 1) {
//Log.i("success", users+"");
if (users.length() == 0) {
Toast.makeText(getActivity(), "No users found! \nPlease try again soon.", Toast.LENGTH_LONG).show();
db.emptyTable(SQLiteHandler.TABLE_USERS);
}else{
db.emptyTable(SQLiteHandler.TABLE_USERS);
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String uid = user.getString("uid");
String name = user.getString("name");
String dob = user.getString("dob");
String gender = user.getString("gender");
String photourl = user.getString("photoUrl");
String distance = user.getString("distance");
String[][] userValues = {
{ SQLiteHandler.KEY_UID, uid},
{ SQLiteHandler.KEY_NAME, name},
{ SQLiteHandler.KEY_DOB, dob},
{ SQLiteHandler.KEY_GENDER, gender},
{ SQLiteHandler.KEY_PHOTOURL, photourl},
{ SQLiteHandler.KEY_DISTANCE, distance}
};
db.insert(SQLiteHandler.TABLE_USERS, userValues);
}
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
//$lat, $lng, $email, $agefrom, $ageto, $distance, $distanceUnit, $interested_men, $interested_wmen
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("lat", gps.getLatitude()+"");
params.put("lng", gps.getLongitude()+"");
params.put("email", email);
params.put("agefrom", agefrom);
params.put("ageto", ageto);
params.put("distance", distance);
params.put("distanceUnit", distanceUnit);
params.put("interested_men", interested_men+"");
params.put("interested_wmen", interested_wmen+"");
params.put("fetch", "y");
Log.i(TAG, params+"");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
How to load GridView images with AsyncTask?
Downloading images as Bitmap in HomeFragment. Use NetworkImageView from Volley in layout of GridView item for loading images in GridView.
Instead of storing Bitmap, store image url in ImageItem.
See following tutorial for more help:
Using NetworkImageView
AsynTask class
public class GridDataAsyncTask extends AsyncTask<GridDataAsyncTask.GridCallback, Void, GridAdapter> {
public interface GridCallback {
void onAdapterReady(GridAdapter adapter);
}
private GridCallback mCallBack;
#Override
protected GridAdapter doInBackground(GridCallback... callbacks) {
mCallBack = callbacks[0];
// TODO get data and create grid adapter
return adapter;
}
#Override
protected void onPostExecute(GridAdapter gridAdapter) {
super.onPostExecute(gridAdapter);
mCallBack.onAdapterReady(gridAdapter);
}
}
Activity
public class GridActivity extends AppCompatActivity implements GridDataAsyncTask.GridCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GridDataAsyncTask().execute(this);
}
#Override
public void onAdapterReady(GridAdapter adapter) {
// TODO set adapte to GridView
}
}
Best you can do is use http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html and make a lru cache and place the images in lru cache.
Example is given in android tutorials
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
As suggested by fractalwrench and Budius, Picasso was a very good and VERY easy solution to this. All I had to do was to pass the photo url instead of the entire BitMap through to my GridView adapter and use Picasso.with(context).load(item.getImage()).into(holder.image); to create the BitMap for the image view. This was so easy to implement and gives me exactly what I need. Thaks

listview does not updates

I am expirience wierd situation because my list view updates only once.
The idia is following, i want to download posts from web, which are located on page 3 and page 5 and show both of them on listview. However, List view shows posts only from page 3. MEanwhile, log shows that all poast are downloded and stored in addList.
So the problem - objects from second itteration are not shown in listview. Help me please to fix this issue.
public class MyAddActivateActivity extends ErrorActivity implements
AddActivateInterface {
// All static variables
// XML node keys
View footer;
public static final String KEY_ID = "not_id";
public static final String KEY_TITLE = "not_title";
Context context;
public static final String KEY_PHOTO = "not_photo";
public final static String KEY_PRICE = "not_price";
public final static String KEY_DATE = "not_date";
public final static String KEY_DATE_TILL = "not_date_till";
private int not_source = 3;
JSONObject test = null;
ListView list;
MyAddActivateAdapter adapter;
ArrayList<HashMap<String, String>> addList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.aadd_my_add_list_to_activate);
footer = getLayoutInflater().inflate(R.layout.loading_view, null);
addList = new ArrayList<HashMap<String, String>>();
ImageView back_button = (ImageView) findViewById(R.id.imageView3);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
Intent intent = this.getIntent();
// if (intent != null) {
// not_source = intent.getExtras().getInt("not_source");
// }
GAdds g = new GAdds();
g.execute(1, not_source);
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new MyAddActivateAdapter(this, addList);
list.addFooterView(footer);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String add_id = ((TextView) view
.findViewById(R.id.tv_my_add_id)).getText().toString();
add_id = add_id.substring(4);
Log.d("ADD_ID", add_id);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(),
AddToCheckActivity.class);
// sending data to new activity
UILApplication.advert.setId(add_id);
startActivity(i);
finish();
}
});
}
private void emptyAlertSender() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Ничего не найдено");
alertDialog.setMessage("У вас нет неактивных объявлений.");
alertDialog.setButton("на главную",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(intent);
finish();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
class GAdds extends AsyncTask<Integer, Void, JSONObject> {
#Override
protected JSONObject doInBackground(Integer... params) {
// addList.clear();
Log.d("backgraund", "backgraund");
UserFunctions u = new UserFunctions();
return u.getAdds(params[0] + "", params[1] + "");
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
Log.d("postexecute", "postexecute");
footer.setVisibility(View.GONE);
JSONArray tArr = null;
if (result != null) {
try {
tArr = result.getJSONArray("notices");
for (int i = 0; i < tArr.length(); i++) {
JSONObject a = null;
HashMap<String, String> map = new HashMap<String, String>();
a = (JSONObject) tArr.get(i);
if (a.getInt("not_status") == 0) {
int premium = a.getInt("not_premium");
int up = a.getInt("not_up");
if (premium == 1 && up == 1) {
map.put("status", R.drawable.vip + "");
} else if (premium == 1) {
map.put("status", R.drawable.prem + "");
} else if (premium != 1 && up == 1) {
map.put("status", R.drawable.up + "");
} else {
map.put("status", 0 + "");
}
map.put(KEY_ID, "ID: " + a.getString(KEY_ID));
map.put(KEY_TITLE, a.getString(KEY_TITLE));
map.put(KEY_PRICE,
"Цена: " + a.getString(KEY_PRICE) + " грн.");
map.put(KEY_PHOTO, a.getString(KEY_PHOTO));
map.put(KEY_DATE,
"Создано: " + a.getString(KEY_DATE));
map.put(KEY_DATE_TILL,
"Действительно до: "
+ a.getString(KEY_DATE_TILL));
map.put("check", "false");
Log.d("MyAddList", "map was populated");
}
if (map.size() > 0)
{
addList.add(map);
Log.d("MyAddList", "addlist was populated");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (UILApplication.login != 2) {
UILApplication.login = 3;
}
onCreateDialog(LOST_CONNECTION).show();
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
if (not_source == 3) {
not_source = 5;
GAdds task = new GAdds();
task.execute(1, 5);
}
if (not_source == 5) {
Log.d("ID", m.get(KEY_ID));
if (addList.size() == 0) {
emptyAlertSender();
}
}
}
}
#SuppressWarnings("unchecked")
public void addAct(View v) {
AddActivate aAct = new AddActivate(this);
aAct.execute(addList);
}
#Override
public void onAddActivate(JSONObject result) {
if (result != null) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
}
adapter
public class MyAddActivateAdapter extends BaseAdapter {
private List<Row> rows;
private ArrayList<HashMap<String, String>> data;
private Activity activity;
public MyAddActivateAdapter(Activity activity,
ArrayList<HashMap<String, String>> data) {
Log.d("mediaadapter", "listcreation: " + data.size());
rows = new ArrayList<Row>();// member variable
this.data = data;
this.activity = activity;
}
#Override
public int getViewTypeCount() {
return RowType.values().length;
}
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
I think the problem is you aren't calling the super class of notifyDataSetChanged(), maybe try
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
super.notifyDataSetChanged();
}

Categories

Resources