think shra1
think shra1

Reputation: 239

how to pass data from servlet to android application

I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;



/**
 *
 * @author trainee
 */
public class form extends HttpServlet {

String name;
String password;
Connection con = null;
Statement stmt = null;
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

        /* TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet form</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet form at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
        */




@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   try
  {

  }

  catch(Exception ex)
  {

  }
} 

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
     String nn=request.getParameter("name");
     String pass=request.getParameter("pass");
     String email=request.getParameter("email");
     stmt=con.createStatement();
     String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
     int v=stmt.executeUpdate(query);
     ArrayList<String> arr=new ArrayList<String>();
     arr.add("inserted");

System.out.println("sent response back...");

  }
  catch(Exception ex)
  {

  }

}

/** 
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

this is my android application

package org.me.loginandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button) findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    private OnClickListener listener_login = new OnClickListener() {

        boolean check = false;

        public void onClick(View v) {
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText passText = (EditText) findViewById(R.id.password);
            EditText nameText = (EditText) findViewById(R.id.uname);

            String name = nameText.getText().toString();
            String email = (emailText.getText().toString());
            String pass = (passText.getText().toString());

            String result = "";
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("pass", pass));
            nameValuePairs.add(new BasicNameValuePair("email", email));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                TextView lbl = (TextView) findViewById(R.id.lbl);
                lbl.setText(result);
            } catch (Exception e) {
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText("Error parsing data " + e.toString());
                System.out.println("Error parsing data " + e.toString());
            }
            //parse json data
            try {
                boolean check=false;
               ArrayList<String> arrays=new ArrayList<String>();
               for(int i=0;i<arrays.size();i++)
               {
                   if(arrays.get(i).equals("Inserted"))
                   {
                        check=true;
                   }
                   else
                   {
                   }
               }
               if(check)
               {
                   Intent myintent = new Intent(MainActivity.this, welcome.class);
                   startActivity(myintent);
               }
               else
               {
                    TextView tv = (TextView) findViewById(R.id.err);
                    tv.setText("Data was not inserted properly");
               }


            } catch (Exception e) {
                //setContentView(R.layout.notify);
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText(e.toString());
                System.out.println("log_tag" + "Error parsing data ");

            }
        }
    };
}

Upvotes: 4

Views: 24971

Answers (4)

code_fish
code_fish

Reputation: 3428

You can check here. There is a whole description with sample code

Send arraylist from servlet to Android application

Upvotes: 0

nurnachman
nurnachman

Reputation: 4565

first of all, if your doGet() and doPost() do the same thing, you can call one from the other, sending the request and response

Second, you can pass an ArrayList<E> to the android app. Both the Servlet and Android APIs have it

edit: You need to read from a InputStream, generated by a HttpURLConnection object. http://developer.android.com/reference/java/io/InputStream.html

check out this book: used book http://www.amazon.com/Professional-Android-Application-Development-Programmer/dp/0470565527)

String input = getString(R.string.input);
try {
URL url = new URL(input);
URLConnection connection = url.openConnection();
HttpURLConnection http = (HttpURLConnection)connection;
int response = http.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
InputStream is = http.getInputStream();
//do whatever you want with the stream
}
}
catch (MalformedURLException exception) { }
catch (IOException exception) { }

Upvotes: 0

Dead Programmer
Dead Programmer

Reputation: 12575

you can get data from servlet to andriod application through json format. Please go through this
http://wiebe-elsinga.com/blog/?p=405 link to get an idea of how to call Servlet from andriod application and get the response back in json format.

call to Servlet from Andriod

  private InputStream callService(String text) {
          InputStream in = null;
           SERVLET_URL = http://wizkid.com/web/updateServlet";
          try {
               URL url = new URL(SERVLET_URL);
               URLConnection conn = url.openConnection();

               HttpURLConnection httpConn = (HttpURLConnection) conn;
               httpConn.setRequestMethod("POST");
               httpConn.setDoInput(true);
               httpConn.setDoOutput(true);
               httpConn.connect();

               DataOutputStream dataStream = new DataOutputStream(conn
                         .getOutputStream());

               dataStream.writeBytes(text);
               dataStream.flush();
               dataStream.close();

               int responseCode = httpConn.getResponseCode();
               if (responseCode == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();
               }
          } catch (Exception ex) {
               display("Error: Not not connect");
          }
          return in;
     }

// Get Data from Server to andriod

   private String getResultFromServlet(String text) {
          String result = "";

          InputStream in = callService(text);
          if (in != null) {
               JSONObject jsonResponse;
               try {
                    jsonResponse = new JSONObject(convertStreamToString(in));
                    result = jsonResponse.getString("output");
               } catch (JSONException e) {
                    result = "Error: JSON Object couldn't be made";
               }
          } else {
               result = "Error: Service not returning result";
          }
          return result;
     }

Upvotes: 1

KishoreK
KishoreK

Reputation: 962

You need to make a URLConnection to your servlet page and do it. Example for it: How to download file/image from url to your device

Upvotes: 2

Related Questions