gpt4 book ai didi

java - 如何使用 URLconnection 将 servlet 连接到 android 应用程序?

转载 作者:行者123 更新时间:2023-12-01 10:07:20 26 4
gpt4 key购买 nike

我正在开发一个 Andriod 应用程序来使用 java-servlet 访问数据库。由于我使用的是 sdk 23,所以以前的一些模块已被弃用,因此我使用 URLconnection 类来连接到 servlet。但是通过运行下面的代码,我的应用程序停止工作。

应用程序是基于抽屉导航 Activity 构建的,下面的代码在一个 fragment 类中实现。是的,我已经设置了网络权限

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

下面的代码是针对 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>

}

最佳答案

堆栈跟踪可能会清楚地指出问题出在代码行上:

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

问题与 Fragment 生命周期有关。此时您无法(成功)调用 findViewById(),因为 Fragment 及其 View 尚未真正存在。

例如,onViewCreated() 方法是调用 findViewById() 的安全位置。所以你可以尝试这样的事情:

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

}

然后一个单独的问题是,当您分配 str = line; 时,只有当您可能想要的内容时才获取最后一个 br.readLine() 返回的内容获取输出

关于java - 如何使用 URLconnection 将 servlet 连接到 android 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com