簡體   English   中英

如何使用URLconnection將servlet連接到android應用?

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

我正在開發一個Andriod應用程序,以使用java-servlet訪問數據庫。 當我使用sdk 23時,不建議使用某些先前的模塊,因此我在使用URLconnection類來獲取與servlet的連接。 但是通過運行以下代碼,我的應用程序停止運行。

應用程序基於導航抽屜活動構建,並且以下代碼在一個片段類中實現。 是的,我已經設置了網絡權限

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生命周期有關。 由於Fragment及其視圖還不存在,您此時無法(成功)調用findViewById()

例如, 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; 並且僅當您可能需要getOutput的內容時,才獲取最后一個br.readLine()返回的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM