简体   繁体   English

如何使用URLconnection将servlet连接到android应用?

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

I am developing an Andriod app to access database using java-servlet. 我正在开发一个Andriod应用程序,以使用java-servlet访问数据库。 As I'm using sdk 23 some previous modules are deprecated, so I'm using URLconnection class to get connection to servlet. 当我使用sdk 23时,不建议使用某些先前的模块,因此我在使用URLconnection类来获取与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. 下面的代码适用于servlet,它可以正常工作。

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>

}

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. 问题与Fragment生命周期有关。 You just can't (succesfully) call findViewById() at that point as the Fragment and its views don't really exist yet. 由于Fragment及其视图还不存在,您此时无法(成功)调用findViewById()

For example the onViewCreated() method would be a safe place to call findViewById() . 例如, onViewCreated()方法将是调用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; 然后另一个问题是您分配str = line; and only get what the last br.readLine() returned when you probably want the contents of the getOutput . 并且仅当您可能需要getOutput的内容时,才获取最后一个br.readLine()返回的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM