refresh json view is not work after update sdk 24 - android

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.

Related

how to remove simple adapter view on listview in runnable

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

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.

Layout not updating properly in Lollipop devices with fragments

I am facing a weird issue in my app. It is working perfectly in Android Kitkat Version but in Lollipop devices I am having a weird issue. Issue is that there is a fragment named help List and currently it is having no records therefore I just show a toast there that No Records found. But after this screen is opened when I open any other fragment in my app they all show no data at all, whether it is static or dynamic. Here are the screen shots to explain it more clearly
This is the original view of this screen
And after opening that fragment that is without data, It looks like this,
More over when I press the home button and then navigate back to app everything is visible again.
Here is the code for this fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<com.bluejamesbond.text.DocumentView
xmlns:ext="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ext:documentView_text="Doorstep Help is the most dynamic on demand service and helper application which shall make your life simple and easy. Get a servant at your door starting from Re 1/- per minute. Looking for someone to help you in shifting your house? Get a Moving Service Doorstep Helper starting at Re 3/- per minute. Want a servant for household chores like deep-cleaning, grocery buying? Get a Doorstep Household servant at your door for instant help. Need a helping hand to wash all your clothes? Get a Doorstep Laundry Helper to wash all your clothes. Your one stop solution for on-demand service and Help!"
ext:documentView_textSize="18sp"
ext:documentView_textAlignment="justified"/>
</LinearLayout>
And java file just have onCreateView and nothing else so I don't think that's necessary.
And this blank thing happens with every screen after that.
I have no clue what's causing this
I am also adding code for Help List fragment. It consists of two tabs
public class FragmentHelpList extends Fragment {
private ViewPager viewPager;
Context context;
public FragmentHelpList(){}
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_help_list, container, false);
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setAdapter(new TabFragmentPagerAdapter(getActivity().getSupportFragmentManager()));
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
return rootView;
}
And these are the two fragments added to view pager
First One
public static SlidingTab1Fragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SlidingTab1Fragment fragment = new SlidingTab1Fragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appSharedPreferences= AppSharedPreferences.getsharedprefInstance(getActivity()) ;
userid = appSharedPreferences.getUserId();
System.out.println("allhelpstabid : " + userid);
ALLHELPS_URL = Baseurl + "job_working.php?customer_id="+appSharedPreferences.getUserId();
new Loadalljobs().execute();
return inflater.inflate(R.layout.tab1, container, false);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
public void updatedisplay(ArrayList<HashMap<String, String>> container) {
TabOneCustomAdapter myCustomAdapter = new TabOneCustomAdapter(getActivity().getBaseContext(), R.layout.tab1_singleitem, container);
setListAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
Log.d("display execution", "");
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
// String value = (String) adapter.getItemAtPosition(position);
HashMap<String, String> map = AllHelpsList.get(position);
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
i.putExtra("name", map.get(TAG_NAME));
i.putExtra("address", map.get(TAG_ADDRESS));
i.putExtra("date", map.get(TAG_DATE));
startActivity(i);
}
});
}
class Loadalljobs extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading All Helps ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
ClearListAdapter clearadapter = new ClearListAdapter();
clearadapter.clearData();
setListAdapter(clearadapter);
}
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(ALLHELPS_URL, ServiceHandler.GET);
System.out.println("Response:" + jsonStr);
Log.d("All Helps JSON: ", "> " + jsonStr);
AllHelpsList.clear();
return jsonStr;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject=new JSONObject(s);
int status=jsonObject.getInt("status");
if (status==1) {
JSONArray jsonArray=jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String date = c.getString(TAG_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_DATE, date);
Log.d("kirti error", map + "");
AllHelpsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
updatedisplay(AllHelpsList);
// dismiss the dialog after getting all products
if (pDialog.isShowing())
pDialog.dismiss();
islListViewLoaded = false;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
System.out.println("Item clicked");
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
startActivity(i);
super.onListItemClick(l, v, position, id);
}
#Override
public void onStop() {
super.onStop();
if(pDialog!= null)
pDialog.dismiss();
}
And the second fragment
public static SlidingTab2Fragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SlidingTab2Fragment fragment = new SlidingTab2Fragment();
fragment.setArguments(args);
return fragment;
}
// Inflate the fragment layout we defined above for this fragment
// Set the associated text for the title
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appSharedPreferences= AppSharedPreferences.getsharedprefInstance(getActivity()) ;
prefs = this.getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
userid = appSharedPreferences.getUserId();
System.out.println("SCHEDULED_helpstabid : " + userid);
SCHEDULED_URL=Baseurl+"job_scheduled.php?cid="+userid;
System.out.println("Second tab url is: " +SCHEDULED_URL);
new LoadScheduled().execute();
return inflater.inflate(R.layout.tab2, container, false);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
public void updatedisplay(ArrayList<HashMap<String, String>> container) {
TabTwoCustomAdapter myCustomAdapter = new TabTwoCustomAdapter(getActivity().getBaseContext(), R.layout.tab2_singleitem, container);
setListAdapter(myCustomAdapter);
Log.d("display execution", "");
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
// String value = (String) adapter.getItemAtPosition(position);
HashMap<String, String> map = ScheduledHelpsList.get(position);
Intent i = new Intent(getActivity(), ActivityHelpDetailsScheduled.class);
i.putExtra("name", map.get(TAG_NAME));
i.putExtra("address", map.get(TAG_ADDRESS));
i.putExtra("time", map.get(TAG_TIME));
i.putExtra("date",map.get(TAG_DATE));
startActivity(i);
}
});
}
/**
* Background Async Task to Load all OUTBOX messages by making HTTP Request
*/
class LoadScheduled extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Scheduled Helps ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
ClearListAdapter clearadapter = new ClearListAdapter();
clearadapter.clearData();
setListAdapter(clearadapter);
}
/**
* getting Outbox JSON
*/
protected String doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(SCHEDULED_URL, ServiceHandler.GET);
Log.d("Scheduled JSON: ", "> " + jsonStr);
System.out.println("Response:" + jsonStr);
ScheduledHelpsList.clear();
try {
JSONArray ja = new JSONArray(jsonStr);
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String time = c.getString(TAG_TIME);
String jobtime = c.getString(TAG_DURATION);
String job_amount = c.getString(TAG_AMOUNT);
String date = c.getString(TAG_DATE);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_TIME, time);
map.put(TAG_DURATION, jobtime);
map.put(TAG_AMOUNT, job_amount);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
ScheduledHelpsList.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 products
updatedisplay(ScheduledHelpsList);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appSharedPreferences= AppSharedPreferences.getsharedprefInstance(getActivity()) ;
userid = appSharedPreferences.getUserId();
System.out.println("allhelpstabid : " + userid);
ALLHELPS_URL = Baseurl + "job_working.php?customer_id="+appSharedPreferences.getUserId();
new Loadalljobs().execute();
return inflater.inflate(R.layout.tab1, container, false);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
public void updatedisplay(ArrayList<HashMap<String, String>> container) {
TabOneCustomAdapter myCustomAdapter = new TabOneCustomAdapter(getActivity().getBaseContext(), R.layout.tab1_singleitem, container);
setListAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
Log.d("display execution", "");
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
// String value = (String) adapter.getItemAtPosition(position);
HashMap<String, String> map = AllHelpsList.get(position);
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
i.putExtra("name", map.get(TAG_NAME));
i.putExtra("address", map.get(TAG_ADDRESS));
i.putExtra("date", map.get(TAG_DATE));
startActivity(i);
}
});
}
class Loadalljobs extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading All Helps ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
ClearListAdapter clearadapter = new ClearListAdapter();
clearadapter.clearData();
setListAdapter(clearadapter);
}
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(ALLHELPS_URL, ServiceHandler.GET);
System.out.println("Response:" + jsonStr);
Log.d("All Helps JSON: ", "> " + jsonStr);
AllHelpsList.clear();
return jsonStr;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject=new JSONObject(s);
int status=jsonObject.getInt("status");
if (status==1) {
JSONArray jsonArray=jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String date = c.getString(TAG_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_DATE, date);
Log.d("kirti error", map + "");
AllHelpsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
updatedisplay(AllHelpsList);
// dismiss the dialog after getting all products
if (pDialog.isShowing())
pDialog.dismiss();
islListViewLoaded = false;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
System.out.println("Item clicked");
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
startActivity(i);
super.onListItemClick(l, v, position, id);
}
#Override
public void onStop() {
super.onStop();
if(pDialog!= null)
pDialog.dismiss();
}
And this the adapter class for view pager
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Current", "Scheduled"};
public TabFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position) {
case 0:
return SlidingTab1Fragment.newInstance(0);
case 1:
return SlidingTab2Fragment.newInstance(0);
default:
return fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}

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

Android window leak error in fragment

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

Categories

Resources