how to remove simple adapter view on listview in runnable - android

I have a listview that gets layout from adapter. The value was fetch using retrofit 2 and parse on the listview. This value updates on the API and want to implement the same feature. The problem is that it doubles value when runnable process. How can I make it work?
Here is the code:
class VehicleListFragment extends Fragment {
private ProgressDialog pDialog;
private ListView lv;
ListAdapter adapter;
final Handler handler = new Handler();
public static String baseUrl = "http://mark.journeytech.com.ph/mobile_api/";
public static NetworkAPI networkAPI;
public ArrayList<HashMap<String, String>> vehicle = new ArrayList<>();
String a = "";
ArrayList pna;
public interface NetworkAPI {
#POST("vehicle_details.php")
#Headers({"Content-Type:application/json; charset=UTF-8"})
Call<JsonElement> loginRequest(#Body VehicleRequestPojo body);
}
public static class VehicleRequestPojo {
String ucsi_num;
String client_table;
String markutype;
public VehicleRequestPojo(String ucsi_num, String client_table, String markutype) {
this.ucsi_num = ucsi_num;
this.client_table = client_table;
this.markutype = markutype;
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
searchItem.setVisible(false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainActivity csActivity;
csActivity = (MainActivity) getActivity();
csActivity.getSupportActionBar().setTitle("Vehicle List");
Runnable refresh = new Runnable() {
#Override
public void run() {
new GetVehicles().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_vehicle, container, false);
lv = (ListView) v.findViewById(R.id.list);
new GetVehicles().execute();
return v;
}
private class GetVehicles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/* // Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();*/
}
#Override
protected Void doInBackground(Void... arg0) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
networkAPI = retrofit.create(NetworkAPI.class);
VehicleRequestPojo loginRequest = new VehicleRequestPojo(MainActivity.ucsi_num, client_table, markutype);
Call<JsonElement> call = networkAPI.loginRequest(loginRequest);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
// success response
if (response.body().isJsonArray()) {
JsonArray objectWhichYouNeed = response.body().getAsJsonArray();
System.out.println(objectWhichYouNeed);
for (int i = 0; i < response.body().getAsJsonArray().size(); i++) {
JsonElement je = response.body().getAsJsonArray().get(i);
JsonObject jo = je.getAsJsonObject();
String plate_n = jo.get("plate_num").toString();
String plate_nString = plate_n;
plate_nString = plate_nString.replace("\"", "");
String plate_num = String.valueOf(plate_nString);
String gps_n = jo.get("gps_num").toString();
String gps_nString = gps_n;
gps_nString = gps_nString.replace("\"", "");
String gps_num = String.valueOf(gps_nString);
String locat = jo.get("location").toString();
String locatString = locat;
locatString = locatString.replace("\"", "");
String location = String.valueOf(locatString);
String da = jo.get("date").toString();
String daString = da;
daString = daString.replace("\"", "");
String date = String.valueOf(daString);
String ti = jo.get("time").toString();
String tiString = ti;
tiString = tiString.replace("\"", "");
String time = String.valueOf(tiString);
String lati = jo.get("lat").toString();
String latiString = lati;
latiString = latiString.replace("\"", "");
String lat = String.valueOf(latiString);
String longi = jo.get("lng").toString();
String longiString = longi;
longiString = longiString.replace("\"", "");
String lng = String.valueOf(longiString);
String en = jo.get("engine").toString();
String enString = en;
enString = enString.replace("\"", "");
String engine = String.valueOf(enString);
String re = jo.get("remarks").toString();
String reString = re;
reString = reString.replace("\"", "");
String remarks = String.valueOf(reString);
if (lat != null && !lat.equals("null") || (lng != null && !lng.equals("null"))) {
// tmp hash map for detail [single]
HashMap<String, String> details = new HashMap<>();
// adding each child node to HashMap key => value
details.put("plate_num", plate_num);
details.put("gps_num", gps_num);
details.put("location", location);
details.put("date", date);
details.put("time", time);
details.put("lat", lat);
details.put("lng", lng);
details.put("engine", engine);
details.put("remarks", remarks);
a = details.get("date");
// adding vehicle to vehicle list
vehicle.add(details);
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(getActivity(), vehicle,
R.layout.list_vehicle, new String[]{"plate_num",
"location", "date", "time", "lat", "lng", "engine",
"remarks"},
new int[]{R.id.plate_num, R.id.location, R.id.date, R.id.time, R.id.latitude, R.id.longitude,
R.id.engine, R.id.remarks});
lv.setAdapter(null);
lv.setAdapter(adapter);
// ((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
TextView plate_n = (TextView) v.findViewById(R.id.plate_num);
TextView dat = (TextView) v.findViewById(R.id.date);
TextView tim = (TextView) v.findViewById(R.id.time);
TextView loc = (TextView) v.findViewById(R.id.location);
TextView lat = (TextView) v.findViewById(R.id.latitude);
TextView lng = (TextView) v.findViewById(R.id.longitude);
TextView eng = (TextView) v.findViewById(R.id.engine);
TextView rem = (TextView) v.findViewById(R.id.remarks);
String plate_num = plate_n.getText().toString();
String date = dat.getText().toString();
String time = tim.getText().toString();
String location = loc.getText().toString();
String latitude = lat.getText().toString();
String longitude = lng.getText().toString();
String engine = eng.getText().toString();
String remarks = rem.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("plate_num", plate_num);
bundle.putString("date", date);
bundle.putString("time", time);
bundle.putString("location", location);
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
bundle.putString("engine", engine);
bundle.putString("remarks", remarks);
if((!latitude.equals("") && latitude != null) || (!longitude.equals("") && longitude != null) )
{
Fragment mFragment = new VehicleListMapFragment(getActivity(), getActivity());
getFragmentManager().beginTransaction().addToBackStack("sd").replace(R.id.mainLayout, mFragment).commit();
mFragment.setArguments(bundle);
} else {
Toast.makeText(getContext(), "Invalid Data.", Toast.LENGTH_LONG).show();
}
}
});
}
}
} else {
System.out.println("Not a JSONArray.");
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
// failure response
System.out.println(call.toString());
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* // Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();*/
}
}
}
Also could it be possible to use lv.invalidateViews();
lv.refreshDrawableState(); also could it be a .clear()? and refetch the api?

Try using this:
Runnable refresh = new Runnable() {
#Override
public void run() {
vehicle.clear(); // This will clear the old data from arraylist.
new GetVehicles().execute();
handler.postDelayed(this, 60 * 1000); //This will call after every 60 seconds.
}
};
handler.postDelayed(refresh, 60 * 1000); // This will be call only first time when the code is executed.
Also remove private from private ProgressDialog pDialog; so that it can be accessed by from another class GetVehicles.
Suggestion : Use RecylerView in place of listview
Hope this helps.

Declare your adapter, list variable in global. The idea is something like this
//Global
private ListView lv;
private ListAdapter adapter;
private ArrayList<HashMap<String, String>> vehicle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_vehicle, container, false);
lv = (ListView) v.findViewById(R.id.list);
vehicle = new ArrayList<>();
adapter = new SimpleAdapter(getContext(), vehicle,
R.layout.list_vehicle, new String[]{"plate_num",
"location", "date", "time", "lat", "lng", "engine",
"remarks",},
new int[]{R.id.plate_num, R.id.location, R.id.date, R.id.time, R.id.latitude, R.id.longitude,
R.id.engine, R.id.remarks});
new GetVehicles().execute();
return v;
}
//right after you get the new dataset from **GetVehicles** ,
//update vehicle list and call,
((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();

Related

How to get Arraylist<HashMap<String, String>> from AsyncTask through onPostExecute

I am trying to put storelist into StoreList variable. But it is not working.
doInBackground method is working perfectly but onPostexecute is not working.
Here is my code,
public class guest_main extends Fragment implements View.OnClickListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Location mCurrentLocation, mDestination;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String currentLon, currentLat;
private ListView mListView = null;
private ListViewAdapter mAdapter = null;
public ArrayList<HashMap<String, String>> StoreList;
class BackgroundWorker3 extends AsyncTask<String, Void,ArrayList<HashMap<String, String>>> {
Context context;
AlertDialog alertDialog;
BackgroundWorker3(Context ctx) {
context = ctx;
}
JSONArray store = null;
ArrayList<HashMap<String, String>> storeList;
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
String type = params[0];
storeList = new ArrayList<HashMap<String, String>>();
if (type.equals("Select2")) {
try {
String link = "...";
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String json;
while ((json = reader.readLine()) != null) {
sb.append(json);
}
String s = sb.toString().trim();
JSONObject jsonObject = new JSONObject(s);
store = jsonObject.getJSONArray("result");
for (int i = 0; i < store.length(); i++) {
JSONObject c = store.getJSONObject(i);
String name = c.getString("name");
String tel = c.getString("tel");
String latitude = c.getString("latitude");
String longitude = c.getString("longitude");
HashMap<String, String> stores = new HashMap<String, String>();
stores.put("name", name);
stores.put("tel", tel);
stores.put("latitude", latitude);
stores.put("longitude", longitude);
storeList.add(stores);
}
return storeList;
} catch (Exception e) {
return null;
}
}
return storeList;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guest_main, container, false);
StoreList = new ArrayList<HashMap<String, String>>();
getData();
buildGoogleApiClient();
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(this);
return v;
}
public void getData(){
BackgroundWorker3 bk2 = new BackgroundWorker3(getActivity());
bk2.execute("Select2");
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent = new Intent(getActivity().getApplicationContext(), gmenu_list.class);
startActivity(intent);
}
}
private class ViewHolder {
public ImageView mIcon;
public TextView mText;
public TextView mDate;
public TextView mDistance;
}
private class ListViewAdapter extends BaseAdapter {
private Context mContext = null;
private ArrayList<g_ListData> mListData = new ArrayList<g_ListData>();
public ListViewAdapter(Context mContext) {
super();
this.mContext = mContext;
}
#Override
public int getCount() {
return mListData.size();
}
#Override
public Object getItem(int position) {
return mListData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addItem(Drawable icon, String mTitle, String mDate, String mDistance){
g_ListData addInfo = null;
addInfo = new g_ListData();
addInfo.mIcon = icon;
addInfo.mTitle = mTitle;
addInfo.mDate = mDate;
addInfo.mDistance = mDistance;
mListData.add(addInfo);
}
public void remove(int position){
mListData.remove(position);
dataChange();
}
public void sort(){
Collections.sort(mListData, g_ListData.ALPHA_COMPARATOR);
dataChange();
}
public void dataChange(){
mAdapter.notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.gmenu_list_item, null);
holder.mIcon = (ImageView) convertView.findViewById(R.id.mImage);
holder.mText = (TextView) convertView.findViewById(R.id.mText);
holder.mDate = (TextView) convertView.findViewById(R.id.mDate);
holder.mDistance = (TextView)convertView.findViewById(R.id.mDistance);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
g_ListData mData = mListData.get(position);
if (mData.mIcon != null) {
holder.mIcon.setVisibility(View.VISIBLE);
holder.mIcon.setImageDrawable(mData.mIcon);
}else{
holder.mIcon.setVisibility(View.GONE);
}
holder.mText.setText(mData.mTitle);
holder.mDate.setText(mData.mDate);
holder.mDate.setText(mData.mDistance);
return convertView;
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100000); // Update location every second
try{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);}catch (SecurityException e){
}
if (mCurrentLocation != null) {
currentLat = String.valueOf(mCurrentLocation.getLatitude());
currentLon = String.valueOf(mCurrentLocation.getLongitude());
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
currentLat = String.valueOf(location.getLatitude());
currentLon = String.valueOf(location.getLongitude());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
}
Ok..The problem is in your case that the Async task runs on separate thread from UI thread So when you call BackgroundWorker3 in getData method then UI thread doesn't wait for Async task response(separte thread) and StoreList have null value. So you see StoreList doesn't have any value and in listView nothing will show.
Write this code in onPostExecute method not in onCreate..
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
}
Hope this will help you.

refresh json view is not work after update sdk 24

After switching to sdk24, I have a problem.
read json php application, but no longer updated. You must give closure forces her to reread.
before I used to refresh and update listfragment perfect. not now.
I give I add new information is added to the database, or you can delete, but the application does not update.
code json reader + inserd + deleted + refresh:
public class playlist_torrent extends ListFragment {
Main2Activity activity= (Main2Activity) getActivity();
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://vrt.ro/remote/index-torrent.php?token=";
// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_IMAGE = "image";
private static final String TAG_ADDRESS = "address";
String POPUP_LOGIN_TITLE;
String POPUP_LOGIN_TEXT;
String EMAIL_HINT;
String PASSWORD_HINT;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_playlist_torrent, container, false);
POPUP_LOGIN_TITLE=getActivity().getString(R.string.text_titlu_insert_stream_playlist);
POPUP_LOGIN_TEXT=getActivity().getString(R.string.text_completeaza_datele);
EMAIL_HINT=getActivity().getString(R.string.name_torrent);
PASSWORD_HINT=getActivity().getString(R.string.magnet_torrent);
final FloatingActionButton actionA = (FloatingActionButton) v.findViewById(R.id.action_a);
actionA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
actionA.setTitle(getActivity().getString(R.string.text_add_new_url));
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(POPUP_LOGIN_TITLE);
alert.setMessage(POPUP_LOGIN_TEXT);
// Set an EditText view to get user input
final EditText name = new EditText(getActivity());
name.setHint(EMAIL_HINT);
final EditText url_streaming = new EditText(getActivity());
url_streaming.setHint(PASSWORD_HINT);
LinearLayout layout = new LinearLayout(getActivity().getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(name);
layout.addView(url_streaming);
alert.setView(layout);
alert.setPositiveButton(getActivity().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (url_streaming.getText().toString().compareToIgnoreCase("") == 0) {
Snackbar.make(view, R.string.error_url_emty_playlist, Snackbar.LENGTH_LONG).show();
return;
}
new Thread() {
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
//HttpURLConnection.setInstanceFollowRedirects(false)
Bundle args = getArguments();
String token = args.getString("token");
String name_streaming = name.getText().toString();
String Url_streaming = url_streaming.getText().toString();
HttpURLConnection con = (HttpURLConnection) new URL("http://vrt.ro/remote/insert-torrent.php?token="+token+"&nume="+name_streaming+"&url="+Url_streaming).openConnection();
con.setRequestMethod("HEAD");
if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
// Reload current fragment
}
else{
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
alert.setNegativeButton(getActivity().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
});
final FloatingActionButton actionB = (FloatingActionButton) v.findViewById(R.id.action_b);
actionB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
actionB.setTitle(getActivity().getString(R.string.refresh_done));
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
}
});
return v;
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
// getting values from selected ListItem
final String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
final String id_stream = ((TextView) view.findViewById(R.id.id_streaming)).getText().toString();
// Starting single contact activity
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setTitle("Select");
// builder.setMessage("Lorem ipsum dolor ....");
builder.setItems(new CharSequence[]
{getString(R.string.play_video), getString(R.string.remove_video)},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
TorrentPlayerFragment fragment3 = new TorrentPlayerFragment();
fragment3.onDestroyView();
FragmentTransaction fragmentTransaction3 = getFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString("url", description);
fragment3.setArguments(args);
fragmentTransaction3.addToBackStack(null);
//getFragmentManager().popBackStack();
fragmentTransaction3.remove(fragment3);
fragmentTransaction3.replace(R.id.frame,fragment3);
fragmentTransaction3.commit();
//----
break;
case 1:
// Snack Bar
Snackbar bar = Snackbar.make(view, R.string.confirm_delete_playlist, Snackbar.LENGTH_LONG)
.setAction(R.string.yes, new View.OnClickListener() {
#Override
public void onClick(View v) {
// ---Control remote api---
new Thread() {
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
//HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL("http://vrt.ro/remote/delete-torrent.php?id="+id_stream).openConnection();
con.setRequestMethod("HEAD");
if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
//--refresh fragment
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
//Fin refresh fragment
// startActivity(getIntent());
// finish();
/* final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new onPreExecute().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000); */
}
else{
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}.start();
// ----fin Control remote api----
}
});
bar.show();
break;
}
}
});
builder.create().show();
}
});
// Calling async task to get json
new GetContacts().execute();
}
public static void createDirectory(File dir) throws IllegalStateException{
if (!dir.exists()){
if(!dir.mkdirs()){
throw new IllegalStateException(
"Check if you've added permissions in AndroidManifest.xml: \n" +
"<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/> \n"
);
}
}
}
/**
* Async task class to get json by making HTTP call
*
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Bundle bundle = getActivity().getIntent().getExtras();
//String token = bundle.getString("id");
Bundle args = getArguments();
String myString = args.getString("token");
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url+myString, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(myString);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String image = c.getString(TAG_IMAGE);
String address = c.getString(TAG_ADDRESS);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_IMAGE, image);
contact.put(TAG_ADDRESS, address);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[]{TAG_NAME, TAG_ID,
TAG_ADDRESS}, new int[]{R.id.name, R.id.id_streaming, R.id.mobile});
setListAdapter(adapter);
}
}
}
This is the code from refresh:
//--refresh fragment
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
//Fin refresh fragment
please help. thank you.
Edit:
if you leave an interval of a few minutes and refresh it goes. but only one time. as if the connection remains open and no longer responds.
Fixed this problem from changed ngix from apache2 and now is work fine.

Set notifyDataSetChanged() on Recyclerview adapter

I'm implementing an endless data loading for a RecyclerView. When software detects that last item is going to be shown, it downloads new items and call to the loadMoreData() function but new dataset is not showing.
When I called notifyDataSetChanged() so nothing to be happened.
I have only one solution that is refresh the view is to set again the adapter but problem is that the recyclerview returns to the first position then again recyclerview scrolled up from the first position to last position.
RecyclerViewActivity.java
RecyclerView rv;
DatabaseHelpr databaseHelpr;
RVAdapter adapter;
LocationFinder locationfinder;
Location currentLocation;
ArrayList<ServiceModel> childList, list;
private int MainService_ID, city_id;
String url2;
ActionBar actionBar;
JSONArray items = null;
Utility utility;
Double lat, longi;
LinearLayoutManager llm;
int counter=0;
ProgressBar progressBar;
private static final String TAG_ITEMS = "items";
private static final String TAG_LOCALITY = "Locality";
private static final String TAG_BUSINESS_ID = "Business_Id";
private static final String TAG_LONGITUDE = "Longitude";
private static final String TAG_BUSINESS_NAME = "Business_Name";
private static final String TAG_LATITUDE = "Latitude";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview_activity);
list = new ArrayList<>();
utility = new Utility(this);
llm = new LinearLayoutManager(this);
Bundle bundle=getIntent().getExtras();
MainService_ID=bundle.getInt("service_id");
String mainService_Name = bundle.getString("service_name");
city_id = bundle.getInt("city_id");
lat= bundle.getDouble("lat");
longi=bundle.getDouble("longi");
rv=(RecyclerView)findViewById(R.id.rv);
rv.setLayoutManager(llm);
actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(mainService_Name);
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=0, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
rv.addOnScrollListener(new EndlessRecyclerOnScrollListener(llm) {
#Override
public void onLoadMore(int current_page) {
// counter= counter+1;
loadMoreData();
}
});
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Toast.makeText(getApplicationContext(),""+statusCode,Toast.LENGTH_LONG).show();
}
});
}
private void loadMoreData() {
counter= counter+1;
//Here city_id = 8, lat = 18.552954, longi = 73.897200, counter=1, MainService_ID = 5
String url="https://servicedata2-dot-indiacomapi.appspot.com/_ah/api/servicedata/v1/ServiceData?city_id=";
url2 =url+city_id+"&lat="+lat+"&lng="+longi+"&roll="+counter+"&service_id="+MainService_ID;
AsyncHttpClient client = new AsyncHttpClient();
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
client.get(url2, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String s = new String(response);
try {
JSONObject jsonObj = new JSONObject(s);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_ITEMS);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String locality = c.getString(TAG_LOCALITY);
String business_Id = c.getString(TAG_BUSINESS_ID);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String business_Name = c.getString(TAG_BUSINESS_NAME);
locationfinder = new LocationFinder(RecyclerViewActivity.this);
// check if GPS enabled
if (locationfinder.canGetLocation()) {
double lat = locationfinder.getLatitude();
double longi = locationfinder.getLongitude();
currentLocation = new Location("");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(longi);
} else {
locationfinder.showSettingsAlert();
}
Location savedLocation = new Location("databaseLocation");
savedLocation.setLatitude(Double.parseDouble(latitude));
savedLocation.setLongitude(Double.parseDouble(longitude));
Double difference = currentLocation.distanceTo(savedLocation) * (0.001);
difference = Double.parseDouble(new DecimalFormat("##.##").format(difference));
String newDifference = String.valueOf(difference) + " km";
ServiceModel serviceModel = new ServiceModel(business_Id, business_Name, newDifference, locality);
list.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
//adapter = new RVAdapter(RecyclerViewActivity.this, list);
//rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});
Toast.makeText(this, "Net is present", Toast.LENGTH_SHORT).show();
}
}
RVAdapter.java
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>{
private final LayoutInflater mInflater;
List<ServiceModel> persons ;
private Context mContext;
public RVAdapter(Context context,List<ServiceModel> persons){
this.mInflater = LayoutInflater.from(context);
this.persons = new ArrayList<>(persons);
this.mContext = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
ServiceModel person = persons.get(i);
personViewHolder.businessName.setOnClickListener(clickListener);
personViewHolder.image_url.setOnClickListener(clickListenerImage);
personViewHolder.businessName.setTag(personViewHolder);
personViewHolder.difference.setTag(personViewHolder);
personViewHolder.business_id.setTag(personViewHolder);
personViewHolder.image_url.setTag(personViewHolder);
personViewHolder.locality.setTag(personViewHolder);
personViewHolder.businessName.setText(Html.fromHtml(person.getBusinessname()));
String firstLetter = String.valueOf(person.getBusinessname().charAt(0));
ColorGenerators generator = ColorGenerators.MATERIAL; // or use DEFAULT
int color = generator.getColor(person.getBusinessname());
TextDrawable drawable = TextDrawable.builder().buildRound(firstLetter, color); // radius in px
personViewHolder.image_url.setImageDrawable(drawable);
personViewHolder.difference.setText(Html.fromHtml(person.getNewDiffer()));
personViewHolder.locality.setText(Html.fromHtml(person.getLocality()));
personViewHolder.bind(person);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
View.OnClickListener clickListenerImage = new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonViewHolder holder = (PersonViewHolder) view.getTag();
int position = holder.getPosition();
ServiceModel person = persons.get(position);
String businessids = person.getBusinessid();
Intent intent = new Intent(mContext, BusinessInfoActivity.class);
intent.putExtra("businessids", businessids);
mContext.startActivity(intent);
}
};
#Override
public int getItemCount() {
return persons.size();
}
public void animateTo(List<ServiceModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ServiceModel> newModels) {
for (int i = persons.size() - 1; i >= 0; i--) {
final ServiceModel model = persons.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ServiceModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ServiceModel model = newModels.get(i);
if (!persons.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ServiceModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ServiceModel model = newModels.get(toPosition);
final int fromPosition = persons.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ServiceModel removeItem(int position) {
final ServiceModel model = persons.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ServiceModel model) {
persons.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ServiceModel model = persons.remove(fromPosition);
persons.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
protected CardView cv;
protected TextView businessName, difference, business_id, locality;
protected ImageView image_url;
public PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
businessName = (TextView)itemView.findViewById(R.id.business_name);
difference = (TextView)itemView.findViewById(R.id.txtDifferenece);
business_id = (TextView)itemView.findViewById(R.id.business_id);
image_url = (ImageView)itemView.findViewById(R.id.thumbnail);
locality= (TextView)itemView.findViewById(R.id.txtLocality);
}
public void bind(ServiceModel model) {
businessName.setText(model.getBusinessname());
}
}
}
Please help me, How to set notifyDataSetChanged() to the adapter. it is not working in my code. I already checked all answers which is posted on the stackoverflow.
you are setting the new list to the RecyclerView Adapter , set the list in the Adapter:
make a method setItems(list) in adapter and call it before notifyDataSetChanged() and in adapter do
this.persons = new ArrayList<>(persons);
in setItems
add this method in adapter:
public void setItems(List<ServiceModel> persons) {
this.persons = persons;
}
and call it before notifyDataSetChanged() like this:
adapter.setItems(list);
adapter.notifyDataSetChanged();
Issue is in these lines..
adapter = new RVAdapter(RecyclerViewActivity.this, list);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
You are initialising your adapter every time. No need to reinitialize it.
Just update your arraylist and invoking to adapter.notifyDataSetChanged(); will make it work.
Like #Beena mentioned, you are creating and setting new adapter ever time, in your success response.
One approach would be to create an adapter and set it to the recycler view only for the first time, and then onSuceess() of your api callback, call a method of your adapter.
In, them adapter method, just add that new data in your main arraylist and do notifyItemInserted() instead of notifyDataSetChanged, in this way you will also see the default adding animation of recyclerView.
Every time you fill your list call the method below:
if (adapter != null) // it works second time and later
adapter.notifyDataSetChanged();
else { // it works first time
adapter = new AdapterClass(context,list);
listView.setAdapter(adapter);
}
I solved this with added method in RVAdapter that call notifyDataSetChanged().
Simply in RVAdapter:
public void refreshList(){
notifyDataSetChanged();
}
and call this method in MainActivity when need:
rVAdapter.refreshList();

How do I convert an ordinary listview to a multi-select listview?

I have been having a problem lately, I have successfully created a listview in the FillList method that displays the items that i need. That is all well. The problem is how do I convert it to a multi-select checkbox like style so that when I select an item it will just be stored in an array for later use. Any insight is helpful.
Here is my PathfinderUpdate.java:
public class PathfinderUpdate extends Fragment {
ConnectionClass connectionClass;
EditText edtproname, edtprodesc;
Button btnadd,btnupdate,btndelete,btnrefresh;
ProgressBar pbbar;
ListView lstpro;
String pathid;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.update_pathfinder, container, false);
connectionClass = new ConnectionClass();
btnupdate = (Button) rootView.findViewById(R.id.btnupdate);
lstpro = (ListView) rootView.findViewById(R.id.lstproducts);
btnrefresh = (Button) rootView.findViewById(R.id.btnrefresh);
pathid = "";
FillList fillList = new FillList();
fillList.execute("");
btnrefresh.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
FillList Fill = new FillList();
Fill.execute("");
}
});
return rootView;
}
#Override
public void onResume(){
super.onResume();
FillList Fill = new FillList();
Fill.execute("");
}
public class FillList extends AsyncTask<String, String, String> {
String z = "";
List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute() {
//old pbbar
}
#Override
protected void onPostExecute(String r) {
String[] from = { "pathfinder_id", "pathfinder_name"};
int[] views = { R.id.lblproid, R.id.lblproname };
final SimpleAdapter ADA = new SimpleAdapter(getActivity(),
prolist, R.layout.lsttemplate, from,views);
lstpro.setAdapter(ADA);
lstpro.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
#SuppressWarnings("unchecked")
HashMap<String, Object> obj = (HashMap<String, Object>) ADA
.getItem(arg2);
pathid = (String) obj.get("pathfinder_id");
String idea_name = (String) obj.get("pathfinder_name");
String benefit_eqv = (String) obj.get("pathfinder_eqv");
String quickwin = (String) obj.get("pathfinder_quick");
String observe = (String) obj.get("pathfinder_obs");
String ideaId = (String) obj.get("pathfinder_idea_id");
String BenefitId = (String) obj.get("pathfinder_benefit");
String closure = (String) obj.get("pathfinder_closure");
Integer ideaIdMain = Integer.parseInt(ideaId);
Integer benefitIdMain = Integer.parseInt(BenefitId);
Integer pathfinderId = Integer.parseInt(pathid);
Double benefiteqv = Double.parseDouble(benefit_eqv);
Bundle bundle = new Bundle();
bundle.putString("id2", pathid);
bundle.putString("name", idea_name);
bundle.putDouble("eqv", benefiteqv);
bundle.putString("quick", quickwin);
bundle.putString("observation", observe);
bundle.putInt("idea_id", ideaIdMain);
bundle.putInt("benefit_id", benefitIdMain);
bundle.putString("closure", closure);
bundle.putInt("id", pathfinderId);
Intent updateMain = new Intent(getActivity(), PathfinderUpdateMain.class);
updateMain.putExtras(bundle);
startActivity(updateMain);
// qty.setText(qtys);
}
});
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from pathfinder ORDER BY pathfinder_id ASC";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("pathfinder_id", rs.getString("pathfinder_id"));
datanum.put("pathfinder_name", rs.getString("pathfinder_name"));
datanum.put("pathfinder_status", rs.getString("pathfinder_status"));
datanum.put("pathfinder_eqv", rs.getString("pathfinder_potential_eqv"));
datanum.put("pathfinder_obs", rs.getString("pathfinder_observation"));
datanum.put("pathfinder_quick", rs.getString("pathfinder_quickwin"));
datanum.put("pathfinder_idea_id", rs.getString("idea_id"));
datanum.put("pathfinder_benefit", rs.getString("benefit_id"));
datanum.put("pathfinder_closure", rs.getString("pathfinder_target_closure"));
prolist.add(datanum);
}
z = "Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
Log.e("MYAPP", "exception", ex);
}
return z;
}
}
}
Check this out i believe its much more close to the new design guidelines!!!
You can create your own adapter and customise list item.
here is a tutorial about list view.
for your questions. chapter 15 might be what you have been looking for.
http://www.vogella.com/tutorials/AndroidListView/article.html#listview_selection
hope this help !!!

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

Categories

Resources