我想在保存的地方弹出,但它在当前的位置给出

时间:2014-08-30 07:14:55

标签: android gps popup location google-maps-api-2

我添加了所需的位置/地点,我想要通知哪个,但它开始在当前位置弹出窗口....

以下是主要课程:

这是服务类:

   package info.androidhive.googlemapsv2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.LinearLayout.LayoutParams;

public class MyLocationService extends Service implements LocationListener{

    //private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    SharedPrefs sharedPrefs;


    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    //private static final long MIN_TIME_BW_UPDATES = 1000 * 600 ; // 10 min

    // Declaring a Location Manager
    protected LocationManager locationManager;


    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        //Toast.makeText(this, "Location Changed", Toast.LENGTH_LONG).show();
        DataSource ds = new DataSource(MyLocationService.this);
        ds.open();
        ArrayList<MLocation> locs  = ds.getAllLocations();
        ds.close();
        if(locs!=null)
        {
            if(locs.size()>0)
            {
                ArrayList<Double>diffs = new ArrayList<Double>();

                for(int i=0;i<locs.size();i++)
                {
                    double latitude = Double.parseDouble(locs.get(i).getLatitude());
                    double longitude = Double.parseDouble(locs.get(i).getLongitude()); 
                    double dist = distance(latitude, longitude, location.getLatitude(), location.getLongitude(), 'K');
                    diffs.add(dist);
                    Log.i("GoogleMapsV2", i+" :"+dist);
                }
                //Collections.sort(diffs);
                int minIndex = diffs.indexOf(Collections.min(diffs));
                Toast.makeText(this, "You Are at "+locs.get(minIndex).getCategory(), Toast.LENGTH_SHORT).show();

                Log.i("GoogleMapsV2" , " min:"+diffs.get(0));
                String category = locs.get(minIndex).getCategory();
                //changeRingerMode(category);

                SharedPrefs sp = new SharedPrefs(this);
                if(category.matches("Home"))
                {
                    if(sp.getNotificationBoolean())

                        showNotification1(this, sharedPrefs.getToDoListHome());

                    if(sp.getProfileBoolean())
                    changeRingerMode(sharedPrefs.getProfileHome());

                }
                else if(category.matches("Work"))
                {
                    if(sp.getProfileBoolean())
                    changeRingerMode(sharedPrefs.getProfileWork());


                    if(sp.getNotificationBoolean())
                    showNotification1(this, sharedPrefs.getToDoListWork());
                }
                else if(category.matches("Market"))
                {
                    if(sp.getProfileBoolean())
                    changeRingerMode(sharedPrefs.getProfileMarket());

                    if(sp.getNotificationBoolean())
                    showNotification1(this,sharedPrefs.getToDoListMarket());
                }


            }
        }
        else
        {
            Toast.makeText(this, "Locs is Null", Toast.LENGTH_LONG).show();
        }
    }
    void changeRingerMode(String ringerMode)
    {
        AudioManager am;
        am= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
        if(ringerMode.matches("Normal"))
        {
            Toast.makeText(getApplicationContext(), "Normal Mode Activated", Toast.LENGTH_LONG).show();
            am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        else if(ringerMode.matches("Vibrate"))
        {
            Toast.makeText(getApplicationContext(), "Vibrate Mode Activated", Toast.LENGTH_LONG).show();
            am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
        }
        else if(ringerMode.matches("Silent"))
                {
            Toast.makeText(getApplicationContext(), "Silent Mode Activated", Toast.LENGTH_LONG).show();
            am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                }
        else
        {
            Toast.makeText(getApplicationContext(), "Default:Normal Mode Activated", Toast.LENGTH_LONG).show();
            am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }

    }
    @SuppressLint("NewApi")
    void showNotification(Context context, String todoList)
    {



        // new DrawGraph().showNotification();
        // define sound URI, the sound to be played when there's a notification
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // intent triggered, you can add other intent for other actions
        Intent intent1 = new Intent(context, Categories.class);

        PendingIntent pIntent = PendingIntent.getActivity(this, 0,intent1 , 0);

        // this is it, we'll build the notification!
        // in the addAction method, if you don't want any icon, just set the first param to 0
        Notification mNotification = new Notification.Builder(context)

            .setContentTitle("To Do")
            .setContentText(todoList)
            .setSmallIcon(R.drawable.ic)
            .setContentIntent(pIntent)
            .setSound(soundUri)

            .build();

        NotificationManager notificationManager=  (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);;

        // If you want to hide the notification after it was selected, do the code below
        // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, mNotification);
    }
    void showNotification1(Context context, String todoList)
    {


        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getApplicationContext());

       /***
        * Creating Alert Dialogue To show Categories
        */
      //  alertDialog.addContentView(listView, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));

       // alertDialog.add(input, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
        alertDialog.setTitle("To Do");
        alertDialog.setMessage(todoList);
alertDialog.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

                }
        });
        AlertDialog alert =  alertDialog.create();

        alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);


        alert.show();
    }
    /**
     * distance Between Two latitudes and longitudes
     * @param lat1
     * @param lon1
     * @param lat2
     * @param lon2
     * @param unit
     * @return
     */
     private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
          double theta = lon1 - lon2;
          double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
          dist = Math.acos(dist);
          dist = rad2deg(dist);
          dist = dist * 60 * 1.1515;
          if (unit == 'K') {
            dist = dist * 1.609344;
          } else if (unit == 'N') {
            dist = dist * 0.8684;
            }
          return (dist);
        }

        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        /*::  This function converts decimal degrees to radians             :*/
        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        private double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }

        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        /*::  This function converts radians to decimal degrees             :*/
        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        private double rad2deg(double rad) {
          return (rad * 180.0 / Math.PI);
        }
    @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
        Toast.makeText(this, provider+" Enabled", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, provider+" Disabled", Toast.LENGTH_LONG).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        //Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        Log.i("GoogleMapsV2" ,"Service Started");
        sharedPrefs = new SharedPrefs(MyLocationService.this);
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        getLocation();
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                Toast.makeText(this, "No Network Provider is Enabled", Toast.LENGTH_LONG).show();
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) 
                {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0, //MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, 
                            this);

                    Log.d("Network", "Network");

                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                //MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, 
                                0,this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }
}

这是位置活动类:

package info.androidhive.googlemapsv2;

import java.util.ArrayList;
import java.util.Calendar;

import android.widget.ListView;

import java.util.List;

import org.apache.http.util.LangUtils;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.location.GpsSatellite;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ArrayAdapter;

public class LocationActivity extends Activity {
    private DataSource obj;
    List<MLocation> stst;
    Button addlocation,viewAddlocation;
    EditText input;
    AlertDialog.Builder alertDialog;
    double latitude=0;
    double longitude=0;
    private GoogleMap googleMap;
     Spinner spinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location);

        try {
            // Loading map
            initilizeMap();

        } catch (Exception e) {
            e.printStackTrace();
        }
        obj = new DataSource(this);
        latitude = 17.385044;
        longitude = 78.486671;
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        try
        {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        }
        catch(Exception e)
        {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

        }

        // create marker
        //MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker");
        //googleMap.addMarker(marker);
        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {
                googleMap.clear();
                MarkerOptions marker = new MarkerOptions().position(
                        new LatLng(point.latitude, point.longitude)).title("New Marker");

                googleMap.addMarker(marker);

            System.out.println(point.latitude+"---"+ point.longitude);  
            latitude=point.latitude;
            longitude=point.longitude;
            }
        });

        /*String abc=String.valueOf(longitude);
        Toast toast = Toast.makeText(getApplicationContext(), "hello "+abc, Toast.LENGTH_LONG);
        toast.show();*/
        googleMap.setMyLocationEnabled(true);
        addlocation=(Button)findViewById(R.id.button1);

        alertDialog = new AlertDialog.Builder(this);
        addlocation.setOnClickListener(new View.OnClickListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                //alertDialog.EditText();

                if(latitude==0 ||longitude==0)
                {
                    Toast.makeText(getApplicationContext(),"No Location Selected", Toast.LENGTH_LONG).show();
                    return;
                }

                //EditText txt=new EditText(getApplicationContext());
                //alertDialog.setMessage("Welcome to AndroidHive.info");

                LinearLayout layout = new LinearLayout(getApplicationContext());
                LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                layout.setLayoutParams(params);
                layout.setOrientation(LinearLayout.VERTICAL);

                layout.removeAllViews();


                input = new EditText(getApplicationContext());
                input.setHint("Description");
                input.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE);

                //add category Spinner
                String[] strings={"Home","Work","Market"};
                spinner=new Spinner(getApplicationContext());
                spinner.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,strings));
                    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> parent,
                                View view, int position, long id) {
                            // TODO Auto-generated method stub
                        //  Toast.makeText(getApplicationContext(), position+"", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                            // TODO Auto-generated method stub

                        }
                    });
                            layout.addView(spinner);


                layout.addView(input);
               /***
                * Creating Alert Dialogue To show Categories
                */
              //  alertDialog.addContentView(listView, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
                alertDialog.setView(layout);
               // alertDialog.add(input, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
                alertDialog.setTitle("Add Discription");

                alertDialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                        //Toast toast = Toast.makeText(getApplicationContext(), input.getText().toString()+" latitude "+latitude+" longitude "+longitude, Toast.LENGTH_LONG);
                        //toast.show();
                        try{
                            if(input.getText().toString().length()>0)
                            {
                            obj.open();
                            obj.createLocation(String.valueOf(latitude), String.valueOf(longitude), input.getText().toString(),spinner.getSelectedItemPosition());
                            obj.close();
                            input.setText("");
                            }
                            else
                            {
                                Toast toast = Toast.makeText(getApplicationContext(), "Desctiption Empty", Toast.LENGTH_LONG);
                                toast.show();
                            }
                        }
                        catch(Exception e)
                        {
                            Toast toast = Toast.makeText(getApplicationContext(), "yes " +e.toString(), Toast.LENGTH_LONG);
                            toast.show();
                        }
                        }
                });
                alertDialog.show();
                //layout.removeAllViews();
            }
        });
        viewAddlocation=(Button)findViewById(R.id.button2);
        viewAddlocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                // yahaan adapter mein alert masge mein list view data show krna thk  ...
                // smjh gaey ho ...
                Intent in =new Intent(LocationActivity.this,ViewLocations.class);
                startActivity(in);

            }
        });

    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressLint("NewApi")
    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            setCurrentLocation();
            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
    double GPSLongitude,GPSLatitude;
     void setCurrentLocation()
        {
            //Get GPS Coordinates

            try
            {
                LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
                Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            if(location==null)
            {
                location  = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }

            if(!(location==null))
            {
            GPSLongitude = location.getLongitude();
            GPSLatitude = location.getLatitude();
            Log.i("GPS","Lat: "+GPSLatitude+" Long "+ GPSLongitude);
            Toast.makeText(getApplicationContext(), "Location is "+GPSLatitude+" Long "+ GPSLongitude, Toast.LENGTH_LONG).show();
            googleMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(GPSLatitude,GPSLongitude) , 16.0f) );
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Location is null", Toast.LENGTH_LONG).show();
            }
            }
            catch(Exception e)
            {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.toString()+"\nCould Not Get GPS  Coordinates. Make Sure Locations Is On!", Toast.LENGTH_LONG).show();

            }
        }

}

这些是数据库处理程序类:

package info.androidhive.googlemapsv2;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DataSource {

  // Database fields
  private SQLiteDatabase database;
  private MySQLiteHelper dbHelper;
  private String[] allColumns = { MySQLiteHelper.COLUMN_ID,MySQLiteHelper.COLUMN_DISCRIPTION, MySQLiteHelper.COLUMN_LATITUDE, MySQLiteHelper.COLUMN_LONGITUDE, MySQLiteHelper.COLUMN_CATEGORY };

  public DataSource(Context context) {
    dbHelper = new MySQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }
  public void read() throws SQLException {
        database = dbHelper.getReadableDatabase();
      }


  public MLocation createLocation(String latitude,String longitude,String discription, int category) {
    ContentValues values = new ContentValues();
    values.put(MySQLiteHelper.COLUMN_LATITUDE, latitude);
    values.put(MySQLiteHelper.COLUMN_LONGITUDE, longitude);
    values.put(MySQLiteHelper.COLUMN_DISCRIPTION, discription);
    values.put(MySQLiteHelper.COLUMN_CATEGORY, category);
    long insertId = database.insert(MySQLiteHelper.TABLE_LOCATION, null,
        values);
   Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,
        allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
        null, null, null);
   /* Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,
            allColumns, null, null,
            null, null, null);*/
    cursor.moveToFirst();
    MLocation newMessage = cursorToLocation(cursor);
    cursor.close();
    return newMessage;
  }

  public void deleteLocation(MLocation loc) {
    long id = loc.getId();
    System.out.println("Comment deleted with id: " + id);
    database.delete(MySQLiteHelper.TABLE_LOCATION, MySQLiteHelper.COLUMN_ID + " = " + id, null);
  }
  /**
   * update a location
   * @param location
   */
  public void updateMessage(MLocation location) {
       /* long id = message.getId();
        System.out.println("Comment updated with id: " + id);
        ContentValues newValues = new ContentValues();
        newValues.put(MySQLiteHelper.COLUMN_DISCRIPTION, message.getmessage());
        int rows = database.update(MySQLiteHelper.TABLE_LOCATION,newValues ,MySQLiteHelper.COLUMN_ID+ " = " + id, null);
        System.out.println("Rows Updated: " + rows);*/

        String q = "UPDATE "+MySQLiteHelper.TABLE_LOCATION+" SET "+
                MySQLiteHelper.COLUMN_DISCRIPTION+" = '"+location.getDescription()
                +"' WHERE "+MySQLiteHelper.COLUMN_ID+" = "+location.getId();
        database.execSQL(q);
        System.out.println("Rows Updated: " +q);
      }


  public ArrayList<MLocation> getAllLocations() {
    ArrayList<MLocation> locs = new ArrayList<MLocation>();
    try
    {
    Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      MLocation loc = cursorToLocation(cursor);
      locs.add(loc);
      cursor.moveToNext();
    }
    // Make sure to close the cursor
    cursor.close();
    return locs;
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
        return null;
    }
  }


  private MLocation cursorToLocation(Cursor cursor) {
    MLocation loc = new MLocation();
    loc.setId(cursor.getLong(0));
    loc.setDescription(cursor.getString(1));
   loc.setLatitude(cursor.getString(2));
   loc.setLongitude(cursor.getString(3));
   loc.setCategoryInt(cursor.getInt(4));
    return loc;
  }
} 

SqliteHelper类:

package info.androidhive.googlemapsv2;import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_LOCATION = "location";
  public static final String COLUMN_ID = "id";
  public static final String COLUMN_LATITUDE = "latitute";
  public static final String COLUMN_LONGITUDE = "longitude";
  public static final String COLUMN_DISCRIPTION = "discription";
  public static final String COLUMN_CATEGORY = "category";

  private static final String DATABASE_NAME = "profile.db";
  private static final int DATABASE_VERSION = 2;


    static final String DATABASE_CREATE = "create table "+TABLE_LOCATION+
            "( " +COLUMN_ID+" integer primary key autoincrement,"+ COLUMN_LATITUDE+ " text not null,"+COLUMN_LONGITUDE+" text not null, "+COLUMN_DISCRIPTION +" text, "
                        +COLUMN_CATEGORY+" integer); ";


  public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);
  }


  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(MySQLiteHelper.class.getName(),
        "Upgrading database from version " + oldVersion + " to "
            + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATION);
    onCreate(db);
  }

} 

0 个答案:

没有答案