在我的程序中,许多值存储在服务器上。
我使用AsyncTask
类从服务器读取了这些数据。
这是我的代码:
public class TestActivity extends AppCompatActivity {
private static List<String> mPackName;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPackName = new ArrayList<>();
try {
boolean check = new GetDataAsyncTask().execute("1234567").get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
e.printStackTrace();
e.printStackTrace();
}
}
private class GetDataAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
final String mCode = params[0];
APIGettingPosts apiGettingPosts = new APIGettingPosts(TestActivity.this, "get_off_code.php");
apiGettingPosts.getOffCode(new APIGettingPosts.OnOffCodeReceived() {
@Override
public void onReceived(List<Posts> posts) {
if (!(posts == null || posts.isEmpty()))
for (int i = 0; i < posts.size(); ++i) {
mPackName.add(posts.get(i).getTitle());
Log.e("mPackName["+String.valueOf(i)+"]",mPackName.get(i));
}
}
});
Log.e("Size of mPackName: ", String.valueOf(mPackName.size()));
for (int i = 0; i < mPackName.size(); ++i)
if (mCode.equals(mPackName.get(i))) {
Log.e("Is Equal: ", mPackName.get(i));
return true;
}
return false;
}
}
}
程序正确从服务器接收数据并将其存储在mPackName
列表中。在doInBackground
函数的最后,程序检查GetDataAsyncTask().execute("1234567")
列表中是否存在mPackName
函数中的输入值,并返回true
值。
尽管GetDataAsyncTask().execute("1234567")
函数的输入值在mPackName
列表中,但程序将返回false
值。
Log cat
的输出如下:
08-28 / com.green E / mPackName的大小:: 0
08-28 / com.green E / mPackName [0]:1234567
08-28 / com.green E / mPackName [1]:QAZXSWE
08-28 / com.green E / mPackName [2]:QWERTYU
mPackName
列表的大小在Log cat
中也为零,尽管它具有三个值{'1234567','QAZXSWE','QWERTYU'}
。
问题是:如何在mPackName
列表中搜索'1234567'值以返回true
中的check = new GetDataAsyncTask().execute("1234567").get();
值
代码?
答案 0 :(得分:3)
编辑答案
看起来您甚至不需要AsyncTask
,因为getOffCode
方法已经在后台线程中运行。
删除GetDataAsyncTask
类,并创建如下所示的方法。
private void search(final SearchCallback callback) {
APIGettingPosts apiGettingPosts = new APIGettingPosts(TestActivity.this, "get_off_code.php");
apiGettingPosts.getOffCode(new APIGettingPosts.OnOffCodeReceived() {
@Override
public void onReceived(List<Posts> posts) {
if (!(posts == null || posts.isEmpty())) {
for (int i = 0; i < posts.size(); ++i) {
mPackName.add(posts.get(i).getTitle());
Log.e("mPackName[" + String.valueOf(i) + "]", mPackName.get(i));
if (mCode.equals(mPackName.get(i))) {
callback.onSearchFound(true);
break;
}
}
}
callback.onSearchFound(false);
}
});
}
public interface SearchCallback{
void onSearchFound(boolean success);
}
然后从如下所示的onCreate方法调用
search(new SearchCallback(){
@Override
public void onSearchFound(boolean success) {
}
});
答案 1 :(得分:1)
尝试在onPostExecute()方法中放置一个开关。
EG。
...
private class GetDataAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
void onPostExecute(Object o){
handleResults()
}
...
void handleResults(){
// Insert your check here
}