我必须将数据从fragment传递到json任务然后传递给servlet。我已经包含了fragment,class和servlet的代码。
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;
}
}
这是以下JSON任务,它从servlet获取数据并显示在片段
上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
}
}
但是当我从servlet调用userId时,我得到空值
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 :(得分:0)
您没有在请求中传递user_id,因此您的Servlet中没有得到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;
}