2016-12-18 6 views
1

フラグメントからjsonタスクにデータを渡してサーブレットに渡す必要があります。私はフラグメント、クラス、サーブレットのコードを含んでいます。フラグメントからサーブレットにデータを渡す

public class Home extends Fragment { 

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


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     ListView lvAccountSummary; 

     Bundle bundle = getActivity().getIntent().getExtras(); 
     String userId = bundle.getString("userName"); 
     Toast.makeText(getActivity().getApplicationContext(),userId,Toast.LENGTH_SHORT).show(); 
     View view = inflater.inflate(R.layout.fragment_home,container,false); 
     lvAccountSummary = (ListView) view.findViewById(R.id.lvAccountSummary); 
     new JSONTask(view.getContext(), lvAccountSummary).execute("http://localhost:8080/examples/examplesSummary"); 
     return view; 
    } 

} 

あなたは

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
    //String userName; 
    System.out.println("++++++++++++++++++++"+(String)request.getParameter("userId")); 
    ... 
} 
+0

あなたはサーブレットにuserIdを渡していません。 –

+0

ありがとうK Neeraj Lalさん、私の質問で私を助けることができます –

+0

サーブレットにuserIdを渡すには –

答えて

0

これは、フラグメント

public class JSONTask extends AsyncTask<String,String,List<SummaryModel>> { 
    private ListView lvSummary; 
    private Context mContext; 
    private ProgressDialog dialog; 
    public JSONTask(Context context, ListView lstView){ 
     this.lvSummary = lstView; 
     this.mContext = context; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     dialog = new ProgressDialog(mContext); 
     dialog.setIndeterminate(true); 
     dialog.setCancelable(false); 
     dialog.setMessage("Loading. Please wait..."); 
     dialog.show(); 
    } 

    @Override 
    protected List<SummaryModel> doInBackground(String... params) { 
     HttpURLConnection connection = null; 
     BufferedReader reader = null; 
     try { 
      URL url= new URL(params[0]); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("POST"); 
      connection.connect(); 
      InputStream stream = connection.getInputStream(); 
      reader = new BufferedReader(new InputStreamReader(stream)); 
      StringBuffer buffer = new StringBuffer(); 
      String line =""; 
      while ((line = reader.readLine())!=null){ 
       buffer.append(line); 
      } 
      String finalJason = buffer.toString(); 

      JSONObject parentObject = new JSONObject(finalJason); 
      JSONArray parentArray = parentObject.getJSONArray("account"); 

      List<SummaryModel> accountModelList = new ArrayList<>(); 

      Gson gson = new Gson(); 

      for (int i=0; i<parentArray.length();i++) { 
       JSONObject finalObject = parentArray.getJSONObject(i); 
       SummaryModel summaryModel = gson.fromJson(finalObject.toString(),SummaryModel.class); 
       accountModelList.add(summaryModel); 
      } 
      return accountModelList; 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } finally { 
      if (connection != null) { 
       connection.disconnect(); 
      } 
      try { 
       if (reader != null) { 
        reader.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(List<SummaryModel> result) { 
     super.onPostExecute(result); 
     dialog.dismiss(); 
     AccountAdapter adapter = new AccountAdapter(mContext,R.layout.row,result); 
     try { 
      lvSummary.setAdapter(adapter); 
     } catch (Exception e){ 
      Toast.makeText(mContext,"No Internet Connection",Toast.LENGTH_SHORT).show(); 
     } 
      //TODO need to set data to the list 
    } 
} 

上のサーブレットやディスプレイからデータを取得し、次のようなJSON作業です。しかし、私は、サーブレットからのuserIdを呼び出すとき、私はNULL値を取得しますリクエストでuser_idを渡さないようにして、サーブレットでuser_idを取得しないようにしてください。以下のコードを試してください:

@Override 
     protected List<SummaryModel> doInBackground(String... params) { 

Map<String,Object> params = new LinkedHashMap<>(); 
     params.put("userId", "12"); 


     StringBuilder postData = new StringBuilder(); 
     for (Map.Entry<String,Object> param : params.entrySet()) { 
      if (postData.length() != 0) postData.append('&'); 
      postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); 
      postData.append('='); 
      postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); 
     } 
     byte[] postDataBytes = postData.toString().getBytes("UTF-8"); 


      HttpURLConnection connection = null; 



      BufferedReader reader = null; 
      try { 
       URL url= new URL(params[0]); 
       connection = (HttpURLConnection) url.openConnection(); 
       connection.setRequestMethod("POST"); 
       connection.setRequestProperty("Content-Length",   String.valueOf(postDataBytes.length)); 
     connection.setDoOutput(true); 
     connection.getOutputStream().write(postDataBytes); 
       connection.connect(); 
       InputStream stream = connection.getInputStream(); 
       reader = new BufferedReader(new InputStreamReader(stream)); 
       StringBuffer buffer = new StringBuffer(); 
       String line =""; 
       while ((line = reader.readLine())!=null){ 
        buffer.append(line); 
       } 
       String finalJason = buffer.toString(); 

       JSONObject parentObject = new JSONObject(finalJason); 
       JSONArray parentArray = parentObject.getJSONArray("account"); 

       List<SummaryModel> accountModelList = new ArrayList<>(); 

       Gson gson = new Gson(); 

       for (int i=0; i<parentArray.length();i++) { 
        JSONObject finalObject = parentArray.getJSONObject(i); 
        SummaryModel summaryModel = gson.fromJson(finalObject.toString(),SummaryModel.class); 
        accountModelList.add(summaryModel); 
       } 
       return accountModelList; 

      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } finally { 
       if (connection != null) { 
        connection.disconnect(); 
       } 
       try { 
        if (reader != null) { 
         reader.close(); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      return null; 
     } 
+0

@Santosh Shresthaまた、このリンクにアクセスすることもできます:http://stackoverflow.com/questions/4205980/java-sending -http-parameters-post-method-easily –

+0

Map params = new LinkedHashMap <>();でエラーが発生しました。 –

+0

Mavya Soni 12値がサーブレットに渡されましたが、私のホームフラグメントのユーザIDがサーブレットに渡されるようにします –

関連する問題