Bonjour, dans le cadre de mon projet en entreprise je dois réaliser une application mobile. La majeure partie du sujet est la connexion à une base de données externe existante afin de par exemple récupérer le dernier acheté par un client. J'ai déjà testé plusieurs tuto mais avec les nouvelles versions les techniques changent, et le tuto qui fonctionnait il y a deux ne fonctionne plus aujourd'hui... Je pense avoir le tour de pas mal de tuto mais certains m'ont peut-être échappé. Pourriez-vous m'aider en me donnant un tuto plus récent ou tout simplement des explications. Merci d'avance.
Bonjour, là je pense que mon code est un plus lisible. Voici mon logcat
Entre temps j'ai essayé de trouver des solutions sur internet mais je n'ai toujours pas trouvé de solution, déjà ce code si j'ai bien compris, il ne fonctionnait que pour Android 1.0. Il faut dorénavant passer par des threads ou AsyncTask mais j'ai toujours passé à avoir accès à ma bdd
Salut, Oui j'ai remarqué ça que tardivement, mon entreprise voudrait que je passe par un web service pour avoir accès à la base de données. J'ai essayé de faire une appli sans requête et elle fonctionne correctement. J'ai voulu adapter le code pour effectuer des requêtes mais je ne m'y prends pas bien du tout.
package com.esi.asynctaskdemo;
import java.util.Random;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private static final long PASSWORD = 12345;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick_StartTask(View v){
final long PUBLISH_RATE = 1000;
final long RANGE = 100000;
PasswordGuesserTask crackerTask = new PasswordGuesserTask();
crackerTask.execute(RANGE, PUBLISH_RATE);
}
public void displayProgress(String message){
TextView textView = (TextView) findViewById(R.id.txtStatus);
textView.setText(message);
}
public void displayAnswer(long answer){
String message = "I know the password: "+ answer;
TextView textView = (TextView) findViewById(R.id.txtFinalAnswer);
textView.setText(message);
}
private class PasswordGuesserTask extends AsyncTask<Long, String, Long>{
@Override
protected Long doInBackground(Long... params) {
// Run on background thread
long range = params[0];
long publishRate = params[1];
long guess = 0;
long count = 0;
Random rand = new Random();
while (guess != PASSWORD){
guess = Math.abs(rand.nextLong()) % range;
count ++;
if(count % publishRate == 0){
publishProgress("guess #: " + count,
"Last guess:" + guess);
}
}
return guess;
}
// Executed on main UI thread
@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
String message = "";
for (String str : values){
message += str + "," ;
} displayProgress(message);
}
@Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
displayAnswer(result);
}
}
}
Les tutos sur Internet pour effectuer une effectuer une requete via un web service sont très peu nombreux. Je pensais le voir à l'iut mais finalement la prof a dit que c'était trop complexe donc on le fera pas mais j'en ai toujours besoin pour l'entreprise
package com.esi.intentservicedemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
String[] mCountry = new String[] { "India", "Pakistan", "Bangladesh",
"Srilanka", "Nepal", "China", "Japan", "South Korea",
"North Korea", "Afghanistan" };
Spinner mSprCountry;
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adapter for Country Spinner
mAdapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.spinner_layout, mCountry);
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
// Getting reference to Country Spinner
mSprCountry = (Spinner) findViewById(R.id.spr_country);
// Setting adapter for the Country Spinner
mSprCountry.setAdapter(mAdapter);
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(),
CapitalService.class);
mSprCountry.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (arg1 != null) {
String country = ((TextView) arg1).getText().toString();
mServiceIntent.putExtra(Constants.EXTRA_COUNTRY, country);
// Starting the CapitalService to fetch the capital of the
// country
startService(mServiceIntent);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent
// filter
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(mReceiver, mFilter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Defining a BroadcastReceiver
private class CapitalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_CAPITAL);
mTvCapital.setText("Capital : " + capital);
}
}
}
CapitalService.java
package com.esi.intentservicedemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class CapitalService extends IntentService{
public CapitalService(){
super("Empty Constructor");
}
public CapitalService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
// This method is executed in background when this service is started
@Override
protected void onHandleIntent(Intent intent) {
String country = "";
String capital = "";
String url = "";
try {
country = URLEncoder.encode(intent.getStringExtra(Constants.EXTRA_COUNTRY),"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
url = Constants.SERVER_URL + "/get_capital.php?country=" + country;
try {
// Retreiving capital from the url
capital = downloadUrl(url);
// Creating an intent for broadcastreceiver
Intent broadcastIntent = new Intent(Constants.BROADCAST_ACTION);
// Attaching data to the intent
broadcastIntent.putExtra(Constants.EXTRA_CAPITAL, capital);
// Sending the broadcast
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/** A method to download data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while fetching data", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
Constants.java
package com.esi.intentservicedemo;
public class Constants {
public static final String BROADCAST_ACTION = "in.wptrafficanalyzer.intentservicedemo.BROADCAST";
public static final String EXTRA_COUNTRY = "country";
public static final String EXTRA_CAPITAL = "capital";
// The url to the server where php script for capital is available
public static final String SERVER_URL = "http://192.168.3.53/get_capital.php";
}
L'application ne plante pas mais la capital n'est pas affichée dans le textview sous le la listbox. Je viens de tester mon fichier php, lorsque dans l'url je mets: http://192.168.3.53/get_capital.php?country=Japan Cela affiche bien Tokyo sur mon navigateur.
Voilà j'ai enfin trouvé ce que je voulais. Pour les erreurs précédentes je n'ai pas trouvé de solutions mais j'ai un code fonctionnelle pour l'utilisation d'un web server. Je mets ce post en résolu. http://programmerguru.com/android-tutorial/android-webservice-example/
Bonjour dans le cadre de mon memoire de fin d'etude je suis entrain de concevoir une application mobile pour la localisation des permanence des soins j'aimerais savoir comment faire le coté administrateur . y'a une appli dédié aux public j'aimerais savoir quelle sont les outils pour administrer la base de donnée externe de cette application (pour la modifié ajouter supprimer .. svp )
[ANDROID] Connexion à une base de données externe
× Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
× Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
Mon site - Mon livre sur le XML - Mon blog
Bonjour, là je pense que mon code est un plus lisible. Voici mon logcat
Mon site - Mon livre sur le XML - Mon blog
Les tutos sur Internet pour effectuer une effectuer une requete via un web service sont très peu nombreux. Je pensais le voir à l'iut mais finalement la prof a dit que c'était trop complexe donc on le fera pas mais j'en ai toujours besoin pour l'entreprise
Mon site - Mon livre sur le XML - Mon blog
Mon site - Mon livre sur le XML - Mon blog
Mon site - Mon livre sur le XML - Mon blog