Android - AsyncTask

jasmine jas - Modifié par BunoCS le 6/06/2016 à 15:12
BunoCS Messages postés 15316 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 3 octobre 2022 - 6 juin 2016 à 15:12
Bonjour,
alors se que j’essaye de réaliser est de choisir une données dans le spinner et l’envoyer a la base dans le serveur voici mon code pour mieux comprendre ,

se code m'affiche les données mais de l'envoyer a la base s marche pas




import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

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.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity
{

private ProgressDialog pDialog ;
JSONParser jsonParser = new JSONParser();
EditText inputid;
Spinner inputnom;
EditText inputprix;
EditText inputdesc;
Button btnCreateProduct;
InputStream is=null;
String result=null;
String line=null;
String[] client , codclient ,prod ,codprd;
String[] codeclient,nomclient;
Spinner spinner1,spinner2,spinner3,spinner4;
EditText code ;
Button choisirProduit ;
//private static String url_posteproduct = "http://192.168.1.16/createPRODUCT2.php";
//private static final String TAG_SUCCESS = "success";
//*************



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCreateProduct = (Button) findViewById(R.id.ajouter);

btnCreateProduct.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
// new CreateNewProduct().execute();
}
});


inputnom = (Spinner) findViewById(R.id.spinner1);
// inputid = (EditText) findViewById(R.id.btnid);



final List<String> list1 = new ArrayList<String>();


// TODO Auto-generated method stub

try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.16/VILLEE.php");
HttpResponse response = httpclient.execute(httppost);
Log.e("Fail 1", "3");

HttpEntity entity = response.getEntity();
Log.e("Fail 1", "4");

is = entity.getContent();
Log.e("Pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",Toast.LENGTH_LONG).show();
finish();
}

try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}


try
{
JSONArray JA=new JSONArray(result);
JSONObject json= null;
client = new String[JA.length()];
codclient = new String[JA.length()];

for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
client[i] = json.getString("D_VILLE");



}

Toast.makeText(getApplicationContext(), "sss", Toast.LENGTH_LONG).show();

for(int i=0;i< client.length;i++)
{
list1.add(client[i]);

}

spinner_fn();

}
catch(Exception e)
{

Log.e("Fail 3", e.toString());
//login.this.finish();

}
}



private void spinner_fn() {
// TODO Auto-generated method stub

ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, client);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()

{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{}

@Override
public void onNothingSelected(AdapterView<?> arg0){}


}); }





class CreateNewProduct extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("patientez svp..");


pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

protected String doInBackground(String... args) {


String nom = inputnom.getSelectedItem().toString();


//
List<NameValuePair> params = new ArrayList<NameValuePair>();


params.add(new BasicNameValuePair("NAME", nom));


//
//
JSONObject json = jsonParser.makeHttpRequest(url_posteproduct, "POST", params);


//
Log.d("Create Response", json.toString());

try {
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
// succes created product
Intent i = new Intent(getApplicationContext(), Afficher_listCL.class);
startActivity(i);


finish();
}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}


protected void onPostExecute(String file_url) {

pDialog.dismiss();
}
}






@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;

}

}


dés que je clic sur le button pour envyer la données choisi , j'aurai les erreur suivante
06-06 12:52:49.755      904-904/riro15.exemple_web_service E/Fail 1﹕ 3
06-06 12:52:49.755 904-904/riro15.exemple_web_service E/Fail 1﹕ 4
06-06 12:52:49.775 904-904/riro15.exemple_web_service E/Pass 1﹕ connection success
06-06 12:52:58.626 904-916/riro15.exemple_web_service E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Caused by: java.lang.NullPointerException
at riro15.exemple_web_service.petitessai$CreateNew.doInBackground(petitessai.java:197)
at riro15.exemple_web_service.petitessai$CreateNew.doInBackground(petitessai.java:183)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
            at java.util.concurrent.FutureTask.run(FutureTask.java:138)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
            at java.lang.Thread.run(Thread.java:1019)
06-06 12:53:02.455 904-904/riro15.exemple_web_service E/WindowManager﹕ Activity riro15.exemple_web_service.petitessai has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40573668 that was originally added here
android.view.WindowLeaked: Activity riro15.exemple_web_service.petitessai has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40573668 that was originally added here
at android.view.ViewRoot.<init>(ViewRoot.java:258)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at riro15.exemple_web_service.petitessai$CreateNew.onPreExecute(petitessai.java:191)
at android.os.AsyncTask.execute(AsyncTask.java:391)
at riro15.exemple_web_service.petitessai$1.onClick(petitessai.java:75)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)


svp c urgent aidez moi svp

1 réponse

BunoCS Messages postés 15316 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 3 octobre 2022 103
6 juin 2016 à 15:12
Hello,

As-tu essayé en mode debug pas-à-pas pour voir ce qu'il se passe?
Tu ne passes pas de paramètres à ton AsyncTask...or, d'après la signature, tu devrais lui passer des Strings.

https://developer.android.com/reference/android/os/AsyncTask.html
0