[英]Arraylist gets cleared on its own in android
我有一個asynctask,它從本地Sqlite數據庫獲取數據並將其顯示給用戶。 如果sqlite中沒有該數據,則將對服務器進行網絡調用以檢索服務器端數據。
問題是,當我調用數據庫並獲取數據時,我將其添加到列表中。 我檢查列表的大小,它顯示了內容。
然后,當我嘗試通知arraylist適配器時,它顯示列表大小為0,而未進行任何clear()調用
文件如下:
包com.example.project.recommendedapp.AsyncTasks;
// SuggestionsGetterAsync start ---------------------------------------------- -------------------------------------------------- ----------------
public class SuggestionsGetterAsync extends AsyncTask<String,Void,Void> {
private String queryString;
private WeakReference<Activity> weakReference;
private Activity localReference;
private Fragment localFragment;
private ArrayList<Suggestions> localSuggestionsList;
double latitude,longitude;
String cityName;
int request_counter_in_fragment;
public SuggestionsGetterAsync(Activity passedReference, Fragment passedFragment, ArrayList<Suggestions> localSuggestionsList,int request_counter_in_fragment,double ...coordinates){
weakReference=new WeakReference<Activity>(passedReference);
localReference=weakReference.get();
localFragment=passedFragment;
this.localSuggestionsList=localSuggestionsList;
latitude=coordinates[0];
longitude=coordinates[1];
this.request_counter_in_fragment=request_counter_in_fragment;
}
@Override
protected Void doInBackground(String... params) {
queryString=params[0];
cityName=params[1];
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) {
localReference.runOnUiThread(new Runnable() {
@Override
public void run() {
localSuggestionsList.clear();
((LocalFragmentInteractionInterface)localFragment).notifyAdapter();
}
});
//cancel the call to avoid load if it is a previously dispatched useless servelet
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()!=request_counter_in_fragment){
this.cancel(true);
return null;
}
}
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing() && !queryString.equals("")){
//cancel the call to avoid load if it is a previously dispatched useless servelet
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()!=request_counter_in_fragment){
this.cancel(true);
return null;
}
LocalDatabaseHelper localDatabaseHelper = LocalDatabaseHelper.getInstance(localReference);
localSuggestionsList=localDatabaseHelper.getLocalSearchSuggestions(queryString);
Log.d("FragmentCreate","localSuggestionsList size after db call is "+localSuggestionsList.size()); // prints ok and shows that the list has values
}
Log.d("FragmentCreate","localSuggestionsList size now is"+localSuggestionsList.size()); // prints ok and shows that the list has values
if (localSuggestionsList.size()==0) {
//basically first query the local cache, if nothing is found locally, go fetch the data from the server
//put the fetched results inside the local database
try {
//String serveleturl = "http://192.168.1.7:8080/Servelet/SearchSuggestionsServelet?latitude="+latitude+"&longitude="+longitude+"&cityName="+cityName+"&queryString="+URLEncoder.encode(queryString,"UTF-8");
String serveleturl = "http://kushan.dynu.com:8080/Servelet/SearchSuggestionsServelet?cityName="+URLEncoder.encode(cityName,"UTF-8")+"&queryString="+(queryString.equals("")?null:URLEncoder.encode(queryString,"UTF-8"));
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30000, TimeUnit.MILLISECONDS)
.readTimeout(30000,TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(false)
.build();
Request request = new Request.Builder()
.url(serveleturl)
.build();
Response response = client.newCall(request).execute();
switch (response.code()){
case 444:
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
@Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("No search results found",false);
}
});
}
break;
case 222:
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
@Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("Hide the errortext",true);
}
});
}
JSONArray suggestionsArray = new JSONArray(response.body().string());
if(suggestionsArray.length()!=0){
try{
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()){
LocalDatabaseHelper localDatabaseHelper = LocalDatabaseHelper.getInstance(localReference);
localDatabaseHelper.putSuggestions(suggestionsArray);
}
}catch (Exception e){
Log.e("FragmentCreate","Error saving the suggestion inside db",e);
}
}
for(int i=0;i<suggestionsArray.length();i++){
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) {
localSuggestionsList.add(new Suggestions(suggestionsArray.getJSONObject(i)));
}else{
return null;
}
}
break;
default:
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
@Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("No search results found",false);
}
});
}
break;
}
response.close();
}catch (Exception e){
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
@Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("Check your Internet connection or try again after some time",false);
}
});
}
}
}else{
if (localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) {
localReference.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("FragmentCreate","before postExecute the size of the list is "+localSuggestionsList.size()); // prints size as zero for no reason
((LocalFragmentInteractionInterface)localFragment).setErrorText("Hide the errortext",true);
}
});
}
}
return null;
}
@Override
public void onPostExecute(Void voided){
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment)) {
Log.d("FragmentCreate","request counter in asynctask ="+request_counter_in_fragment+" queryString is = "+queryString+" "+localSuggestionsList.size()); // prints size as zero for no reason
((LocalFragmentInteractionInterface) localFragment).notifyAdapter();
if(queryString.equals("")){
((LocalFragmentInteractionInterface)localFragment).setErrorText("",true);
}
}
weakReference=null;
localReference=null;
localFragment=null;
queryString=null;
localSuggestionsList=null;
}
@Override
public void onCancelled(){
Log.d("FragmentCreate","AsyncTaskCancelled");
}
}
從sqlite返回列表的函數如下:
public ArrayList<Suggestions> getLocalSearchSuggestions(String searchString) throws SQLiteException{
//localSuggestionsList.clear();
ArrayList<Suggestions> localSuggestionsList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT "+TableAndColumnNames.SEARCH_RESULTS_DATA+" FROM "+TableAndColumnNames.SEARCH_RESULTS_TABLE_NAME+" WHERE "+TableAndColumnNames.SEARCH_RESULTS_SUGGESTION+" LIKE '%"+searchString+"%' limit 20";
Cursor c = db.rawQuery(sql,null);
JSONObject suggestionObject;
if(c!=null){
if(c.moveToFirst()){
do{
try{
//Log.d("FragmentCreate",c.getString(0)+" found in suggestion");
suggestionObject = new JSONObject(c.getString(0));
localSuggestionsList.add(new Suggestions(suggestionObject));
}catch (JSONException je){
Log.d("FragmentCreate","Data got corrupted for searched list");
}
}while(c.moveToNext());
}
c.close();
}
return localSuggestionsList;
}
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) {
localReference.runOnUiThread(new Runnable() {
@Override
public void run() {
localSuggestionsList.clear();
((LocalFragmentInteractionInterface)localFragment).notifyAdapter();
}
});
//cancel the call to avoid load if it is a previously dispatched useless servelet
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()!=request_counter_in_fragment){
this.cancel(true);
return null;
}
}
在這里您清除列表並通知適配器
首先檢查您的數據庫數據更新與否。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.