Dia*_*ana 24 android android-asynctask
我知道这个标题已经有很多问题,但我仍然没有找到适合我案例的解决方案.
我有以下代码从在线数据库中获取用户数据.如标题所述,问题是AsyncTask没有开始.
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getData(); // retrieves "friends" data from database
FloatingActionButton btn3 = (FloatingActionButton) findViewById(R.id.button_add_new_friend);
btn3.setBackgroundTintList(getResources().getColorStateList(R.color.Blonde));
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater layoutInflater = LayoutInflater.from(profile.this);
View promptView = layoutInflater.inflate(R.layout.input_new_friend, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(profile.this);
alertDialogBuilder.setView(promptView);
final EditText editText1 = (EditText) promptView.findViewById(R.id.edittext_addnewfriend);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
InputStream is = null;
// add values to the database
String friend = "" + editText1.getText();
// Verify the user in the USERS database - get users data from the dabase
GetDataJSON g = new GetDataJSON();
g.execute();
if (friends.contains(friend)) // if you are already friends with that user
Toast.makeText(getApplicationContext(), "You are already friends with that user!",
Toast.LENGTH_LONG).show();
else {
if (!users.contains(friend)) // the user doesn't exist in our database
Toast.makeText(getApplicationContext(), "That user doesn't exist! You either haven't introduced the right email or he's not a registered user within Poinder.",
Toast.LENGTH_LONG).show();
else // the user exists so we add him to the friends list
{
//do something
}
}
// Getting the users
protected void showList2(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
people = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<people.length();i++){
JSONObject c = people.getJSONObject(i);
String user = c.getString(TAG_USER);
String email = c.getString(TAG_EMAIL);
Double location_latitude = c.getDouble(TAG_LATITUDE);
Double location_longitude = c.getDouble(TAG_LONGITUDE);
users.add(email);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Getting the users
private class GetDataJSON extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxxxxxx/friends_out.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
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
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
@Override
protected void onPostExecute(String result){
myJSON=result;
showList2();
}
}
Run Code Online (Sandbox Code Playgroud)
知道我应该使用什么其他方法吗?或者最好是我应该如何修改这个以及我AsyncTask从未开始的任何想法?
编辑:我应用了下面提到的所有建议,不幸的是到目前为止它们都没有工作(我AsyncTask仍然没有开始).
另一个问题:AsyncTask在同一个活动中使用多个问题与我的问题有什么关系?
Dav*_*idH 25
由于其他建议的解决方案都不起作用,我怀疑你的问题就在于此 AsyncTask s的执行方式.如果在同一个Activity中正在执行多个AsyncTasks,就像在您的应用程序中一样,那么这些AsyncTasks将不会并行执行.他们将一个接一个地执行.
我怀疑你的其他AsyncTask是长期运行的,所以你的 GetDataJSON AsyncTask正在等待其他任务完成.
解决方案是启用AsyncTask的并行执行.使用以下代码并行执行AsyncTasks.
GetDataJSON g = new GetDataJSON();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Run Code Online (Sandbox Code Playgroud)
来自AsyncTask文档:
执行顺序
首次引入时,AsyncTasks在单个后台线程上串行执行.从DONUT开始,这被改为一个线程池,允许多个任务并行运行.从HONEYCOMB开始,任务在单个线程上执行,以避免由并行执行引起的常见应用程序错误.
如果您真的想要并行执行,可以使用THREAD_POOL_EXECUTOR调用executeOnExecutor(java.util.concurrent.Executor,Object []).
希望这可以帮助.
May*_*ara 10
只需更改你的asyntask参数
class GetDataJSON extends AsyncTask<String, Void, String>
Run Code Online (Sandbox Code Playgroud)
至,
class GetDataJSON extends AsyncTask<Void, Void, String>
Run Code Online (Sandbox Code Playgroud)
根据您的问题,我得出结论,您正在尝试从服务器获取好友列表,并根据结果显示Toast消息.
根据您的代码,您不是从alertDialogBuilder创建和显示AlertDialog.尝试显示AlertBox.
AsyncTask在一个单独的线程中运行.因此,
if (friends.contains(friend))
Run Code Online (Sandbox Code Playgroud)
将立即执行
g.execute();
Run Code Online (Sandbox Code Playgroud)
因此,即使用户在朋友列表中,也会显示其他部分的Toast.
此外,您没有将日志放在Asynctask方法中,这可能会让您觉得AsyncTask没有运行.
我建议你将你的if条件代码从方法转移AlertDialog到后面.另外,在AsyncTask方法中放入一些日志.onPostExecute()GetDataJSONshowList2();
希望这会有所帮助.请查找以下代号供您参考:
public class AIssue extends Activity {
String result = " DATA";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some);
findViewById(R.id.button1).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View arg0) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AIssue.this);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
GetDataJSON g = new GetDataJSON();
g.execute();
}
});
alertDialogBuilder.create().show();
}
});
}
// Getting the users
private class GetDataJSON extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("IN", "ONPRE EXECUTE");
}
@Override
protected String doInBackground(Void... params) {
String result = "SOME DATA";
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
Log.e("IN", "DO IN BACKGROUND");
} catch (InterruptedException e) {
e.printStackTrace();
result = "ERROR";
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
Log.e("IN", "ON POST EXECUTE");
Log.e("IN", "" + result);
/*****
* Your Condition to Check The Friend should be here after
* showList2();
* ***/
if (result.equalsIgnoreCase("SOME DATA"))// replace it with your
// condition to check
// friends
{
Log.e("IN", "IF");
} else {
Log.e("IN", "ELSE");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
在 getData2() 方法中试试这个:
new AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// your code
}
@Override
protected void onPostExecute(String result){
// your code
}
}.execute();
Run Code Online (Sandbox Code Playgroud)
或者如果它不起作用,将AsyncTask类放在方法之外,然后直接调用执行AsyncTask类而不是getData2(),像这样
new GetDataJSON().execute();
Run Code Online (Sandbox Code Playgroud)
问题出在你的 asynctask 参数上
谷歌的 Android 文档说:
异步任务由 3 个通用类型(称为 Params、Progress 和 Result)和 4 个步骤(称为 onPreExecute、doInBackground、onProgressUpdate 和 onPostExecute)定义。
AsyncTask 的泛型类型:
异步任务使用的三种类型如下:
谷歌的 Android 文档说:
AsyncTask 的泛型类型:
异步任务使用的三种类型如下:
并非所有类型都始终由异步任务使用。要将类型标记为未使用,只需使用类型 Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Run Code Online (Sandbox Code Playgroud)
因此,由于您没有向 AsyncTask 发送任何参数,所以您的异步任务如下所示
// Getting the users
public void getData2(){
new GetDataJSON().execute();
}
class GetDataJSON extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
/// your logic here
return result;
}
@Override
protected void onPostExecute(String result){
// your logic here
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15695 次 |
| 最近记录: |