Android 使用POST执行异步任务
我已经执行了异步任务过程,但这次我应该执行一个asynk任务,发送两个参数,这需要在php文件中完成查询。它们是一个ID和一个日期,我将它们存储在两个textview中,并通过getText().toString()获得。下面是我编辑的类和异步任务,但是params没有到达php查询。总之,我也尝试过测试php文件和相关的查询,它似乎工作正常。 我不知道如何发送这些数据。有人能帮我吗?提前谢谢Android 使用POST执行异步任务,android,android-asynctask,Android,Android Asynctask,我已经执行了异步任务过程,但这次我应该执行一个asynk任务,发送两个参数,这需要在php文件中完成查询。它们是一个ID和一个日期,我将它们存储在两个textview中,并通过getText().toString()获得。下面是我编辑的类和异步任务,但是params没有到达php查询。总之,我也尝试过测试php文件和相关的查询,它似乎工作正常。 我不知道如何发送这些数据。有人能帮我吗?提前谢谢 public class Activity3 extends ActionBarActivity {
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);
}
公共类活动3扩展了ActionBarActivity{
TextView IdentitaColl,数据搜索;
意图;
GridView-appGrid;
字符串myJSON;
私人对话;
私有静态最终字符串标记_RESULTS=“result”;
私有静态最终字符串标记\u ID=“ID”;
私有静态最终字符串标记_DATA=“DATA”;
私有静态最终字符串标记_START=“oranizio”;
私有静态最终字符串标记_END=“OraFine”;
私有静态最终字符串urlAgenda=”http://www.xsite.com/testparams.php";
JSONArray dati_cal=null;
ArrayList应用程序;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_esitoGenda);
intent=getIntent();
IdentitaColl=(TextView)findViewById(R.id.tv_identcoll);
数据搜索=(TextView)findViewById(R.id.tv_数据集);
appGrid=(GridView)findviewbyd(R.id.gvApp);
list_app=new ArrayList();
riportaParametri();
字符串clID=identiacoll.getText().toString();
字符串aData=DataSearch.getText().toString();
Log.i(“数据Scelta:,”+aData);
Log.i(“ID-Collab”,即“+clID”);
getData();
}
私有无效riportaParametri(){
字符串pkg=getApplicationContext().getPackageName();
字符串tCode=intent.getStringExtra(pkg+“IDCOLL”)+“\n”;
String tData=intent.getStringExtra(pkg+“数据”)+“\n”;
identiacoll.setText(tCode);
DataSearch.setText(tData);
}
受保护的无效显示列表(){
试一试{
JSONObject jsonObj=新的JSONObject(myJSON);
dati_cal=jsonObj.getJSONArray(标记结果);
如果要将值传递给asynctask,请执行以下操作(int i=0;i)
.execute(param1, param2);
如果您的问题不同,请更清楚。试试这个
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);
}
如果您对PHP没有问题,就不需要对其进行标记。我不知道…对不起。是的,这正是我的意思。我不知道将参数放在哪里发送。因此,如果我理解,我有两个TextView,我可以得到两个tv的值,如下所示:字符串xxx=mytv1.getText().toString()和字符串yyy=mytv2.getText().toString(),然后执行(xxx,yyy)关于php?我如何识别这个字符串?$data=POST['xxx']?您可以将数据作为json.StringEntity se=new StringEntity(json);entity.setEntity(se)传递;正如您所看到的,我已经编辑了这段代码,如果我登录nparams,我可以看到要发送的数据。这些数据没有到达php文件,事实上,如果我从查询中读取echo,参数“aLav”为空。我无法解决。谢谢您的建议。我将单独尝试您发布的代码,我将给您答复。但是,这不会改变我的问题stion…我的代码中的错误在哪里?很明显,我可以从日志中读取传递的参数…我问自己错误是否存在于php文件中,但我已经在没有post变量的情况下对其进行了测试,它工作正常…请告诉我如何调用您的类“YourClassFetchData”?如果我将其称为Youretc();给我红旗。你必须调用new YourClassFetchData().execute(id,date);
谢谢你,但是我得到了这个错误:错误解析数据org.json.JSONException:Value SELECT类型java.lang.String无法转换为JSONObject,但是看起来值是正确的:E/json Parser﹕ {“aData”:“2015-9-28”,“clID”:“2”}还能做什么?
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;
}