2016-04-01 19 views
0

私はjava-servletを使用してデータベースにアクセスするAndriodアプリを開発しています。 私はsdk 23を使用しているので、以前のいくつかのモジュールは廃止予定です。そのため、URL接続クラスを使用してサーブレットに接続しています。 しかし、以下のコードを実行すると、私のアプリは動作しなくなります。URLconnectionを使用してAndroidアプリにサーブレットを接続するにはどうすればよいですか?

アプリケーションはナビゲーション引き出しアクティビティに基づいており、以下のコードは1つのフラグメントクラスに実装されています。はい、ネットワークのアクセス許可を設定しました

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

以下のコードは完全に動作するサーブレット用です。

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> 

} 
+0

これは動作を停止することを意味しますか? –

+0

同様に、ポップアップが表示されます。残念ながら、あなたのアプリは動作を停止しました –

+0

この場合、デバッグコンソールにスタックトレースが表示されます。その情報は、問題の発生元を特定する上で重要です。 –

答えて

1

スタックトレースは、おそらく明確に問題がコード行であることを指摘します:

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()が返さものを手に入れるということです。

+0

答えをくれてありがとうが、私もそれを試みましたが、接続できませんでした@ MarkusKauppinen –

関連する問題