Nirmal Purohit
Nirmal Purohit

Reputation: 67

How do i connect a servlet to android app using URLconnection.?

I am developing an Andriod app to access database using java-servlet. As I'm using sdk 23 some previous modules are deprecated, so I'm using URLconnection class to get connection to servlet. But By running below code, my app stops working.

App is built upon Navigation drawer activity and below code is implemented in one fragment class. And yes I've set permissions for network

package com.example.nirmal.gaminghub;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.lang.Object;

public class GameList extends Fragment {


TextView gm_lst=(TextView)getView().findViewById(R.id.game_list);
Button show;
String str ="" ;

public GameList() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    new AsyncTask<String, String, String>() {
        protected String doInBackground(String... url) {
            try {
                URL openUrl = new URL("http://localhost:8080/GamingHub/ShowDataServlet");
                HttpURLConnection connection = (HttpURLConnection) openUrl.openConnection();
                connection.setDoInput(true);
              //  Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG).show();
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line = "";
                StringBuilder getOutput = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    getOutput.append(line);
                }
                br.close();
                str=line;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return str;
        }

        protected void OnPostExecute(String otpt)
        {
            gm_lst.setText(otpt);
        }
    }.execute();
    gm_lst.setText(str);
    return inflater.inflate(R.layout.fragment_game_list, container, false);
   }
 }

Below code is for servlet, which is working perfectly.

package com.gaming_hub;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


 public class ShowDataServlet extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ClassNotFoundException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
         Class.forName("com.mysql.jdbc.Driver"); 

        Connection con=DriverManager.getConnection(  
            "jdbc:mysql://localhost:3306/gaming_hub","root","");
        String sql="SELECT * from games";
        PreparedStatement ps=con.prepareStatement(sql);
        ResultSet rs=ps.executeQuery();

       // DataOutputStream dout=new DataOutputStream();
        while(rs.next())
        {
            out.println(rs.getString(1));
        }

    }
}


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}


@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

Upvotes: 0

Views: 3533

Answers (1)

Markus Kauppinen
Markus Kauppinen

Reputation: 3235

The stack trace would probably clearly point out that the problem is with the code line:

TextView gm_lst=(TextView)getView().findViewById(R.id.game_list);

The problem has to do with the Fragment lifecycle. You just can't (succesfully) call findViewById() at that point as the Fragment and its views don't really exist yet.

For example the onViewCreated() method would be a safe place to call findViewById(). So you could try something like:

public class GameList extends Fragment {


TextView gm_lst;
Button show;
String str ="" ;

public GameList() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_game_list, container, false);
   }
 }

 @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    gm_lst = (TextView)getView().findViewById(R.id.game_list);

    new AsyncTask<String, String, String>() {
        protected String doInBackground(String... url) {
            try {
                URL openUrl = new URL("http://localhost:8080/GamingHub/ShowDataServlet");
                HttpURLConnection connection = (HttpURLConnection) openUrl.openConnection();
                connection.setDoInput(true);
              //  Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG).show();
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line = "";
                StringBuilder getOutput = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    getOutput.append(line);
                }
                br.close();
                str=line;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return str;
        }

        protected void OnPostExecute(String otpt)
        {
            gm_lst.setText(otpt);
        }
    }.execute();
    gm_lst.setText(str);

    }

And then a separate issue is that you assign str = line; and only get what the last br.readLine() returned when you probably want the contents of the getOutput.

Upvotes: 1

Related Questions