6

I am working on an Android code that on click of a button inserts data in a remote database via a web service. My web service code is pretty simple. It just takes in one parameter which is the android Spinner value and inserts that value into the database

I have used HttpClient for posting but I am not able to succeed in doing my task. Can anyone just help me out with this issue?

Here is the web service code:

 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";
 }
 }
 }

Here is my main logic for the Android code:

 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();
 }
 } 

Here is the 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: com.android.internal.view.IInputMethodClient$Stub$Proxy@45004b40
 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: org.apache.http.conn.EofSensorInputStream@44f4a4f8
 11-07 12:20:50.490: DEBUG/dalvikvm(260): GC_EXPLICIT freed 759 objects / 54952 bytes in 1185ms
Konstantin Pribluda
12.3k1 gold badge33 silver badges38 bronze badges
asked Nov 7, 2011 at 7:15
3
  • Anroid logic looks correct (up to unused JSON Object), and I do not see any problems in your logcat snippet. But what happens on server? Can you post server logs too? Commented Nov 10, 2011 at 14:27
  • I men webservice output. It is nature of client-server applications, that they have problem sources on both sides ( and sometimes in the middle ) Commented Nov 10, 2011 at 15:29
  • You could also use something sexier than a plain HttpClient, like Spring Android. See static.springsource.org/spring-android/docs/1.0.x/reference/… , section 2.6.5 is what you would want. Commented Nov 17, 2011 at 11:39

4 Answers 4

2

u r missing these lines most probably : (add them before httpclient.execute)

httppost.setHeader("Accept", "application/json");
 httppost.setHeader("Content-type", "application/json"); OR 
 httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
answered Nov 15, 2011 at 9:48

Comments

1

you may have to set a timeout

you did not defined a content type for the request

and I would use a responsehandler for easier programming with execute command

answered Nov 7, 2011 at 7:22

1 Comment

Yes will add that content type and timeout code . Basically I want that when the data is inserted , I should get some response, that must be "success" as per my web service code and I want to go to next activity after I get "success" . So how should I do that and yea how to use responseHandler?
1

To help isolate the cause of the problem, make the web service return "success" without doing anything else. That way you can verify the httpclient communication with the web service is working properly. Then add back the database logic and continue troubleshooting.

answered Nov 10, 2011 at 18:22

Comments

1

It looks as though the problem is most likely with your web service or the format of the database, since your android code looks correct. If I were you, I would try debugging the web service to locate the problem.

answered Nov 10, 2011 at 18:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.