I want to access mysql database on my localhost via a java servlet through my android app. I was able to access database through a java class but when tried the same code in my android activity, it’s not working. Below is the code for my java servlet, java class through which I successfully accessed my database and android code which isn’t working. In my LogCat log I am getting all the logs till BufferedReader class. Also please tell me which widget can I use in Android to display the response string. I know presently my response string will contain HTML code but that doesn’t matter I just want to know if I am able to access my database. Thank You.
Java Servlet Code:
package org.spark.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet2
*/
@WebServlet("/HelloServlet2")
public class HelloServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
public void service(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Hello World</title></head>");
out.println("<body>");
out.println("<h1>Hello World2</h1>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306", "root", "password");
stmt = con.createStatement();
rs = stmt.executeQuery("Use servlettest");
rs = stmt.executeQuery("SELECT * FROM servlet");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.println("</body></html>");
out.close();
}
}
Java Class Code:
package org.ProjectEuler;
import java.io.*;
import java.net.*;
public class HelloServlet {
public static void main( String [] args ) {
try {
URL url = new URL("http://localhost:8080/HelloServlet/HelloServlet2");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream()));
out.write("username=javaworld\r\n");
out.flush();
out.close();
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream()));
String response;
while ( (response = in.readLine()) != null ) {
System.out.println( response );
}
in.close();
}
catch ( MalformedURLException ex ) {
// a real program would need to handle this exception
}
catch ( IOException ex ) {
// a real program would need to handle this exception
}
}
}
Andriod Code:
package org.spark.mysqltest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;
public class MySqlTestActivity extends Activity {
EditText test;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("checked","checked");
System.out.println("check");
Log.d("checked2","checked2");
test = (EditText) findViewById(R.id.mtv);
Log.d("checked3","checked3");
setContentView(R.layout.main);
Log.d("checked4","checked4");
try {
Log.d("checked5","checked5");
URL url = new URL("http://localhost:8080/HelloServlet/HelloServlet2");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
Log.d("checked6","checked6");
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream()));
Log.d("checked7","checked7");
out.write("username=javaworld\r\n");
Log.d("checke","checke");
out.flush();
Log.d("check","check");
out.close();
Log.d("chec","chec");
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream()));
Log.d("che","che");
String response;
while ( (response = in.readLine()) != null ) {
System.out.println( response );
// test.setText(response);
Log.d("checked8","checked8");
}
Log.d("checked9","checked9");
in.close();
}
catch ( MalformedURLException ex ) {
// a real program would need to handle this exception
}
catch ( IOException ex ) {
// a real program would need to handle this exception
}
}
}
First problem: you aren’t specifying an encoding when you create your
InputStreamReader. That means you’ll use the platform default encoding, which may not be the encoding used to create the web response. (Likewise when you’re creating the request.)Second problem: you’re ignoring any exceptions:
My guess is that an exception is being thrown, but you have no idea because you’ve swallowed those exceptions without even logging. At the very least, add logging in here and I think you’ll see what’s going wrong. You should almost never have empty catch statements like this.
Do you have any reason for using the low-level API like this, by the way? Using a good high-level HTTP client library is likely to make your life a lot simpler.