我已经执行了异步任务程序,但这次我应该执行一个asynk任务发送两个params,需要在php文件中完成我的查询。它们是一个ID和一个Date,我存储在两个textview中,我得到了getText()。toString()。下面是我的EDITED类和异步任务,但是params没有到达php查询。总而言之,我也试过测试php文件和相关查询,它似乎工作正常。 我不知道如何发送这些数据。谁能帮我?提前谢谢。
public class Activity3 extends ActionBarActivity {
TextView IdentitaColl,DataSearch;
Intent intent;
GridView appGrid;
String myJSON;
private ProgressDialog pDialog;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "ID";
private static final String TAG_DATA = "Data";
private static final String TAG_START ="OraInizio";
private static final String TAG_END ="OraFine";
private static final String urlAgenda = "http://www.xsite.com/testparams.php";
JSONArray dati_cal = null;
ArrayList<HashMap<String, String>> list_app;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_esitoagenda);
intent = getIntent();
IdentitaColl = (TextView) findViewById(R.id.tv_identcoll);
DataSearch = (TextView) findViewById(R.id.tv_datasel);
appGrid= (GridView) findViewById(R.id.gvApp );
list_app = new ArrayList<HashMap<String,String>>();
riportaParametri();
String clID = IdentitaColl.getText().toString();
String aData = DataSearch.getText().toString();
Log.i("DATA Scelta: ","" +aData);
Log.i("ID Collab ", "" + clID);
getData();
}
private void riportaParametri() {
String pkg = getApplicationContext().getPackageName();
String tCode = intent.getStringExtra(pkg + "IDCOLL") + "\n";
String tData = intent.getStringExtra(pkg + "DATA") + "\n";
IdentitaColl.setText(tCode);
DataSearch.setText(tData);
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
dati_cal = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<dati_cal.length();i++){
JSONObject c = dati_cal.getJSONObject(i);
String id = c.getString(TAG_ID);
String dataap = c.getString(TAG_DATA);
String oStart = c.getString(TAG_START);
String oEnd = c.getString(TAG_END);
HashMap<String,String> impegni = new HashMap<String,String>();
impegni.put(TAG_ID,id);
impegni.put(TAG_DATA,dataap);
impegni.put(TAG_START,oStart);
impegni.put(TAG_END,oEnd);
list_app.add(impegni);
}
ListAdapter adapter = new SimpleAdapter(
Activity3.this, list_app, R.layout.activity_esitoagenda,
new String[]{TAG_ID,TAG_DATA,},
new int[]{R.id.tv_id,R.id.tv_datasel}
);
appGrid.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(urlAgenda);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
String clID = IdentitaColl.getText().toString();
String aData = DataSearch.getText().toString();
List<NameValuePair> valuePairs = new ArrayList<>(2);
valuePairs.add(new BasicNameValuePair("clID", clID));
valuePairs.add(new BasicNameValuePair("aData",aData));
httppost.setEntity(new UrlEncodedFormEntity(valuePairs));
Log.i("entity", "xxxxxxxxxxxxx"+valuePairs);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity3.this);
pDialog.setMessage("Obtaining list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected void onPostExecute(String result){
pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_seleziona_data, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:0)
如果要将值传递给asynctask。这样做。
.execute(param1, param2);
如果您的问题不同,请更清楚。
答案 1 :(得分:0)
试试这个。
JSONParser.java - 创建一个文件JSONParser.java并将代码放入文件中。您必须使用此文件向服务器发送请求并解析响应。
public class JSONParser {
/* Defining all variables */
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
/* Get Json object as respective response to url */
public JSONObject getJSONFromUrl(String url, JSONObject jObj) {
Log.v("Requ. URL: ",url);
// Making HTTP request
try {
// Default Http Client
DefaultHttpClient httpClient = new DefaultHttpClient();
// Http Post Header
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(jObj.toString());
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
// Execute Http Post Request
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
try {
// Getting Server Response
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
// Reading Server Response
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.e("JSON Parser", jObj.toString());
return jObj;
}
}
将以下代码写入您的活动/片段:
// Async Class for fetching live metal price from webapi
private class YourClassToFetchData extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params) {
// getting parameters sent by execute() method.
String id = params[0];
String date = params[1];
JSONParser jParser = new JSONParser();
JSONObject jsonObject = jParser.getJSONFromUrl(
URL, getConvertedinJson(id,date));
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
以JSON
格式
将此方法写入您创建AsyncTask
类
private JSONObject getConvertedinJson(String idString, string dateString) {
JSONObject object = new JSONObject();
try {
// put your parameter's name correctly at the place of ID and Date
object.put("ID", idString);
object.put("Date", dateString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("JObj", "JObj " + object.toString());
return object;
}