2017-03-24 116 views
0

我有一个asynctask从本地Sqlite数据库获取数据并将其显示给用户。如果数据不存在于sqlite中,则将对服务器进行网络调用以检索服务器端数据。Arraylist自己清除android

问题是,当我调用分贝,我得到的数据,我把它添加到列表中。我检查列表的大小并显示内容。

然后当我尝试通知的ArrayList适配器,它显示列表大小为0,没有任何明显的()调用正在取得

的文件如下:

包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; 

} 
+0

notifyDataSetChanged在ArrayList中添加数据后调用... –

+0

其中onPostExecute – Kushan

回答

0
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; 
    } 
} 

在这里你清单和通知适配器

+0

是的,但之后我从数据库中获取数据并再次通知适配器。该列表显示db调用之后的项目。但在onPostExecute它奇迹般地显示大小0 – Kushan

0

首先检查你的db数据更新与否。

+0

db有数据....立即在数据库调用后,当我检查列表的大小,它显示项目 – Kushan

+0

下载sqlitedatabrowser并检查您的数据库 –

+0

有数据库中的数据 – Kushan