ArrayList and HashMap confusion - java

public class PackageTabActivity extends ListActivity{
HashMap<String,Object> hm ;
ArrayList<HashMap<String,Object>> applistwithicon ;
private static final String APP_NAME = "app_name";
private static final String APP_ICON = "app_icon";
private static final String APP_SIZE = "app_size";
Method getPackageSizeInfo = null;
PackageManager pm ;
#Override
public void onCreate(Bundle icicle){
super.onCreate(icicle);
pm = getPackageManager();
applistwithicon = new ArrayList<HashMap<String,Object>>();
try {
getPackageSizeInfo = pm.getClass().getMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
new AppDetails().execute();
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
class AppDetails extends AsyncTask<Void, Void, ArrayList<HashMap<String , Object>>>
{
private long app_apk_size;
ProgressDialog mDialog;
#Override
public void onPreExecute()
{
mDialog = new ProgressDialog(PackageTabActivity.this);
mDialog.setCancelable(true);
mDialog.setMessage("Loading... " );
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setProgress(0);
mDialog.show();
}
#Override
protected ArrayList<HashMap<String, Object>> doInBackground(
Void... params) {
ArrayList<HashMap<String,Object>> app = new ArrayList<HashMap<String,Object>>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
long [] size = new long[packs.size()];
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
if(!isSystemPackage(p))
{
/* String package_name = p.applicationInfo.packageName;
appname[i] = p.applicationInfo.loadLabel(getPackageManager()).toString();
icon[i] = p.applicationInfo.loadIcon(getPackageManager());
size[i] = GetSize(package_name);
// Log.v("Test", "app_name = " +appname[i]+" app_size = "+size[i]);*/
app= GetSize(p);
}
}
//
return app;
}
private ArrayList<HashMap<String, Object>> GetSize(final PackageInfo pInfo)
{
try
{
getPackageSizeInfo.invoke(pm, pInfo.applicationInfo.packageName, new IPackageStatsObserver.Stub()
{
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException
{
app_apk_size= pStats.codeSize/1024;
if(app_apk_size!=0)
{
// If I uncomment-out the below commented-out lines, I get
// an incorrect result:
// hm = new HashMap<String, Object>();
// hm.put(APP_SIZE, app_apk_size);
// hm.put(APP_NAME, pInfo.applicationInfo.loadLabel(pm));
Log.v("apksize", "appsize = "+app_apk_size+"appname = "+pInfo.applicationInfo.loadLabel(pm));
// applistwithicon.add(hm);
}
}
});
}
catch(IllegalAccessException e) {}
catch(IllegalArgumentException r) {}
catch(InvocationTargetException w){}
return applistwithicon;
}
#Override
public void onPostExecute(ArrayList<HashMap<String, Object>> result)
{
mDialog.dismiss();
CustomAdapterList myAdapter = new CustomAdapterList(result,PackageTabActivity.this );
setListAdapter(myAdapter);
}
}
}
But if I uncomment-out the commented-out lines, the wrong result gets logged.
Does anyone know why?

I don't know what pInfo.applicationInfo.loadLabel(pm) does, but try to put the result in a var instead of calling method twice.

Related

DIsplay files downloaded from json on main screen?

I'm parsing a json to display a list of files a user can tap to download. I want to display the files the users have chosen to download on my main screen. this is the code when they download a file.
public final class Main extends Activity {
// Log tag for this class
private static final String TAG = "Main";
// Callback code for request of storage permission
final private int PERMISSIONS_REQUEST_STORAGE = 735;
// JSON Node Names
private static final String TAG_TYPE = "plans";
private static final String TAG_NAME = "name";
private static final String TAG_FILENAME = "filename";
private static final String TAG_URL = "url";
private static final String TAG_SHOULD_NOT_CACHE = "shouldNotCache";
// Files to delete
private static final ArrayList<String> filesToGetDeleted = new ArrayList<>();
// Strings displayed to the user
private static String offline;
private static String noPDF;
private static String localLoc;
private static String jsonURL;
// PDF Download
private static DownloadManager downloadManager;
private static long downloadID;
private static File file;
#SuppressLint("StaticFieldLeak")
private static SwipeRefreshLayout swipeRefreshLayout;
private final BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
final DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
final Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
final int columnIndex = cursor
.getColumnIndex(DownloadManager.COLUMN_STATUS);
final int status = cursor.getInt(columnIndex);
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
final Uri path = Uri.fromFile(file);
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
break;
case DownloadManager.STATUS_FAILED:
Utils.makeLongToast(Main.this,
getString(R.string.down_error));
break;
case DownloadManager.STATUS_PAUSED:
Utils.makeLongToast(Main.this,
getString(R.string.down_paused));
break;
case DownloadManager.STATUS_PENDING:
Utils.makeLongToast(Main.this,
getString(R.string.down_pending));
break;
case DownloadManager.STATUS_RUNNING:
Utils.makeLongToast(Main.this,
getString(R.string.down_running));
break;
}
}
}
};
// Data from JSON file
private ArrayList<HashMap<String, String>> downloadList = new ArrayList<>();
private static void checkDir() {
final File dir = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/");
if (!dir.exists()) dir.mkdir();
}
#Override
protected void onResume() {
super.onResume();
final IntentFilter intentFilter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(downloadReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Delete files which should not get cached.
for (String file : filesToGetDeleted) {
final File f = new File(file);
if (f.exists()) {
f.delete();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Utils.makeLongToast(Main.this, getString(R.string.permission_write_external_storage_success));
}
else {
final String permission_write_external_storage_failure = getString(R.string.permission_write_external_storage_failure);
final String app_title = getString(R.string.app_name);
final String message = String.format(permission_write_external_storage_failure, app_title);
Utils.makeLongToast(Main.this, message);
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(Main.this, permissions[0]);
if (!showRationale) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
break;
}
}
private void update(boolean force, boolean firstLoad) {
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout_main);
offline = getString(R.string.status_offline);
noPDF = getString(R.string.except_nopdf);
localLoc = getString(R.string.gen_loc);
jsonURL = getString(R.string.gen_json);
checkDir();
if (firstLoad) {
try {
downloadList = (ArrayList<HashMap<String, String>>) Utils.readObject(this, "downloadList");
if (downloadList != null) {
setList(true, true);
}
} catch (ClassNotFoundException | IOException e) {
Log.e(TAG, e.getMessage());
}
}
// Parse the JSON file of the plans from the URL
JSONParse j = new JSONParse();
j.force = force;
j.online = !Utils.isNoNetworkAvailable(this);
j.execute();
}
private void setList(final boolean downloadable, final boolean itemsAvailable) {
if (itemsAvailable) {
try {
Utils.writeObject(this, "downloadList", downloadList);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
final ListView list = (ListView) findViewById(R.id.listView_main);
final ListAdapter adapter = new SimpleAdapter(this, downloadList,
android.R.layout.simple_list_item_1, new String[]{TAG_NAME},
new int[]{android.R.id.text1});
list.setAdapter(adapter);
// React when user click on item in the list
if (itemsAvailable) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
int hasStoragePermission = ContextCompat.checkSelfPermission(Main.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Main.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_REQUEST_STORAGE);
return;
}
final Uri downloadUri = Uri.parse(downloadList.get(pos).get(TAG_URL));
final String title = downloadList.get(pos).get(TAG_NAME);
final String shouldNotCache = downloadList.get(pos).get(TAG_SHOULD_NOT_CACHE);
file = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/"
+ downloadList.get(pos).get(TAG_FILENAME) + ".pdf");
final Uri dst = Uri.fromFile(file);
if (file.exists()) {
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(dst, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
return;
}
if (downloadable && !Utils.isNoNetworkAvailable(Main.this)) {
// Download PDF
final Request request = new Request(downloadUri);
request.setTitle(title).setDestinationUri(dst);
downloadID = downloadManager.enqueue(request);
if (shouldNotCache.equals("true")) {
filesToGetDeleted.add(file.toString());
}
} else {
Utils.makeLongToast(Main.this, offline);
}
}
});
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
update(true, false);
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public boolean force = false;
public boolean online = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
#Override
protected JSONObject doInBackground(String... args) {
return JSONParser.getJSONFromUrl(Main.this, jsonURL, force, online);
}
#Override
protected void onPostExecute(JSONObject json) {
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
});
downloadList.clear();
if (json == null) {
String error = getString(R.string.except_json);
if (!online) {
error = offline;
}
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_NAME, error);
downloadList.add(map);
setList(false, false);
return;
}
try {
// Get JSON Array from URL
final JSONArray j_plans = json.getJSONArray(TAG_TYPE);
for (int i = 0; i < j_plans.length(); i++) {
final JSONObject c = j_plans.getJSONObject(i);
// Storing JSON item in a Variable
final String ver = c.getString(TAG_FILENAME);
final String name = c.getString(TAG_NAME);
final String api = c.getString(TAG_URL);
String shouldNotCache = "";
if (c.has(TAG_SHOULD_NOT_CACHE)) {
shouldNotCache = c.getString(TAG_SHOULD_NOT_CACHE);
}
// Adding value HashMap key => value
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_FILENAME, ver);
map.put(TAG_NAME, name);
map.put(TAG_URL, api);
map.put(TAG_SHOULD_NOT_CACHE, shouldNotCache);
downloadList.add(map);
setList(online, true);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}
SO how do I get the result of the above code and display it on main screen every time the user opens app

how to save list view state and get back to that state

i am getting data from MySQL database in JSON form and showing in custom list view.list view is very lengthy. now i want that when i click on button in main activity it redirect me to the list view to the same position where i have left.
thanks in advance.
public class ShowParahDetail extends AppCompatActivity {
ProgressDialog pd;
CustomAdapter c;
ArrayList<Ayah_textAR> ar_ayahAR;
ArrayList<Ayah_textTR> ar_ayah_TR;
JazzyListView lv;
String intent_parah_ID;
String intent_parahName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_parah_detail);
intent_parah_ID=getIntent().getExtras().getString("parahID");
intent_parahName=getIntent().getExtras().getString("parahName");
setTitle(intent_parahName);
pd = new ProgressDialog(ShowParahDetail.this, R.style.pdtheme);
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.show();
lv= (JazzyListView) findViewById(R.id.lvparahDetail);
ar_ayahAR = new ArrayList<>();
ar_ayah_TR = new ArrayList<>();
ShowDataAR();
ShowTranslationUR();
}
private void ShowTranslationUR() {
new Thread(new Runnable() {
#Override
public void run() {
String RecievedString = "";
HashMap<String, String> params = new HashMap<String, String>();
params.put("parahid", intent_parah_ID);
Network network = new Network("showParahTranslationUR.php", params);
try {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
RecievedString = network.ToRecieveDataFromWeb();
JsonParsing jsonparsing = new JsonParsing(RecievedString);
ArrayList<HashMap<String, String>> convertedarraydata = jsonparsing.ParsejsonArray(RecievedString);
for (int i = 0; i < convertedarraydata.size(); i++) {
HashMap<String, String> positionHashmap;
positionHashmap = convertedarraydata.get(i);
String str_ayahText = positionHashmap.get("verseText");
String str_verseID = positionHashmap.get("verse_id");
String str_surahID = positionHashmap.get("surah_id");
Ayah_textTR ayahTR = new Ayah_textTR();
ayahTR.ayah_textTR = str_ayahText;
ayahTR.verse_id = str_verseID;
ayahTR.surah_id = str_surahID;
ar_ayah_TR.add(ayahTR);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void ShowDataAR() {
new Thread(new Runnable() {
#Override
public void run() {
String RecievedString = "";
HashMap<String, String> params = new HashMap<String, String>();
params.put("parahid", intent_parah_ID);
Network network = new Network("showParahDetails.php", params);
try {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
RecievedString = network.ToRecieveDataFromWeb();
JsonParsing jsonparsing = new JsonParsing(RecievedString);
ArrayList<HashMap<String, String>> convertedarraydata = jsonparsing.ParsejsonArray(RecievedString);
for (int i = 0; i < convertedarraydata.size(); i++) {
HashMap<String, String> positionHashmap;
positionHashmap = convertedarraydata.get(i);
String str_ayahID = positionHashmap.get("verse_id");
String str_ayahText = positionHashmap.get("verseText");
Ayah_textAR ayahText = new Ayah_textAR();
ayahText.ayah_id = str_ayahID;
ayahText.ayah_textAR = str_ayahText;
ar_ayahAR.add(ayahText);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ShowParahDetail.this == null)
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Parcelable state = lv.onSaveInstanceState();
lv.onRestoreInstanceState(state);
c = new CustomAdapter(ShowParahDetail.this, R.layout.cstm_parah, R.id.tv_parahNAME, ar_ayahAR);
lv.setAdapter(c);
if(pd!=null){
pd.dismiss();
pd = null;
}
}
});
}
}
}).start();
}
class CustomAdapter extends ArrayAdapter<Ayah_textAR> {
public CustomAdapter(Context context, int resource, int textViewResourceId, ArrayList<Ayah_textAR> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.cstm_ayah, parent, false);
final TextView tv_ayah_text = (TextView) v.findViewById(R.id.tv_ayahText);
final TextView tv_ayahTR = (TextView) v.findViewById(R.id.tv_ayahTR);
try {
Ayah_textAR ayah = ar_ayahAR.get(position);
tv_ayah_text.setText(ayah.ayah_id + " : " + ayah.ayah_textAR);
Ayah_textTR parahTR = ar_ayah_TR.get(position);
tv_ayahTR.setText(parahTR.ayah_textTR);
}catch (Exception e){
notifyDataSetChanged();
}
});
return v;
}
}
public class Ayah_textAR {
String ayah_id;
String ayah_textAR;
}
public class Ayah_textTR {
String verse_id;
String ayah_textTR;
String surah_id;
}
#Override
public void onDestroy() {
super.onDestroy();
if (pd != null) {
pd.dismiss();
pd = null;
}
}
}
You have three activities, A,B and C. Start your activity B with Intent. And also start your activity C with intent. Then, if you start your activity A and wish to save data which are exist in C, then start your activity A with intent. And don't finish your activity C. And if you want to resume activity C, just call onBackPressed() from your activity A. Don't forget finishing your activity A. For this call onFinish().

Marker.remove() is not working in google map, I want to remove the marker outside the radius?

in my application I am using list of markers but when I tried to remove the marker its not removing the marker.
Marker.remove() is not working in google map, I want to remove the marker outside the radius.
Please help
My source code is given below :
public class MapFragment extends Fragment implements LocationListener
{
private static final String LOG_TAG = "ExampleApp";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private static final String SERVICE_URL = "http://203.187.247.199/primevts/vtsservice.svc/data";
JSONObject json = null;
JSONObject jsonobject = null;
JSONObject jsonobject1 =null;
JSONObject jsonobject2 =null;
JSONObject ja = null;
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
JSONArray jsonarray2 = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist1;
ArrayList<HashMap<String, String>> arraylist11;
ArrayList<HashMap<String, String>> arraylist12;
ArrayList<HashMap<String, String>> arraylist;
List<Marker> markerList = new ArrayList<Marker>();
private Timer timer;
static String LONG = "Long";
static String LAT = "Lat";
ArrayList<String> ct;
public double latt = 0;
public double lng = 0;
public ArrayList<Integer> dLat;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Handler handler;
public Marker marker;
Marker stop = null;
String RegistrationNo="";
LatLng destination,source,destination2,center;
Polyline polylin;
String ime1,destname,routeid;
GMapV2GetRouteDirection md;
private HashMap<String, Marker> mMarkers = new HashMap<>();
int value=1;
// LatLngBounds values ;
double latitude, longitude,destlat,destlong,sourcelat,sourcelong,destlat2,destlong2;
String ime,reg,regi;
Geocoder geocoder;
List<Address> addresses;
CircleOptions circleOptions;
Circle circle;
// LatLng val;
float[] distance = new float[2];
static HashMap<String, String> datas;
static HashMap<String, String> map;
String[] latlngvalues;
// LocationManager locman;
Context context;
View rootView;
ImageView imageView1;
TextView Address;
public MapFragment() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
Address=(TextView)rootView.findViewById(R.id.adressText);
//imageView1=(ImageView) rootView.findViewById(R.id.imageView1);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
new DestinationJSON().execute();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoContents(Marker marker) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
View v = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);
TextView markerLabel = (TextView)v.findViewById(R.id.ime);
TextView destiname=(TextView)v.findViewById(R.id.destname);
TextView route=(TextView)v.findViewById(R.id.routeid);
markerLabel.setText(regi);
destiname.setText(destname);
route.setText(routeid);
Log.e("imeid", ""+ime1);
return v;
}
});
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
//Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(final CameraPosition arg0) {
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng= mMap.getCameraPosition().target;
double lat = latLng.latitude;
double lng = latLng.longitude;
Log.e("lati",""+lat);
Log.e("longi",""+lng);
Log.d("TAG", latLng.toString());
//mMap.clear();
if(circle!=null){
circle.remove();
//mMap.clear();
}
circleOptions = new CircleOptions();
circleOptions.center(latLng);
//circleOptions.fillColor(Color.TRANSPARENT);
circleOptions.radius(10000);
circleOptions.strokeColor(Color.TRANSPARENT);
circle = mMap.addCircle(circleOptions);
Log.e("",""+circle);
center = mMap.getCameraPosition().target;
new GetLocationAsync(center.latitude, center.longitude).execute();
/* geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
Log.e("address",""+address);
String city = addresses.get(0).getLocality();
Log.e("city",""+city);
String state = addresses.get(0).getAdminArea();
Log.e("state",""+state);
String country = addresses.get(0).getCountryName();
Log.e("contry",""+country);
String postalCode = addresses.get(0).getPostalCode();
Log.e("postalcode",""+postalCode);
String knownName = addresses.get(0).getFeatureName();
Log.e("knownName",""+knownName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Here 1 represent max location result to returned, by documents it recommended 1 to 5
//Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
}*/
}
});
}
});
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub
if(stop!=null){
mMap.clear();
}
regi=arg0.getTitle().toString();
Log.e("aaa", ""+regi);
JSONPost jsonpost= new JSONPost();
ja=jsonpost.datewise(regi);
Log.e("Home_details..", "" + ja);
// new DownloadJSON2().execute();
try
{
arraylist11 = new ArrayList<HashMap<String, String>>();
arraylist12 = new ArrayList<HashMap<String, String>>();
jsonarray = ja.getJSONArray("Routeinbus");
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
Log.e("G>>>>>>>>>>>", "" + json);
// Retrive JSON Objects
// map.put("flatID", jsonobject.getString("flatID"));
map.put("FromLat", json.getString("FromLat"));
map.put("FromLong", json.getString("FromLong"));
sourcelat = json.getDouble("FromLat");
sourcelong=json.getDouble("FromLong");
source=new LatLng(sourcelat, sourcelong);
map.put("Fromaddress", json.getString("Fromaddress"));
map.put("ToLat", json.getString("ToLat"));
map.put("ToLong", json.getString("ToLong"));
routeid=json.getString("RouteID");
destname=json.getString("Toaddress");
destlat2=json.getDouble("ToLat");
destlong2=json.getDouble("ToLong");
destination2=new LatLng(destlat2, destlong2);
jsonarray1 = json.getJSONArray("Routes");
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonarray1);
for (int j = 0; j <jsonarray1.length(); j++) {
jsonobject1 = jsonarray1.getJSONObject(j);
jsonarray2=jsonobject1.getJSONArray("stages");
Log.d("jsonarray2", "" + jsonarray2);
for(int k=0;k<jsonarray2.length();k++)
{
jsonobject2 =jsonarray2.getJSONObject(k);
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Lat",jsonobject2.getString("Lat"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Lat"));
map1.put("Long",jsonobject2.getString("Long"));
map1.put("StopName", jsonobject2.getString("StopName"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Long"));
// map1.put("LiveLongitude",jsonobject1.getString("LiveLongitude"));
// Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject1.getString("LiveLongitude"));
arraylist12.add(map1);
Log.e("arraylist12", ""+arraylist12);
/*if(polylin!=null){
polylin.remove();
}
if(marker!=null){
marker.remove();
}
md = new GMapV2GetRouteDirection();
Document doc = md.getDocument(source, destination2,
GMapV2GetRouteDirection.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.CYAN);
for (int a = 0; a < directionPoint.size(); a++) {
rectLine.add(directionPoint.get(a));
}
polylin = mMap.addPolyline(rectLine);*/
//marker=mMap.addMarker(new MarkerOptions().position(destination2).icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)));
for (int m = 0; m < arraylist12.size(); m++)
{
final LatLng stopposition = new LatLng(Double .parseDouble(arraylist12.get(m).get("Lat")),Double.parseDouble(arraylist12.get(m).get("Long")));
Log.e("position", ""+stopposition);
String stopname = arraylist12.get(m).get("StopName");
Log.e("markcheck",""+stopname);
final MarkerOptions options = new MarkerOptions().position(stopposition).icon(BitmapDescriptorFactory .fromResource(R.drawable.greenbus)).title(stopname);
//mMap.addMarker(options);
stop=mMap.addMarker(options);
}
}
}
arraylist11.add(map);
Log.e("arraylist11",""+arraylist11);
}
}catch (Exception e) {
String result = "Error";
}
return false;
}
});
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
// mMap.clear();
/* if(marker!=null){
marker.remove();
}*/
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
Double lati=Double.parseDouble(arraylist1.get(i).get("Latitude"));
Double longi=Double.parseDouble(arraylist1.get(i).get("Longitude"));
// Log.e("doublelati",""+lati);
// Log.e("doublelongi",""+longi);
ime1 = arraylist1.get(i).get("RegistrationNo");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)));
// mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
//marker.showInfoWindow();
try
{
Location.distanceBetween(lati,longi,circle.getCenter().latitude, circle.getCenter().longitude, distance);
if ( distance[0] <= circle.getRadius())
{
marker=mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.whitebus)).anchor(0.0f, 1.0f).title(ime1));
// Inside The Circle
}
else
{
//Toast.makeText(getActivity(), "currently no buses available at this location", Toast.LENGTH_SHORT).show();
/* if(marker!=null)
{
marker.remove();
}*/
// Outside The Circle
marker.remove();
}
}catch (Exception e){
}
//options.title(ime1);
builder.include(position);
} if(value==1){
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLnglatLng));
// mMap.setOnMapClickListener(null);
//mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(10) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
value++;
}
}
});
}
}
}
private class DestinationJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl("http://beta.json-generator.com/api/json/get/NJMZPNSi");
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
destlat = json.getDouble("Latitude");
destlong = json.getDouble("Longitude");
ime = json.getString("IME");
//reg=json.getString("RegistrationNo");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
//map.put("RegistrationNo", json.getString("RegistrationNo"));
map.put("IME", json.getString("IME"));
destination=new LatLng(destlat, destlong); }
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try { geocoder = new Geocoder(getActivity(), Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (Exception e) {
// TODO: handle exception
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
reg=json.getString("RegistrationNo");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("RegistrationNo", json.getString("RegistrationNo"));
map.put("IME", json.getString("IME"));
arraylist1.add(map);
//Log.e("arraylist1", ""+arraylist1);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
} {
}
}

using shared preferences to store arraylist, null object returned

I have an ArrayList listwriter which I populate using this AsyncTask.
class LoadAllGamesWhenNull extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// *//**
// * getting All products from url
// *//*
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_games);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", name));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
if (status.equals("open")) {
useroutcomes.put(id.substring(0, 10), Teams);
}
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, "","",Teams));
Log.d("map", map.toString());
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
String ultparam = "";
int i = 0;
for (HashMap<String, String> a : bet) {
String teams = a.get(TAG_TEAMS);
Map<String, String> listofteams = new HashMap<>();
Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
Matcher m = p.matcher(teams);
Log.d("printa", teams);
while (m.find()) {
listofteams.put(m.group(1), m.group(2));
}
Log.d("dede", listofteams.toString());
String c = "";
for (String x : listofteams.keySet()) {
String b = x + ",";
c = c + b;
}
Log.d("C", c);
c = c.substring(0, c.lastIndexOf(","));
// Log.d("Cproc", c);
ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
passtocheck.add(listofteams);
allopens.put(Integer.toString(i), a.get(TAG_STATUS));
i++;
i++;
}
ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
Log.d("ULTPARAM", ultparam);
CheckBet checker = new CheckBet(ultparam, passtocheck);
HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
Log.d("Finaloutcomes", finaloutcomes.toString());
finaloutcomess = finaloutcomes.toString();
for (String x : finaloutcomes.keySet()) {
for (int p = 0; p < listwriter.size(); p++) {
if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
for (int r = 0; r < finaloutcomearray.length; r++) {
Log.d("finaloutcomearray", finaloutcomearray[r]);
Log.d("useroutcomearray", useroutcomearray[r]);
String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
String[] induseroutcomearray = useroutcomearray[r].split("\\)");
for (int d = 0; d < indfinaloutcomesarray.length; d++) {
Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
Log.d("induseroutcome", induseroutcomearray[d]);
finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));
}
}
Log.d("FINALHASHfinal", finalhash.toString());
listwriter.get(p).setActualselections(finalhash.toString());
listwriter.get(p).setUserselections(userhash.toString());
Log.d("USERHASHfinal", userhash.toString());
listwriter.get(p).setStatus("won");
for (String id : userhash.keySet()) {
if (finalhash.get(id).equals("null")) {
listwriter.get(p).setStatus("open");
} else if (!(finalhash.get(id).equals(userhash.get(id)))) {
listwriter.get(p).setStatus("lost");
break;
}
}
finalhash.clear();
userhash.clear();
currentitem = listwriter.get(p);
if (currentitem.getStatus().equals("open")) {
} else {
if (currentitem.getStatus().equals("won")) {
valuechange = valuechange + currentitem.getReturns() - (currentitem.getStake());
}
String c = currentitem.getId() + "," + currentitem.getStatus() + "//";
updateparam = updateparam + c;
Log.d("UPDATEPARAM1", updateparam);
}
}
}
}
Log.d("Listwriterbefore",listwriter.toString());
session.setListwriter(listwriter);
new UpdateBetStatus().execute();
Intent g = new Intent(loadingscreen.this,DisplayAllBets.class);
startActivity(g);
finish();
}}
This is done on my loadscreen Activity and I want to set the listwriter to my SharedPreferences so that I can use it in another Activity. This is my session manager class. The logging in the AsyncTask shows me that the listwriter gets populated correctly. However, when I call on the getlistwriter in my other class I receive an empty ArrayList. I can't see where the error is.
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "AndroidHiveLogin";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
public static final String USERNAME = "username";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public ArrayList<BetDisplayer> getListwriter() {
return listwriter;
}
public void setListwriter(ArrayList<BetDisplayer> listwriter) {
this.listwriter = listwriter;
}
public void setLogin(boolean isLoggedIn, String username) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.putString(USERNAME, username);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(USERNAME, pref.getString(USERNAME, null));
// return user
return user;
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}}
Code used to retrieve listwriter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
menu menu = (menu)
getFragmentManager().findFragmentById(R.id.fragment);
menu.updateinfo(getName());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.USERNAME);
listwriter = session.getListwriter();
AppController class :
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
private ArrayList<HashMap<String, String>> gamesList;
public ArrayList<HashMap<String, String>> getGamesList() {
return gamesList;
}
public void setGamesList(ArrayList<HashMap<String, String>> gamesList) {
this.gamesList = gamesList;
}
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
In your SessionManager you're not saving your List into SharedPrefs. You should do something like this:
public static final String MY_LIST = "my_list";
private static final Type LIST_TYPE = new TypeToken<List<BetDisplayer>>() {}.getType();
to save:
public void setListwriter(ArrayList<BetDisplayer> listwriter) {
this.listwriter = new ArrayList<BetDisplayer>(listwriter);
mPrefs.edit()
.putString(MY_LIST, new Gson().toJson(listwriter));
.commit();
}
to load:
public ArrayList<BetDisplayer> getListwriter() {
if (listwriter == null) {
listwriter = new Gson().fromJson(mPrefs.getString(MY_LIST, null), LIST_TYPE);
if(listwriter == null){
listwriter = new ArrayList<BetDisplayer>();
}
}
return listwriter;
}
Your BetDisplayer must implements Serializable.
See here: Android array to Sharedpreferences with Gson
To use Gson just add this dependency: 'com.google.code.gson:gson:2.3.1' or download the .jar
UPDATE:
Create a Singleton that holds one reference only to your SharedPreferences editor, it's just a will guess but I think you are using different context to get your editor and that could be the problem (UPDATE 2: it's not, check here, but the Singleton approach it's a plus):
private static SharedPreferences mPrefs;
private static SessionManager sInstance = null;
protected SessionManager() {
mPrefs = AppController.getInstance().getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static SessionManager getInstance() {
if (sInstance == null) {
sInstance = new SessionManager();
}
return sInstance;
}
And when you need to use SharedPreferences use SessionManager().getInstance().someMethod();

My Simple Adapter Wont Populate my listview

I am creating an android application and my code will loop through the json data and if finds a match to the string that i have placed in ( in this case "Guil Hernandez") , then it will add that name to an array list of hashmaps. I then populate my listview with a simple adapter. Everything is working properly, but my listview will not appear. Am i doing this sorting "algorithm" wrong? Also if you know of a better way to do the sorting to find a match..PLEASE LET ME KNOW. i am still new to this. Thank you in advance!
private void handleResponse() {
if (mNameDataJson == null ) {
// TODO: handle error
} else {
try {
JSONArray namesArray = mNameDataJson.getJSONArray("posts");
ArrayList<HashMap<String , String> > nameArrayList = new ArrayList<HashMap<String, String>>();
for ( int i = 0 ; i < namesArray.length() ; i++ ) {
JSONObject unit = namesArray.getJSONObject(i);
String name = unit.getString(KEY_NAME);
name = Html.fromHtml(name).toString();
String title = unit.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
HashMap<String , String> hashMap = new HashMap<String, String>();
if (name == "Guil Hernandez") {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
} else {
Log.v(TAG , "no match");
}
}
String[] keys = { KEY_NAME , KEY_TITLE };
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MyActivity.this , nameArrayList , android.R.layout.simple_list_item_2,
keys , ids);
setListAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
full code here :
public class MyActivity extends ListActivity {
private JSONObject mNameDataJson;
private final String TAG = MyActivity.class.getSimpleName();
private final String KEY_NAME = "author";
private final String KEY_TITLE = "title";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
GetNameData getNameData = new GetNameData();
getNameData.execute();
}
private void handleResponse() {
if (mNameDataJson == null ) {
// TODO: handle error
} else {
try {
JSONArray namesArray = mNameDataJson.getJSONArray("posts");
ArrayList<HashMap<String , String> > nameArrayList = new ArrayList<HashMap<String, String>>();
for ( int i = 0 ; i < namesArray.length() ; i++ ) {
JSONObject unit = namesArray.getJSONObject(i);
String name = unit.getString(KEY_NAME);
name = Html.fromHtml(name).toString();
String title = unit.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
HashMap<String , String> hashMap = new HashMap<String, String>();
if (name == "Guil Hernandez") {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
} else {
Log.v(TAG , "no match");
}
}
String[] keys = { KEY_NAME , KEY_TITLE };
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MyActivity.this , nameArrayList , android.R.layout.simple_list_item_2,
keys , ids);
setListAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetNameData extends AsyncTask<Object, Void, JSONObject> {
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... objects) {
String nameUrl = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(nameUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
String responseString = response.body().string();
Log.v(TAG , responseString);
try {
jsonResponse = new JSONObject(responseString);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
mNameDataJson = jsonObject;
handleResponse();
}
}
}
If you want to compare strings use equals(). Like this:
if (name.equals("Guil Hernandez")) {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
}

Categories

Resources