Skip to content

Instantly share code, notes, and snippets.

@scumola
Created June 5, 2013 20:06
Show Gist options
  • Select an option

  • Save scumola/5716862 to your computer and use it in GitHub Desktop.

Select an option

Save scumola/5716862 to your computer and use it in GitHub Desktop.
ListView not updating
package com.badcheese.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.util.Log;
import com.badcheese.androidhive.JSONParser;
import com.badcheese.androidhive.R;
import com.badcheese.androidhive.SingleMenuItemActivity;
import com.badcheese.androidhive.library.DatabaseHandler;
import com.badcheese.androidhive.library.UserFunctions;
public class DashboardActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView altitudeField;
private TextView accuracyField;
private ListView lv;
private LocationManager locationManager;
private String provider;
UserFunctions userFunctions;
Button btnLogout;
Button newnote;
Button refresh;
Button reload;
Location location;
ListAdapter adapter;
private static String url = "http://badcheese.com/~steve/geonote/places.php";
// JSON Node names
private static final String TAG_LOCATIONS = "locations";
private static final String TAG_TITLE = "title";
private static final String TAG_NOTE = "note";
private static final String TAG_SUMMARY = "summary";
private static final String TAG_ALT = "alt";
private static final String TAG_LAT = "lat";
private static final String TAG_LON = "lon";
private static final String TAG_DISTANCE = "distance";
private static final String TAG_CREATED = "created";
private static final String TAG_EXPIRES = "expires";
private static final String TAG_ID = "id";
// flag for GPS and network status
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
// contacts JSONArray
JSONArray locations = null;
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
/*
newnote = (Button) findViewById(R.id.btnLogout);
newnote.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
*/
btnLogout = (Button) findViewById(R.id.new_note_btn);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent newnote = new Intent(getApplicationContext(), NewNoteActivity.class);
startActivity(newnote);
}
});
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
altitudeField = (TextView) findViewById(R.id.TextView06);
accuracyField = (TextView) findViewById(R.id.TextView08);
refresh = (Button) findViewById(R.id.refresh_btn);
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
contactList = db.getNotes(latituteField.getText().toString(),longitudeField.getText().toString());
// System.out.println("ContactList: " + contactList);
lv = (ListView) findViewById(R.id.list_view);
ListAdapter adp = lv.getAdapter();
((BaseAdapter) adp).notifyDataSetChanged();
System.out.println("adapter: " + adapter + " told that there is new data");
// lv.destroyDrawingCache();
// lv.setVisibility(ListView.INVISIBLE);
// lv.setVisibility(ListView.VISIBLE);
// lv.invalidateViews();
// lv.scrollBy(0, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
});
reload = (Button) findViewById(R.id.reload_btn);
reload.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Creating JSON Parser instance
JSONParser jsonParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("lat", latituteField.getText().toString()));
params.add(new BasicNameValuePair("lon", longitudeField.getText().toString()));
// getting JSON string from URL
JSONObject json = jsonParser.getJSONFromUrl(url, params);
// Log.e("JSON", json.toString());
try {
// Getting Array of Contacts
locations = json.getJSONArray(TAG_LOCATIONS);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// looping through All Contacts
for(int i = 0; i < locations.length(); i++){
JSONObject c = locations.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String note = c.getString(TAG_NOTE);
String summary = c.getString(TAG_SUMMARY);
String my_lat = c.getString(TAG_LAT);
String my_lon = c.getString(TAG_LON);
String my_alt = c.getString(TAG_ALT);
String expires = c.getString(TAG_EXPIRES);
String created = c.getString(TAG_CREATED);
String uid = c.getString("uid");
String rating = c.getString("rating");
String num_ratings = c.getString("num_ratings");
String num_abuses = c.getString("num_abuses");
String sponsored = c.getString("sponsored");
String isprivate = c.getString("private");
db.addNote(
id,
title,
summary,
note,
my_lat,
my_lon,
my_alt,
created,
expires,
uid,
rating,
num_ratings,
num_abuses,
sponsored,
isprivate
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Define the criteria how to select the location provider -> use
// default
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setSpeedRequired(false);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_LOW);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
showSettingsAlert();
}
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("N/A");
longitudeField.setText("N/A");
altitudeField.setText("N/A");
accuracyField.setText("N/A");
}
} catch (Exception e) {
e.printStackTrace();
}
// DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// contactList = db.getNotes(latituteField.getText().toString(),longitudeField.getText().toString());
contactList.clear();
// System.out.println("ContactList: " + contactList);
// ((BaseAdapter) adapter).notifyDataSetChanged();
// System.out.println("adapter: " + adapter + " told that there is new data");
adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_TITLE, TAG_CREATED, TAG_DISTANCE, TAG_SUMMARY, TAG_EXPIRES, TAG_NOTE }, new int[] {
R.id.title, R.id.created, R.id.distance, R.id.summary, R.id.expires, R.id.note });
lv = (ListView) findViewById(R.id.list_view);
// lv.invalidateViews();
// lv.scrollBy(0, 0);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String created = ((TextView) view.findViewById(R.id.created)).getText().toString();
String expires = ((TextView) view.findViewById(R.id.expires)).getText().toString();
String note = ((TextView) view.findViewById(R.id.note)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_CREATED, created);
in.putExtra(TAG_EXPIRES, expires);
in.putExtra(TAG_NOTE, note);
startActivity(in);
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
/*
public class MySimpleAdapter extends SimpleAdapter {
private ArrayList<HashMap<String, String>> results;
public MySimpleAdapter(OnClickListener onClickListener, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {
super((Context) onClickListener, data, resource, from, to);
this.results = data;
}
}
*/
/* Request updates at startup */
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 1000, 10, this);
}
/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
float lat = (float) (location.getLatitude());
float lng = (float) (location.getLongitude());
float alt = (float) (location.getAltitude());
float acc = (float) (location.getAccuracy());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
altitudeField.setText(String.valueOf(alt));
accuracyField.setText(String.valueOf(acc));
if (acc >= 50.0) {
accuracyField.setTextColor(0xffff8888);
} else {
accuracyField.setTextColor(0xff88ff88);
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
/*
public ListAdapter Refresh() {
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_TITLE, TAG_CREATED, TAG_DISTANCE, TAG_SUMMARY, TAG_EXPIRES, TAG_NOTE }, new int[] {
R.id.title, R.id.created, R.id.distance, R.id.summary, R.id.expires, R.id.note });
try {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
contactList = db.getNotes(latituteField.getText().toString(),longitudeField.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
return adapter;
}
*/
public void Disabled(String error) {
Toast.makeText(this, "Not working yet. " + error,
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment