我是android的新手。我尝试从活动中获取此信息:
i.putExtra("mlat", String.valueOf(latitude));
到这里:
public class PostDataActivity extends AsyncTask<Void, Void, Void>{
GpsData gps;
// double latitude = gps.getLatitude();
//String mlat;
@Override
protected Void doInBackground(Void... params) {
Bundle extras = getIntent().getExtras();
String mlat = extras.getString("mlat");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://test.de");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("lat", mlat));
nameValuePairs.add(new BasicNameValuePair("lon", "7.358154"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
但getIntent ist undefined
Bundle extras = getIntent().getExtras();
String mlat = extras.getString("mlat");
如何在Activity和doInBackground之间传输数据?
答案 0 :(得分:2)
execute
的{{1}}方法采用一系列String参数,可用于将额外数据输入后台任务。
这是Android source documentation:
中的示例AsyncTask
您可以通过这种方式从主线程中调用它:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
..
}
答案 1 :(得分:0)
首先阅读我的Matt提供的教程。
对于您的情况,您必须修改您的代码,如下所示:
1.将您的参数类型从void更改为String:
public class PostDataActivity扩展AsyncTask&lt; String ,Void,Void&gt; {
2.将您的数据作为参数传递给AsyncTask:
new PostDataActivity()。execute(“ mlat ”);
答案 2 :(得分:0)
Intent不包含任何内容,因为您正在扩展AsyncTask
。
我认为整个方法存在缺陷。
由于PostDataActivity
是一个Activity,它不应该扩展AsyncTask。
以下是我认为它应该是什么样子的想法:
public class PostDataActivity extends Activity {
GPSData gps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.);
Bundle extras = getIntent().getExtras();
String mlat = extras.getString("mlat");
MyDownloaderTask task = new MyDownloaderTask();
task.execute(mlat);
}
//Check docs for parameterisation of AsyncTask
private class MyDownloaderTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String params...) {
string someResult;
String mlat = params[0];
//Got your variable, do whatever you want from here on
return someResult; //Since it is no longer AsyncTask<Void, Void, Void>
}
protected void onPostExecute(String result) {
//This executes after task completes successfully
}
protected void onCancelled(String result) {
//This executes after task completes unsuccessfully
}
}
//...
}