IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

Utilisation de SQLLite


Sujet :

Android

  1. #1
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut Utilisation de SQLLite
    bonjour à tous,

    je veut utliser une base de données pour une application sous Android.

    j' ai déja créer un ContentProvider est j'ai mis tout ses méthodes (insert , upgrade, oncreate ...).

    Je veut utiliser cette classe là.Mais,je ne connais pas où je dois insérer le contenu de ma table (les valeurs) et comment

    Merci de répondre

  2. #2
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut
    y t il quelqu'un qui me répondre.

    il se peut que la question est un peu vage ou trés facile mais je n'arrive pas à la résoudre.


    Mais,je veut comment remplir la table.Ou je dois mettre la méthode qui fait ca

    dans la ContentProvider ou ailleurs.

  3. #3
    Rédacteur
    Avatar de MrDuChnok
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2002
    Messages
    2 112
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 2 112
    Points : 4 240
    Points
    4 240
    Par défaut
    Perso, j'ai pas bien compris ton problème.
    Tu dis avoir tout fais pour faire des requêtes d'insert / update / select / delete, et ensuite tu nous dis ne pas réussir à remplir ta table.
    Pourrais-tu détailler un peu plus ton problème ?

    merci.
    Si vous jugez mon post utile dans la résolution de votre problème, n'hésitez pas à utiliser le système de vote afin d'améliorer la qualité du forum

  4. #4
    Inscrit

    Profil pro
    Inscrit en
    Février 2008
    Messages
    658
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2008
    Messages : 658
    Points : 892
    Points
    892
    Par défaut
    Voici comment insérer une ligne :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
     
    private void ajouteruneligne(String string) {
     
    //db est le nom de la base cree
    SQLiteDatabase db = events.getWritableDatabase();
     
    // values contient les valeurs à inserer par exemple pour une personne definie //par son nom et prenom values.put("Nom"),values.put("Prenom")
    ContentValues values = new ContentValues();
    values.put()........................
     
    //table est le nom de la table dans la base 
    db.insertOrThrow(table, null, values);

  5. #5
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut
    Merci pour vos réponses,

    j'ai utilisé ce que jahbromo à proposer dans un autre classe (pas dans le

    ContentProvider)comme dans le code ci-dessus .

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    button1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // Perform action on click
                	ContentResolver cr = getContentResolver();
     
                	ContentValues newValues1 = new ContentValues();
            		newValues1.put(LocationsProvider.KEY_LOCATION_REGION,"NorthAfrica");
            		newValues1.put(LocationsProvider.KEY_LOCATION_LAT,"10.3");
            		newValues1.put(LocationsProvider.KEY_LOCATION_LNG,"23.14");
            		cr.insert(LocationsProvider.CONTENT_URI,newValues1);
     
                	ContentValues newValues2 = new ContentValues();
            		newValues2.put(LocationsProvider.KEY_LOCATION_REGION,"NorthAfrica");
            		newValues2.put(LocationsProvider.KEY_LOCATION_LAT,"10.3");
            		newValues2.put(LocationsProvider.KEY_LOCATION_LNG,"24.14");
            		cr.insert(LocationsProvider.CONTENT_URI,newValues2);
     
             final MapView LocationMap=(MapView)findViewById(R.id.mapView);
     
                   Uri locationsURI= LocationsProvider.CONTENT_URI;
                   locationsCursor = getContentResolver().query(locationsURI,null,null,null,null);
     //  la méthode invokée ci- dessous permet de placer des points au positions
    //   dont les lat et long sont dans la base définie dans   LocationsProvider              
                    LocalisationOverlay eo=new LocalisationOverlay(locationsCursor);
    // LocationMap est le nom du MapActivity 
                    LocationMap.getOverlays().add(eo);            
                }
            });       
        }

    Est-ce que ce est juste?

    Merci de répondre.

  6. #6
    Inscrit

    Profil pro
    Inscrit en
    Février 2008
    Messages
    658
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2008
    Messages : 658
    Points : 892
    Points
    892
    Par défaut
    Apparemment c'est juste, mais c'est après l'exécution quand le code te donne ce que tu attends, c'est alors que tu dira que c'est juste

  7. #7
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut
    Merci jahbromo,

    J'ai essayé de lancer l'application mais elle se plante.
    Mon code est le suivant:
    1) LocationProvider:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    package com.android.P2A;
     
    import android.content.ContentProvider;
    import android.content.ContentUris;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.UriMatcher;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.database.sqlite.SQLiteQueryBuilder;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    import android.net.Uri;
    import android.text.TextUtils;
    import android.util.Log;
     
    public class LocationsProvider extends ContentProvider{
     
    	/*
    	 * Fields:
    	 */
     
    	public static final Uri CONTENT_URI =
    		Uri.parse("content://com.android.P2A.LocationsProvider/locations");
    	// The underlying database
    	private SQLiteDatabase LocalisationDB;
    	private static final String TAG = "LocationProvider";
    	private static final String DATABASE_NAME = "Locations.db";
    	private static final int DATABASE_VERSION = 1;
    	private static final String LOCATIONS_TABLE = "Locations";
    	// Column Names
    	public static final String KEY_ID = "_id";
    	public static final String KEY_LOCATION_REGION = "région";
    	public static final String KEY_LOCATION_LAT = "latitude";
    	public static final String KEY_LOCATION_LNG = "longitude";
     
    	// Column indexes
    	public static final int REGION_COLUMN = 1;
    	public static final int LATITUDE_COLUMN =2;
    	public static final int LONGITUDE_COLUMN =3;
     
     
     
     
     // Create the constants used to differentiate between the different URI
     // requests.
        private static final int LOCATIONS = 1;
        private static final int LOCATION_ID = 2;
        private static final UriMatcher uriMatcher;
        static {
        	uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        	uriMatcher.addURI("com.android.P2A.LocationsProvider", "Localions",
        	LOCATIONS);
        	uriMatcher.addURI("com.android.P2A.LocationsProvider", "Locations/#",
        	LOCATION_ID);
        }
     
     // Helper class for opening, creating, and managing
     // database version control
        private static class LocationsDatabaseHelper extends SQLiteOpenHelper {
        	private static final String DATABASE_CREATE =
        			"create table " + LOCATIONS_TABLE + " ("
        					+ KEY_ID + " integer primary key autoincrement, "
     
        					+ KEY_LOCATION_REGION + " VARCHAR(255), "
        					+ KEY_LOCATION_LAT + " FLOAT, "
        					+ KEY_LOCATION_LNG + " FLOAT, ";
     
     
        	public LocationsDatabaseHelper(Context context, String name,
        				CursorFactory factory, int version) {
        				super(context, name, factory, version);
        	}
        	@Override
        	public void onCreate(SQLiteDatabase db) {
        	db.execSQL(DATABASE_CREATE);
        	}  	
        	@Override
        	public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) {
        		Log.w(TAG,"Upgrading database from version " + oldVersion + " to "
        				+ newVersion + ", which will destroy all old data");
        				db.execSQL("DROP TABLE IF EXISTS " + LOCATIONS_TABLE);
        				onCreate(db);
        				}
        				}	
     
    	@Override
    	public int delete(Uri uri, String where, String[] whereArgs) {
    		// TODO Auto-generated method stub
    		int count;
    		switch (uriMatcher.match(uri)) {
    		case LOCATIONS:
    		count = LocalisationDB.delete(LOCATIONS_TABLE, where, whereArgs);
    		break;
    		case LOCATION_ID:
    		String segment = uri.getPathSegments().get(1);
    		count = LocalisationDB.delete(LOCATIONS_TABLE, KEY_ID + "="
    		+ segment
    		+ (!TextUtils.isEmpty(where) ? " AND ("
    		+ where + ')' :""), whereArgs);
    		break;
    		default: throw new IllegalArgumentException("Unsupported URI: " +
    		uri);
    		}
    		getContext().getContentResolver().notifyChange(uri, null);
    		return count;
    		}
     
    	@Override
    	public String getType(Uri arg0) {
    		// TODO Auto-generated method stub
    		return null;
    	}
     
     
     
    	@Override
    	public Uri insert(Uri _uri, ContentValues _initialValues) {
    		// TODO Auto-generated method stub
    		// Insert the new row, will return the row number if
    		// successful.
    		long rowID = LocalisationDB.insert(LOCATIONS_TABLE, "quake",
    		_initialValues);
    		// Return a URI to the newly inserted row on success.
    		if (rowID > 0) {
    		Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
    		getContext().getContentResolver().notifyChange(uri, null);
    		return uri;
    		}
    		throw new SQLException("Failed to insert row into " + _uri);
    		}
     
     
     
    	@Override
    	public boolean onCreate() {
    		// TODO Auto-generated method stub
     
    		Context context = getContext();
    		LocationsDatabaseHelper dbHelper;
    		dbHelper = new LocationsDatabaseHelper(context, DATABASE_NAME, null,
    		DATABASE_VERSION);
    		LocalisationDB = dbHelper.getWritableDatabase();
    		return (LocalisationDB == null) ? false : true;
    		}
     
     
    	@Override
    	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
    			String sort) {
    		// TODO Auto-generated method stub
    		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    		qb.setTables(LOCATIONS_TABLE);
    		// If this is a row query, limit the result set to the passed in row.
    		switch (uriMatcher.match(uri)) {
    		case LOCATION_ID:
    		qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
    		break;
    		default: break;
    		}
    		// If no sort order is specified sort by date / time
    		String orderBy;
    		if (TextUtils.isEmpty(sort)) {
    		orderBy = KEY_ID;
    		} else {
    		orderBy = sort;
    		}
    		// Apply the query to the underlying database.
    		Cursor c = qb.query(LocalisationDB,projection,selection, selectionArgs,null, null,orderBy);
    		// Register the contexts ContentResolver to be notified if
    		// the cursor result set changes.
    		c.setNotificationUri(getContext().getContentResolver(), uri);
    		// Return a cursor to the query result.
    		return c;
    		}
     
    	@Override
    	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    		// TODO Auto-generated method stub
    		int count;
    		switch (uriMatcher.match(uri)) {
    		case LOCATIONS:
    		count = LocalisationDB.update(LOCATIONS_TABLE, values,
    		where, whereArgs);
    		break;
    		case LOCATION_ID:
    		String segment = uri.getPathSegments().get(1);
    		count = LocalisationDB.update(LOCATIONS_TABLE, values, KEY_ID
    		+ "=" + segment
    		+ (!TextUtils.isEmpty(where) ? " AND ("+ where + ')' : ""), whereArgs);
    		break;
    		default: throw new IllegalArgumentException("Unknown URI " + uri);
    		}
    		getContext().getContentResolver().notifyChange(uri, null);
    		return count;
    		}
     
     
    }
    2) LocationMap:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    package com.android.P2A;
     
     
    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.database.Cursor;
     
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
     
     
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;
     
    public class LocalisationMap extends MapActivity{
    	/*
    	 * Fields:
    	 */
    	Cursor locationsCursor;
     
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.localisation_map);
     
            final Button button1 = (Button) findViewById(R.id.Button02);
     
            button1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // Perform action on click
                	ContentResolver cr = getContentResolver();
     
                	ContentValues newValues1 = new ContentValues();
            		newValues1.put(LocationsProvider.KEY_LOCATION_REGION,"NorthAfrica");
            		newValues1.put(LocationsProvider.KEY_LOCATION_LAT,"10.3");
            		newValues1.put(LocationsProvider.KEY_LOCATION_LNG,"23.14");
            		cr.insert(LocationsProvider.CONTENT_URI,newValues1);
     
                	ContentValues newValues2 = new ContentValues();
            		newValues2.put(LocationsProvider.KEY_LOCATION_REGION,"NorthAfrica");
            		newValues2.put(LocationsProvider.KEY_LOCATION_LAT,"10.3");
            		newValues2.put(LocationsProvider.KEY_LOCATION_LNG,"24.14");
            		cr.insert(LocationsProvider.CONTENT_URI,newValues2);
             final MapView LocationMap=(MapView)findViewById(R.id.mapView);	
                   Uri locationsURI= LocationsProvider.CONTENT_URI;
                   locationsCursor = getContentResolver().query(locationsURI,null,null,null,null);
     
                    LocalisationOverlay eo=new LocalisationOverlay(locationsCursor); 
                    LocationMap.getOverlays().add(eo);            
                }
            });       
        } 
     
     
     
     
     
    	@Override
    	protected boolean isRouteDisplayed() {
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    }


    Le LogCat me donne une erreur au niveau de ContentProvider:

    02-01 21:00:55.714: ERROR/AndroidRuntime(716): Uncaught handler: thread main exiting due to uncaught exception

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): java.lang.RuntimeException: Unable to get provider com.android.P2A.LocationsProvider: android.database.sqlite.SQLiteException: near " ": syntax error: create table Locations (_id integer primary key autoincrement, région VARCHAR(255), latitude FLOAT, longitude FLOAT,

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.app.ActivityThread.installProvider(ActivityThread.java:3857)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.app.ActivityThread.installContentProviders(ActivityThread.java:3659)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3618)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.app.ActivityThread.access$2500(ActivityThread.java:112)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1729)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.os.Handler.dispatchMessage(Handler.java:99)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.os.Looper.loop(Looper.java:123)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.app.ActivityThread.main(ActivityThread.java:3948)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at java.lang.reflect.Method.invokeNative(Native Method)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at java.lang.reflect.Method.invoke(Method.java:521)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at dalvik.system.NativeStart.main(Native Method)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): Caused by: android.database.sqlite.SQLiteException: near " ": syntax error: create table Locations (_id integer primary key autoincrement, région VARCHAR(255), latitude FLOAT, longitude FLOAT,

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1496)
    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at com.android.P2A.LocationsProvider$LocationsDatabaseHelper.onCreate(LocationsProvider.java:77)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:106)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at com.android.P2A.LocationsProvider.onCreate(LocationsProvider.java:144)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.content.ContentProvider.attachInfo(ContentProvider.java:607)

    02-01 21:00:55.736: ERROR/AndroidRuntime(716): at android.app.ActivityThread.installProvider(ActivityThread.java:3854)



    J'arrive à déterminer l'emplacement des erreurs:

    Ligne 77:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     	db.execSQL(DATABASE_CREATE);
    Ligne 144:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    LocalisationDB = dbHelper.getWritableDatabase();
    Mon Manifest contient :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
          <provider android:name=".LocationsProvider"
                    android:authorities="com.android.P2A.LocationsProvider"/>
    Pouvez vous indiquer l'erreur?

    Merci

  8. #8
    Rédacteur
    Avatar de MrDuChnok
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2002
    Messages
    2 112
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 2 112
    Points : 4 240
    Points
    4 240
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    private static final String DATABASE_CREATE =
        			"create table " + LOCATIONS_TABLE + " ("
        					+ KEY_ID + " integer primary key autoincrement, "
        					
        					+ KEY_LOCATION_REGION + " VARCHAR(255), "
        					+ KEY_LOCATION_LAT + " FLOAT, "
        					+ KEY_LOCATION_LNG + " FLOAT, ";
    Tu as une erreur sur la fin de ta requête. Je suis pas expert BDD, mais dans mes souvenirs, une requete ne se termine pas par ",", mais plutôt par ")" dans ton cas, non ?
    Si vous jugez mon post utile dans la résolution de votre problème, n'hésitez pas à utiliser le système de vote afin d'améliorer la qualité du forum

  9. #9
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut
    Merci pour votre remarque MrDuChnok,

    Aprés la correction de ce problème,l'application marche ,Mais lorsque je clique le bouton rien ne s'affiche .

    Je ne sais pas s'il ya une erreur au niveau de l'Authority vers la base (Path)
    ou ailleurs.


    La méthode (constructeur ) que j'appelle dans le Listener sur le button se trouve dans l'Activity suivante:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    package com.android.P2A;
     
    import java.util.ArrayList;
     
    import android.database.Cursor;
    import android.database.DataSetObserver;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Point;
    import android.graphics.RectF;
     
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapView;
    import com.google.android.maps.Overlay;
    import com.google.android.maps.Projection;
     
    public class LocalisationOverlay extends Overlay{
     
    	/*
    	 * Fields:
    	 */
    	ArrayList<GeoPoint> HopitalLocations;
        Cursor localisations;
        int rad=5;
        Double lat;
        Double lng;
        /*
         * Constructor:
         */
        public LocalisationOverlay(Cursor cursor){
        	super();
        	localisations= cursor;
        	HopitalLocations=new ArrayList<GeoPoint>();
        	refreshLocalisations();
        	localisations.registerDataSetObserver(new DataSetObserver(){
        		public void onChanged(){
        			refreshLocalisations();}
        	});
        }
     
        private void refreshLocalisations(){
        	if (localisations.moveToFirst())
        	do {
        	     lat =localisations.getFloat(2)*1E6;
        	     lng =localisations.getFloat(3)*1E6;
        	     GeoPoint geopoint=new GeoPoint(lng.intValue(),lat.intValue());
        	     HopitalLocations.add(geopoint);
        	}while (localisations.moveToNext());   
        	}
        public void draw(Canvas canvas,MapView mapview,boolean shadow){
        	Projection projection=mapview.getProjection();
        	// create and setup your paint brush
        	Paint paint=new Paint();
        	paint.setARGB(250,255,0,0);
        	paint.setAntiAlias(true);
        	paint.setFakeBoldText(true);
     
        	if(shadow==false){
        		for (GeoPoint  point:HopitalLocations){
        			Point mypoint=new Point();
        			projection.toPixels(point,mypoint);
        			RectF oval=new RectF(mypoint.x-rad,mypoint.y-rad,mypoint.x+rad,mypoint.y+rad);
        			canvas.drawOval(oval,paint);
        		}
        	}
        }
        }
    Est ce que vous pouvez m'indiquer si savez l'erreur?

    Merci

  10. #10
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut
    A t il quelqu'un qui peut connaitre l'erreur.

    Ou y t il une outre méthode pour le faire sachant que je cherche à afficher le map avec des markers au niveau de points définies dans ma base de données.

    Merci de répondre c urgent

  11. #11
    Rédacteur
    Avatar de MrDuChnok
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2002
    Messages
    2 112
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 2 112
    Points : 4 240
    Points
    4 240
    Par défaut
    Tu construit ton composant, mais as tu pensé à l'afficher ?

    Sinon faudrait que tu montres le code de ton listener sur ton bouton pour qu'on t'aide plus facilement.
    Si vous jugez mon post utile dans la résolution de votre problème, n'hésitez pas à utiliser le système de vote afin d'améliorer la qualité du forum

  12. #12
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut
    Voici le code du Map Activity y compris le listener que je utilisée:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    package com.android.P2A;
     
     
    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.graphics.Canvas;
     
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
     
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapView;
     
    public class LocalisationMap extends MapActivity{
    	/*
    	 * Fields:
    	 */
    	Cursor locationsCursor;
     
     
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.localisation_map);
     
        	ContentResolver cr = getContentResolver();
     
        	ContentValues newValues1 = new ContentValues();
    		newValues1.put(LocationsProvider.KEY_LOCATION_REGION,"Grand Tunis");
    		newValues1.put(LocationsProvider.KEY_LOCATION_LAT,"10");
    		newValues1.put(LocationsProvider.KEY_LOCATION_LNG,"23");
    		cr.insert(LocationsProvider.CONTENT_URI,newValues1);
     
        	ContentValues newValues2 = new ContentValues();
    		newValues2.put(LocationsProvider.KEY_LOCATION_REGION,"Grand Tunis");
    		newValues2.put(LocationsProvider.KEY_LOCATION_LAT,"10");
    		newValues2.put(LocationsProvider.KEY_LOCATION_LNG,"24");
    		cr.insert(LocationsProvider.CONTENT_URI,newValues2);
     
            Button button1 = (Button) findViewById(R.id.Button01);
     
            button1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // Perform action on click 
     
                MapView LocationMap=(MapView)findViewById(R.id.mapView);	
                Uri locationsURI= LocationsProvider.CONTENT_URI;
     
                locationsCursor = getContentResolver().query(locationsURI,null,null,null,null);
     
                LocalisationOverlay eo=new LocalisationOverlay(locationsCursor); 
                LocationMap.getOverlays().add(eo); 
                LocationMap.postInvalidate();   
     
                }
            });     
        } 
     
     
     
     
     
    	@Override
    	protected boolean isRouteDisplayed() {
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    }

    Je vous dit encore que l'Overlay que j'ai invoqué son constructeur:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    package com.android.P2A;
     
    import java.util.ArrayList;
     
    import android.database.Cursor;
    import android.database.DataSetObserver;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Point;
    import android.graphics.RectF;
     
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapView;
    import com.google.android.maps.Overlay;
    import com.google.android.maps.Projection;
     
    public class LocalisationOverlay extends Overlay{
     
    	/*
    	 * Fields:
    	 */
    	ArrayList<GeoPoint> HopitalLocations;
        Cursor localisations;
        int rad=5;
       Double lat;
       Double lng;
        /*
         * Constructor:
         */
     
        public LocalisationOverlay(Cursor cursor){
        	super();
        	localisations= cursor;
        	HopitalLocations=new ArrayList<GeoPoint>();
       	refreshLocalisations();  	
        	localisations.registerDataSetObserver(new DataSetObserver(){
        		public void onChanged(){
        			refreshLocalisations();}
        	});
        }
     
        private void refreshLocalisations(){
        	if (localisations.moveToFirst())
        	do {
        	     lat =localisations.getInt(2)*1E6;
        	     lng =localisations.getInt(3)*1E6;
        	     GeoPoint geopoint=new GeoPoint(lng.intValue(),lat.intValue());
        	     HopitalLocations.add(geopoint);
        	}while (localisations.moveToNext());   
        	}
     
     
     
        public void draw(Canvas canvas,MapView mapview,boolean shadow){
        	Projection projection=mapview.getProjection();
        	// create and setup your paint brush
        	Paint paint=new Paint();
        	paint.setARGB(250,255,0,0);
        	paint.setAntiAlias(true);
        	paint.setFakeBoldText(true);
     
        	if(shadow==false){
        		for (GeoPoint  point:HopitalLocations){
        			Point mypoint=new Point();
        			projection.toPixels(point,mypoint);
        			RectF oval=new RectF(mypoint.x-rad,mypoint.y-rad,mypoint.x+rad,mypoint.y+rad);
        			canvas.drawOval(oval,paint);
        		}
        	}
        }      
        }

    Merci esssayer je me suis bloqué

  13. #13
    Membre à l'essai
    Inscrit en
    Avril 2009
    Messages
    26
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 26
    Points : 17
    Points
    17
    Par défaut
    J'arrive à découvrir que le marker ne s'affichent pas au premier vue (j'ai glissé le Map pour y aller )


    Que ce que je peut faire pour que les markers s'affichent au premier vue ( sans glisser le Map) ?

    Merci

Discussions similaires

  1. utiliser les tag [MFC] [Win32] [.NET] [C++/CLI]
    Par hiko-seijuro dans le forum Visual C++
    Réponses: 8
    Dernier message: 08/06/2005, 15h57
  2. Réponses: 4
    Dernier message: 05/06/2002, 14h35
  3. utilisation du meta type ANY
    Par Anonymous dans le forum CORBA
    Réponses: 1
    Dernier message: 15/04/2002, 12h36
  4. [BCB5] Utilisation des Ressources (.res)
    Par Vince78 dans le forum C++Builder
    Réponses: 2
    Dernier message: 04/04/2002, 16h01
  5. Réponses: 2
    Dernier message: 20/03/2002, 23h01

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo