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 :

Consommation de WebService et ProgressBar


Sujet :

Android

  1. #1
    Membre éclairé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2007
    Messages
    387
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2007
    Messages : 387
    Par défaut Consommation de WebService et ProgressBar
    Bonjour,

    Je souhaiterais mettre en place un loader pour un appel à un WebService Rest JSON.

    J'ai vu pas mal de réponses sur internet qui demandent d'utiliser "AsyncTask".

    J'ai donc mis en place "AsyncTask", mais le problème est que lors de l'appel au WebService le loader n'est pas affiché.

    Si je commente les lignes "mailboxThread.start();mailboxThread.join();" et "dialog.dismiss();" le loader apparait bien (éternellement du fait du commentage de "dismiss"). C'est donc bien l'appel au WebService qui pose problème.

    Le problème viendrait-il du fait que "MailboxThread" étend "Thread" et se mettrait donc en conflit avec "AsynkTask" ?

    Merci d'avance pour votre aide.

    Cordialement.

    NB : "ActionBarWindow" est une fenêtre permettant la gestion de "ActionbarSherlock".

    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
     
    public class NewMailboxActivity extends ActionBarWindow implements OnTouchListener, Handler.Callback
    {
    	protected LoadingTask loader;
     
    	class LoadingTask extends AsyncTask<Void, Void, Void>
    	{
    		Exception failure;
    		ProgressDialog dialog = null;
    		ArrayList<Hashtable<String, String>> values;
     
    		public Void doInBackground(Void... params)
    		{
    			this.failure = null;
    			this.values = new ArrayList<Hashtable<String, String>>();
    			try
    			{
    				dialog = new ProgressDialog(NewMailboxActivity.this);
    				dialog.setMessage("Test");
    				dialog.show();
     
    				 mailboxThread.start();
    				 mailboxThread.join();
    			} catch (Exception ex)
    			{
    				Log.e("MONAPP", "Failed to retrieve JSON list", ex);
    				this.failure = ex;
    			} finally
    			{
    				NewMailboxActivity.this.loader = null;
    				 dialog.dismiss();
    			}
    			return null;
    		}
     
    		public void onPostExecute(Void result)
    		{
    			 dialog.dismiss();
    		}
    	}
     
    	private static final String TAG = "NewMailboxActivity Display";
     
    	private Intent m_intent;
     
    	@Override
    	public void onCreate(Bundle savedInstanceState)
    	{
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.mailbox);
     
    		m_intent = getIntent();
    	}
     
    	public void submitForm(View v)
    	{
    		try
    		{
    			String url = "mon_url";
     
    			mailboxThread = new MailboxThread(url);
    			Log.v(TAG, " OK PROGRESS");
    			this.loader = new LoadingTask();
    			this.loader.doInBackground(null);
    			m_errorContent = mailboxThread.getError();
    			m_resultContent = mailboxThread.getResult();
    			if (m_errorContent != null || m_resultContent != null)
    			{
    				try
    				{
    					if (m_errorContent != null && m_errorContent.getString("parameter").compareToIgnoreCase("") != 0)
    					{
    						AlertDialog.Builder builder = new AlertDialog.Builder(NewMailboxActivity.this);
    						String errorLabel = "";
    						String errorCode = m_errorContent.getString("parameter");
    						String errorText = m_errorContent.getString("message");
    						InternationalizeUtility internationalizeUtility = new InternationalizeUtility();
    						errorLabel = internationalizeUtility.getResultFromCode(NewMailboxActivity.this, errorCode, errorText);
    						if (errorCode.compareToIgnoreCase("unable_to_connect_with_this_login_and_password") == 0)
    						{
    							if (m_imapAuthorized == false)
    							{
    								errorLabel = getString(R.string.imap_unauthorized);
    							}
    						}
    						// R.string.errorLabel;
    						builder.setMessage(errorLabel).setCancelable(false).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener()
    						{
    							public void onClick(DialogInterface dialog, int id)
    							{
    							}
    						});
     
    						AlertDialog alert = builder.create();
    						alert.show();
     
    					} else
    					{
    						// Aucune erreur n'a été rencontrée
    						// Récupération des données :
    						if (m_resultContent.has("account_id") && m_resultContent.has("mailbox_id"))
    						{
    							m_intent = new Intent();
    							m_intent.setClass(NewMailboxActivity.this, SettingActivity.class);
    							startActivity(m_intent);
    						} else
    						{
    							AlertDialog.Builder builder = new AlertDialog.Builder(NewMailboxActivity.this);
    							String errorLabel = "";
    							String errorCode = "internal_error";
    							String errorText = "internal error";
    							InternationalizeUtility internationalizeUtility = new InternationalizeUtility();
    							errorLabel = internationalizeUtility.getResultFromCode(NewMailboxActivity.this, errorCode, errorText);
    							// R.string.errorLabel;
    							builder.setMessage(errorLabel).setCancelable(false).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener()
    							{
    								public void onClick(DialogInterface dialog, int id)
    								{
    								}
    							});
     
    							AlertDialog alert = builder.create();
    							alert.show();
    						}
     
    						// startActivity(m_intent);
    					}
    				} catch (JSONException e)
    				{
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
     
    		} catch (Exception e)
    		{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
     
    	@Override
    	public boolean handleMessage(Message msg)
    	{
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    	@Override
    	public boolean onTouch(View v, MotionEvent event)
    	{
    		// TODO Auto-generated method stub
    		return false;
    	}
    }
    Le code du Thread appelé :

    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
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.protocol.HTTP;
    import org.json.JSONException;
    import org.json.JSONObject;
     
    import android.util.Log;
     
    public class MailboxThread extends Thread
    {
    	private static final String TAG = "MailboxThread";
     
    	private JSONObject m_error = null;
    	private JSONObject m_result = null;
    	private String m_urlStr;
     
     
    	public MailboxThread(String urlStr)
    	{
    		m_urlStr = urlStr;
    	}
     
    	public JSONObject getError()
    	{
    		return m_error;
    	}
     
    	public JSONObject getResult()
    	{
    		return m_result;
    	}
     
    	public void run()
    	{
    		Log.v(TAG, "Text : " + m_urlStr);
     
    		HttpClient httpClient = new DefaultHttpClient();
    		try
    		{
    			HttpPost httpPost = new HttpPost(m_urlStr);
    			JSONObject entry = new JSONObject();
    			entry.put("toto", "toto");
     
    			StringEntity entity = new StringEntity(entry.toString());
    			Log.i(TAG, entry.toString());
     
    			entity.setContentType("application/json;charset=utf-8");
    			entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"));
    			httpPost.setEntity(entity);
     
    			HttpResponse httpResponse = httpClient.execute(httpPost);
     
    			int statusCode = httpResponse.getStatusLine().getStatusCode();
    			Log.i(TAG, "Code retour : " + statusCode);
     
    			HttpEntity httpEntity = httpResponse.getEntity();
    			if (httpEntity != null)
    			{
    				InputStream inputStream = httpEntity.getContent();
     
    				// Lecture du retour au format JSON
    				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    				StringBuilder stringBuilder = new StringBuilder();
     
    				String ligneLue = bufferedReader.readLine();
    				while (ligneLue != null)
    				{
    					stringBuilder.append(ligneLue + "\n");
    					ligneLue = bufferedReader.readLine();
    				}
    				bufferedReader.close();
    				inputStream.close();
     
    				// TMP
    				String str2 = stringBuilder.toString();
    				Log.i(TAG, str2);
     
    				// Analyse du retour
    				JSONObject jsonObject = new JSONObject(stringBuilder.toString());
    				if (jsonObject.has("error"))
    				{
    					JSONObject jsonResultSetError = jsonObject.getJSONObject("error");
    					// if (jsonResultSetError != null)
    					// {
    					Log.i(TAG, "OK ERROR");
    					m_error = jsonResultSetError;
    				} else
    				{
    					Log.i(TAG, "OK PAS ERROR");
    					m_result = jsonObject;
    				}
    			}
     
    		} catch (IOException e)
    		{
    			Log.e(TAG, e.getMessage());
    		} catch (JSONException e)
    		{
    			Log.e(TAG, e.getMessage());
    		}
    	}
    }

  2. #2
    Membre éclairé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2007
    Messages
    387
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2007
    Messages : 387
    Par défaut
    Comme pré-senti, le Thread à l'intérieur d'une "AsyncTask", ça ne passe pas bien.

    Voici le code qui fonctionne parfaitement avec la gestion d'une "AlertDialog" en cas de message d'erreur.

    Si ça peut aider quelqu'un par la suite ...

    Cordialement.

    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
     
     
    public class NewMailboxActivity extends ActionBarWindow implements OnTouchListener, Handler.Callback
    {
     
    	protected String m_url = "";
     
    	private class GrabURL extends AsyncTask<String, Void, Void>
    	{
    		private ProgressDialog dialog = new ProgressDialog(NewMailboxActivity.this);
    		private String errorMessage = "";
     
    		protected void onPreExecute()
    		{
    			dialog.setMessage(getString(R.string.loadingMessage));
    			dialog.setCanceledOnTouchOutside(false);
    			dialog.setCancelable(false);
    			dialog.show();
    		}
     
    		protected Void doInBackground(String... urls)
    		{
    			try
    			{
    				HttpClient httpclient = new DefaultHttpClient();
     
    				HttpPost httppost = new HttpPost(m_url);
     
    				JSONObject entry = new JSONObject();
    				entry.put("toto", "toto");
    				StringEntity entity = new StringEntity(entry.toString());
    				Log.i(TAG, entry.toString());
     
    				entity.setContentType("application/json;charset=utf-8");
    				entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"));
     
    				httppost.setEntity(entity);
     
    				HttpResponse httpResponse = httpclient.execute(httppost);
    				int statusCode = httpResponse.getStatusLine().getStatusCode();
    				Log.i(TAG, "Code retour : " + statusCode);
     
    				HttpEntity httpEntity = httpResponse.getEntity();
    				if (httpEntity != null)
    				{
    					InputStream inputStream = httpEntity.getContent();
     
    					// Lecture du retour au format JSON
    					BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    					StringBuilder stringBuilder = new StringBuilder();
     
    					String ligneLue = bufferedReader.readLine();
    					while (ligneLue != null)
    					{
    						stringBuilder.append(ligneLue + "\n");
    						ligneLue = bufferedReader.readLine();
    					}
    					bufferedReader.close();
    					inputStream.close();
     
    					// TMP
    					String str2 = stringBuilder.toString();
    					Log.i(TAG, str2);
     
    					// Analyse du retour
    					JSONObject jsonObject = new JSONObject(stringBuilder.toString());
    					if (jsonObject.has("error"))
    					{
    						JSONObject jsonResultSetError = jsonObject.getJSONObject("error");
    						// if (jsonResultSetError != null)
    						// {
    						Log.i(TAG, "OK ERROR");
    						m_errorContent = jsonResultSetError;
    					} else
    					{
    						Log.i(TAG, "OK PAS ERROR");
    						m_resultContent = jsonObject;
    					}
     
    					if (m_errorContent != null || m_resultContent != null)
    					{
    						try
    						{
    							if (m_errorContent != null && m_errorContent.getString("parameter").compareToIgnoreCase("") != 0)
    							{
    								String errorCode = m_errorContent.getString("parameter");
    								String errorText = m_errorContent.getString("message");
    								InternationalizeUtility internationalizeUtility = new InternationalizeUtility();
    								errorMessage = internationalizeUtility.getResultFromCode(NewMailboxActivity.this, errorCode, errorText);
     
    							} else
    							{
    								// Aucune erreur n'a été rencontrée
    								// Récupération des données :
    								if (m_resultContent.has("account_id") && m_resultContent.has("mailbox_id"))
    								{
    									m_intent = new Intent();
    									m_intent.setClass(NewMailboxActivity.this, SettingActivity.class);
    									startActivity(m_intent);
    								} else
    								{
    									errorMessage = getString(R.string.internal_error);
    								}
    							}
    						} catch (JSONException e)
    						{
    							errorMessage = getString(R.string.internal_error);
    							e.printStackTrace();
    						}
    					}
    				}
     
    			} catch (Exception e)
    			{
    				errorMessage = getString(R.string.internal_error);
    				Log.e(TAG, "Error in http connection " + e.toString());
    			}
     
    			return null;
     
    		}
     
    		protected void onPostExecute(Void unused)
    		{
     
    			dialog.dismiss();
    			if (errorMessage.compareToIgnoreCase("") != 0)
    			{
    				AlertDialog.Builder builder = new AlertDialog.Builder(NewMailboxActivity.this);
    				builder.setMessage(errorMessage).setCancelable(false).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener()
    				{
    					public void onClick(DialogInterface dialog, int id)
    					{
    					}
    				});
     
    				AlertDialog alert = builder.create();
    				alert.show();
     
    			}
     
    		}
    	}
     
    	private static final String TAG = "NewMailboxActivity Display";
     
    	private Intent m_intent;
     
    	@Override
    	public void onCreate(Bundle savedInstanceState)
    	{
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.mailbox);
     
    		m_actionBar.setSubtitle(R.string.new_mailbox);
     
    		m_intent = getIntent();
    	}
     
    	public void submitForm(View v)
    	{
    		try
    		{
    			m_url = "mon_url";
     
    			GrabURL grab = new GrabURL();
    			grab.execute(m_url);
    		} catch (Exception e)
    		{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
     
    	@Override
    	public boolean handleMessage(Message msg)
    	{
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    	@Override
    	public boolean onTouch(View v, MotionEvent event)
    	{
    		// TODO Auto-generated method stub
    		return false;
    	}
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [C#] Consommer un WebService sans savoir d'avance l'URL
    Par SoaB dans le forum Services Web
    Réponses: 7
    Dernier message: 20/02/2008, 17h11
  2. Consommer un webservice asp.net depuis soap::lite
    Par bleuerouge dans le forum Web
    Réponses: 0
    Dernier message: 11/01/2008, 15h17
  3. consommer des webservices : client standalone
    Par NullPointerException dans le forum Services Web
    Réponses: 1
    Dernier message: 07/01/2008, 16h26
  4. [CF][C#] Comment consommer un WebService sur PPC ?
    Par Jérôme Lambert dans le forum Windows Mobile
    Réponses: 1
    Dernier message: 21/02/2006, 11h04
  5. Consommer un WebService en C++
    Par FunnyDjo dans le forum MFC
    Réponses: 4
    Dernier message: 12/12/2005, 20h31

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