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

API standards et tierces Android Discussion :

Récupération des données du serveur dans l'application Android


Sujet :

API standards et tierces Android

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2014
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Mai 2014
    Messages : 3
    Points : 0
    Points
    0
    Par défaut Récupération des données du serveur dans l'application Android
    Bonjour à tous,
    j'espère que vous allez bien. Voici l'exposé de mon problème :

    1.j'ai une table commande (cid,login,name,price,quantite,created_at,somme)

    2.j'ai une listview
    Nom : cmd.JPG
Affichages : 1135
Taille : 110,6 KoNom : cmd.JPG
Affichages : 1009
Taille : 17,2 Ko



    mon problème : lorsque je clique sur l'un des items(login) de la listview je veux afficher les dates de commandes(created_at) de chaque item(login).

    Voici mes sources Java et PHP :

    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
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
     
    	package com.example.androidhive;
     
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
     
    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.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
     
    public class voirdate extends ListActivity {
     
     
    	String login;
    	// Progress Dialog
    	private ProgressDialog pDialog;
     
    	// Creating JSON Parser object
    	JSONParser jParser = new JSONParser();
     
    	ArrayList<HashMap<String, String>> productsList;
     
    	// url to get all products list
    	private static String url_all_products = "http://192.168.1.2/tst/tous_les_dates2.php";
     
    	// JSON Node names
    	private static final String TAG_SUCCESS = "success";
    	private static final String TAG_PRODUCTS = "commande";
     
    	private static final String TAG_LOGIN = "login";
     
     
    	private static final String TAG_CREATED_AT = "created_at";
     
    	// products JSONArray
    	JSONArray commande = null;
    	//JSONArray client = null;
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.all_products);
     
    		// getting product details from intent
    				Intent i = getIntent();
     
    				// getting product id (pid) from intent
    				login = i.getStringExtra(TAG_LOGIN);
     
    		// Hashmap for ListView
    		productsList = new ArrayList<HashMap<String, String>>();
     
    		// Loading products in Background Thread
    		new LoadAllProducts().execute();
     
    		// Get listview
     
    		ListView lv = getListView();
     
    		// on seleting single product
    		// launching Edit Product Screen
    		lv.setOnItemClickListener(new OnItemClickListener() {
     
    			public void onItemClick(AdapterView<?> parent, View view,int position, long id)
    			{
    				// getting values from selected ListItem
     
    				String login = ((TextView)view.findViewById(R.id.login)).getText().toString();
     
     
     
     
    				//String created_at = ((TextView) view.findViewById(R.id.created_at)).getText()
    						//.toString();
    			//String login = ((TextView) view.findViewById(R.id.login)).getText().toString();
     
    				// Starting new intent
    				Intent in = new Intent(getApplicationContext(),
    						ModiferproduitActivity.class);
     
    				// sending pid to next activity
    				//in.putExtra(TAG_CREATED_AT, created_at);
    				in.putExtra(TAG_LOGIN, login);
    				// starting new activity and expecting some response back
    				startActivityForResult(in, 100);
    			}
    		});
     
    	}
     
    	// Response from Edit Product Activity
    	@Override
    	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    		super.onActivityResult(requestCode, resultCode, data);
    		// if result code 100
    		if (resultCode == 100) {
    			// if result code 100 is received 
    			// means user edited/deleted product
    			// reload this screen again
    			Intent intent = getIntent();
    			finish();
    			startActivity(intent);
    		}
     
    	}
     
    	/**
             * Background Async Task to Load all product by making HTTP Request
             * */
    	class LoadAllProducts extends AsyncTask<String, String, String> {
     
    		/**
                     * Before starting background thread Show Progress Dialog
                     * */
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    			pDialog = new ProgressDialog(voirdate.this);
    			pDialog.setMessage("Chargement . Patientez svp...");
    			pDialog.setIndeterminate(false);
    			pDialog.setCancelable(false);
    			pDialog.show();
    		}
     
    		/**
                     * getting All products from url
                     * */
    		protected String doInBackground(String... args) {
    			// Building Parameters
    			List<NameValuePair> params = new ArrayList<NameValuePair>();
    			params.add(new BasicNameValuePair("login", login));
    			// getting JSON string from URL
    			JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
     
    			// Check your log cat for JSON reponse
    			Log.d("All Products: ", json.toString());
     
    			try {
    				// Checking for SUCCESS TAG
    				int success = json.getInt(TAG_SUCCESS);
     
    				if (success == 1) {
    					// products found
    					// Getting Array of Products
    					commande = json.getJSONArray(TAG_PRODUCTS);
    					//client = json.getJSONArray(TAG_PRODUCTS);
     
    					// looping through All Products
    					for (int i = 0; i < commande.length(); i++) 
    						//for (int j = 0; j < client.length(); j++) 
    						{
    						JSONObject c = commande.getJSONObject(i);
    						//JSONObject d = client.getJSONObject(j);
     
    						// Storing each json item in variable
    						//String login = c.getString(TAG_LOGIN);
    						//String login = c.getString(TAG_LOGIN);
    						String created_at = c.getString(TAG_CREATED_AT);
    						// creating new HashMap
    						HashMap<String, String> map = new HashMap<String, String>();
     
    						// adding each child node to HashMap key => value
    						//map.put(TAG_LOGIN, login);
    						//map.put(TAG_LOGIN, login);
    						map.put(TAG_CREATED_AT, created_at);
    						// adding HashList to ArrayList
    						productsList.add(map);
    					}
    				} /*else {
    					// no products found
    					// Launch Add New product Activity
    					Intent i = new Intent(getApplicationContext(),
    							AjouterproduitActivity.class);
    					// Closing all previous activities
    					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    					startActivity(i);
    				}*/
    			} catch (JSONException e) {
    				e.printStackTrace();
    			}
     
    			return null;
    		}
     
    		/**
                     * After completing background task Dismiss the progress dialog
                     * **/
    		protected void onPostExecute(String file_url) {
    			// dismiss the dialog after getting all products
    			pDialog.dismiss();
    			// updating UI from Background Thread
    			runOnUiThread(new Runnable() {
    				public void run() {
    					/**
                                             * Updating parsed JSON data into ListView
                                             * */
    					ListAdapter adapter = new SimpleAdapter(
    							voirdate.this, productsList,
    							R.layout.list_item4, new String[] { TAG_LOGIN,
    									/*TAG_LOGIN,*/TAG_CREATED_AT},
    							new int[] {R.id.login, /* R.id.login,*/R.id.created_at });
    					// updating listview
    					setListAdapter(adapter);
    				}
    			});
     
    		}
     
    	}
    }


    php :
    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
     
     
    /*
     * Following code will list all the products
     */
     
    // array for JSON response
    $response = array();
     
    if (isset($_GET['lgon'])){
     $login = $_GET['login'];
    // include db connect class
    require_once'db_connect.php';
     
    // connecting to db
    $db = new DB_CONNECT();
     
     /*session_start();
     
     $login=$_SESSION['login'];*/
    // get all products from products table
    $result = mysql_query ("SELECT created_at FROM commande WHERE login = '$login'") or die(mysql_error());
     
    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
        $response["commande"] = array();
     
        while ($row = mysql_fetch_array($result)) {
            // temp user array
            $product = array();
           // $product["login"] = $row["login"]; 
    	//$commande["cid"] = $row["cid"];
           //$commande["login"] = $row["login"];
          /*$commande["name"] = $row["name"];
            $commande["price"] = $row["price"];
    	$commande["quantite"] = $row["quantite"];*/
     
            $product["created_at"] = $row["created_at"];
            //$commande["somme"] = $row["somme"];
     
     
     
            // push single product into final response array
            array_push($response["commande"], $product);
        }
        // success
        $response["success"] = 1;
     
        // echoing JSON response
        echo json_encode($response);
    }}else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "Aucun Produit trouve";
     
        // echo no users JSON
        echo json_encode($response);
    }

  2. #2
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    Il suffit que ton Web Service en PHP te renvoie plus d'information sous format JSON (toutes ta tables par exemple). Ainsi, lorsque tu récupéreras tes données, tu les parseras et les stockeras dans une base de données SQLLite pour pouvoir les récupérer facilement dans ton application.

    Regardes ce tutoriel qui permet de savoir comment communiquer avec des WS : http://dsilvera.developpez.com/tutor...es-script-php/

Discussions similaires

  1. Réponses: 2
    Dernier message: 16/01/2015, 15h33
  2. [MySQL] Récupération des données sur serveur MySQL
    Par Thibault85 dans le forum PHP & Base de données
    Réponses: 7
    Dernier message: 04/06/2014, 09h38
  3. Récupération des données de formulaire dans une page JSP
    Par fauthie dans le forum Servlets/JSP
    Réponses: 2
    Dernier message: 16/09/2009, 14h02
  4. Réponses: 3
    Dernier message: 26/09/2008, 13h10
  5. Réponses: 33
    Dernier message: 20/08/2008, 14h38

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