2011-11-07 11 views
6

Sto lavorando su un codice Android che al clic di un pulsante inserisce i dati in un database remoto tramite un servizio web. Il mio codice di servizio web è piuttosto semplice. Prende solo un parametro che è il valore di Android Spinner e inserisce tale valore nel databaseFeed dati nel database dall'app Android tramite servizio web

Ho usato HttpClient per la pubblicazione ma non sono in grado di eseguire correttamente il mio compito. Qualcuno può aiutarmi con questo problema?

Ecco il codice di servizio Web:

  using System; 
      using System.Collections; 
      using System.ComponentModel; 
      using System.Data; 
      using System.Linq; 
      using System.Web; 
      using System.Web.Services; 
      using System.Web.Services.Protocols; 
      using System.Xml.Linq; 
      using System.Data.SqlClient; 


     namespace putdata 
      { 
     /// <summary> 
     /// Summary description for Service1 
/// </summary> 
[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[ToolboxItem(false)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService] 
public class Service1 : System.Web.Services.WebService 
{ 

    [WebMethod] 
    public String put(String value) 
    { 
     int count=1; 
     int rows; 

     SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123"); 
     try 
     { 
      myConnection.Open(); 
      count++; 
      SqlCommand myCommand = new SqlCommand(); 
      myCommand.Connection = myConnection; 
      myCommand.CommandText = "insert into record values('"+ count +"','" + value + "')"; 
      myCommand.Parameters.Add("@value", SqlDbType.VarChar).Value = value; 
      rows = myCommand.ExecuteNonQuery(); 
      SqlDataReader myReader = myCommand.ExecuteReader(); 

      } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
     finally 
     { 
      myConnection.Close(); 
     } 

     return "success"; 
    } 

     } 
    } 

Qui è la mia logica principale per il codice di Android:

  public void onClick(View v) { 

     String spinnerval1=""; 
     String spinnerval2=""; 

     // Perform action on clicks 
     Toast.makeText(Mark.this, "calling web service", Toast.LENGTH_LONG).show(); 
     if (v == findViewById(R.id.button)) { 
      // prepare the dialog box 
      Button progress = (Button) findViewById(R.id.button); 
      progress.setOnClickListener((OnClickListener) Mark.this); 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://10.0.2.2/enterdata/Service1.asmx"); 


      try 
      { 
      String result; 
      JSONObject obj = new JSONObject(); 
      obj.put("Maths",spinnerval1); 
      obj.put("Science",spinnerval2); 


      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("value1", spinnerval1)); 
      nameValuePairs.add(new BasicNameValuePair("value2", spinnerval2)); 
      httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request 
      HttpResponse httpResponse = httpclient.execute(httppost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 

      if (httpEntity != null) 
      { 
       InputStream is = httpEntity.getContent(); 
       result = is.toString(); 
       Log.i("Result is ", "Result: " + result); 
      } 

      } 

      catch (ClientProtocolException e1) 
      { 
       // TODO Auto-generated catch block 
      } 
      catch (IOException e) { 
       // TODO Auto-generated catch block 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 



      ProgressDialog dialog=new ProgressDialog(Mark.this); 

      // make the progress bar cancelable 
      dialog.setCancelable(true); 

      // set a message text 
      dialog.setMessage("Loading..."); 

      dialog.show(); 

     } 

    }  

Ecco l'logcat:

11-07 12:20:28.970: INFO/ActivityManager(58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example/.Mark } 

    11-07 12:20:29.361: DEBUG/AndroidRuntime(299): Shutting down VM 
    11-07 12:20:29.390: DEBUG/dalvikvm(299): Debugger has detached; object registry had 1 entries 
    11-07 12:20:29.460: INFO/AndroidRuntime(299): NOTE: attach of thread 'Binder Thread #3' failed 
    11-07 12:20:29.470: INFO/ActivityManager(58): Start proc com.example for activity com.example/.Mark: pid=306 uid=10060 gids={3003, 1015} 
    11-07 12:20:31.170: INFO/ActivityManager(58): Displayed activity com.example/.Mark: 1809 ms (total 1809 ms) 
    11-07 12:20:39.341: DEBUG/dalvikvm(127): GC_EXPLICIT freed 1321 objects/73848 bytes in 161ms 
    11-07 12:20:40.981: WARN/InputManagerService(58): Window already focused, ignoring focus gain of: [email protected] 
    11-07 12:20:44.440: DEBUG/dalvikvm(201): GC_EXPLICIT freed 109 objects/9024 bytes in 190ms 
    11-07 12:20:48.840: INFO/Result is(306): Result: [email protected] 
    11-07 12:20:50.490: DEBUG/dalvikvm(260): GC_EXPLICIT freed 759 objects/54952 bytes in 1185ms 
+0

logica Anroid sembra corretto (fino a inutilizzata oggetto JSON), e non vedo alcun problema nel vostro frammento di logcat. Ma cosa succede sul server? Puoi registrare anche i log del server? –

+0

intendi il codice del servizio web? –

+0

Uscita web server uomo. È la natura delle applicazioni client-server, che hanno fonti di problemi su entrambi i lati (e talvolta nel mezzo) –

risposta

2

u r mancano queste linee molto probabilmente: (aggiungerli prima httpclient.execute)

httppost.setHeader("Accept", "application/json"); 
    httppost.setHeader("Content-type", "application/json"); OR 

    httppost.setHeader("Content-type", "application/x-www-form-urlencoded"); 
1

si possono avere impostare un timeout

non hai definito un tipo di contenuto per la richiesta

e vorrei usare un responsehandler per la programmazione più facile con il comando eseguire

+0

Sì aggiungerà quel tipo di contenuto e il codice di timeout. Fondamentalmente voglio che quando i dati sono inseriti, dovrei ottenere una risposta, che deve essere "successo" come per il mio codice di servizio web e voglio andare alla prossima attività dopo aver ottenuto il "successo". Quindi, come dovrei farlo e yea come usare responseHandler? –

1

Per aiutare a isolare la causa del problema, rendono il ritorno servizio web "successo" senza fare qualunque altra cosa. In questo modo è possibile verificare che la comunicazione httpclient con il servizio Web funzioni correttamente. Quindi aggiungere nuovamente la logica del database e continuare la risoluzione dei problemi.

1

Sembra che il problema sia molto probabile con il tuo servizio web o il formato del database, dal momento che il tuo codice Android sembra corretto. Se fossi in te, proverei a eseguire il debug del servizio Web per individuare il problema.

Problemi correlati