2017-10-21 78 views
0

我的應用程序佈局顯然不是一個正常的佈局,所以我無法設置我的列表適配器自動更新時進行編輯。需要幫助刷新我的數據庫ListView在我的應用程序

我在自己的活動和佈局中控制的Java文件中編輯我的數據庫。

public void onClick(View view){ 
    if (view == findViewById(R.id.addsave)) { 
     RecipeRepo repo = new RecipeRepo(this); 
     Recipe recipe = new Recipe(); 
     if (editTextName.getText().toString().equals("")) { 
      editTextName.setError("Recipe name required!"); 
      return; 
     } else { 
      recipe.name = editTextName.getText().toString(); 
     } 
     if (textImagePath.getText().toString().equals("")) { 
      recipe.image = (""); 
     }else{ 
      recipe.image = textImagePath.getText().toString(); 
     } 
     recipe.category = staticSpinner.getSelectedItem().toString(); 
     if (editTextIngredients.getText().toString().equals("")) { 
      editTextIngredients.setError("Ingredient required!"); 
      return; 
     } else { 
      recipe.ingredients = editTextIngredients.getText().toString(); 
     } 
     if (editTextInstruct.getText().toString().equals("")) { 
      editTextIngredients.setError("Instruction required!"); 
      return; 
     } else { 
      recipe.instructions = editTextInstruct.getText().toString(); 
     } 
     recipe.cooktemp = editTextCookTemp.getText().toString(); 
     recipe.cooktime = editTextCookTime.getText().toString(); 
     recipe.serves = editTextServings.getText().toString(); 
     recipe.recipe_Id = _Recipe_Id; 

     if (_Recipe_Id == 0) { 
      _Recipe_Id = repo.insert(recipe); 

      Toast.makeText(this, "New Recipe Added", Toast.LENGTH_SHORT).show(); 
      finish(); 

它實際上插入並在此Java文件

int insert(Recipe recipe){ 

    //Open connection to write data 
    SQLiteDatabase db = dbHelper.getWritableDatabase(); 
    ContentValues values = new ContentValues(); 
    values.put(Recipe.KEY_SERVES, recipe.serves); 
    values.put(Recipe.KEY_COOKTIME, recipe.cooktime); 
    values.put(Recipe.KEY_COOKTEMP, recipe.cooktemp); 
    values.put(Recipe.KEY_INSTRUCT, recipe.instructions); 
    values.put(Recipe.KEY_INGREDIENTS, recipe.ingredients); 
    values.put(Recipe.KEY_CATEGORY, recipe.category); 
    values.put(Recipe.KEY_IMAGE, recipe.image); 
    values.put(Recipe.KEY_NAME, recipe.name); 

    //Inserting Row 
    long recipe_Id = db.insert(Recipe.TABLE, null, values); 
    db.close();// Closing database connection 
    return (int) recipe_Id; 
} 

void delete(int recipe_Id){ 

    SQLiteDatabase db = dbHelper.getWritableDatabase(); 
    db.delete(Recipe.TABLE, Recipe.KEY_ID + "=?", new String[] {String.valueOf(recipe_Id)}); 
    db.close(); 
} 

void update(Recipe recipe){ 

    SQLiteDatabase db = dbHelper.getWritableDatabase(); 
    ContentValues values = new ContentValues(); 

    values.put(Recipe.KEY_SERVES, recipe.serves); 
    values.put(Recipe.KEY_COOKTIME, recipe.cooktime); 
    values.put(Recipe.KEY_COOKTEMP, recipe.cooktemp); 
    values.put(Recipe.KEY_INSTRUCT, recipe.instructions); 
    values.put(Recipe.KEY_INGREDIENTS, recipe.ingredients); 
    values.put(Recipe.KEY_CATEGORY, recipe.category); 
    values.put(Recipe.KEY_IMAGE, recipe.image); 
    values.put(Recipe.KEY_NAME, recipe.name); 

    db.update(Recipe.TABLE, values, Recipe.KEY_ID + "=?", new String[]{String.valueOf(recipe.recipe_Id)}); 
    db.close(); 
} 

更新,最後它被投入從這個.java文件和獨立佈局列表視圖。這是我的適配器的位置,但我無法得到notifyDataSetChanged()在這裏工作......因爲它甚至不會出現。

 public boolean onNavigationItemSelected(MenuItem item) { 
    // Handle navigation view item clicks here. 
    int id = item.getItemId(); 
    RecipeRepo repo = new RecipeRepo(this); 

    if (id == R.id.nav_meat) { 

     final ArrayList<HashMap<String, String>> recipeList = repo.getRecipeMeat(); 


     if(recipeList.size()!=0) { 
      ListView lv = (ListView) findViewById(R.id.list); 
      lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        recipe_Id = (TextView) view.findViewById(R.id.recipe_Id); 
        String recipeId = recipe_Id.getText().toString(); 
        Intent objIndent = new Intent(getApplicationContext(), RecipeDetail.class); 
        objIndent.putExtra("recipe_Id", Integer.parseInt(recipeId)); 
        startActivity(objIndent); 
       } 
      }); 
      ListAdapter adapter = new SimpleAdapter(SousChef.this, recipeList, R.layout.view_recipe_entry, new String[]{"id", "category", "name"}, new int[]{R.id.recipe_Id, R.id.recipe_list_category, R.id.recipe_list_name}); 
      lv.setAdapter(adapter); 
     }else { 
      Toast.makeText(this, "No recipe!", Toast.LENGTH_SHORT).show(); 
     } 
    } else if (id == R.id.nav_veg) { 

     final ArrayList<HashMap<String, String>> recipeList = repo.getRecipeVeg(); 
     if(recipeList.size()!=0) { 
      ListView lv = (ListView) findViewById(R.id.list); 
      lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        recipe_Id = (TextView) view.findViewById(R.id.recipe_Id); 
        String recipeId = recipe_Id.getText().toString(); 
        Intent objIndent = new Intent(getApplicationContext(), RecipeDetail.class); 
        objIndent.putExtra("recipe_Id", Integer.parseInt(recipeId)); 
        startActivity(objIndent); 
       } 
      }); 
      ListAdapter adapter = new SimpleAdapter(SousChef.this, recipeList, R.layout.view_recipe_entry, new String[]{"id", "category", "name"}, new int[]{R.id.recipe_Id, R.id.recipe_list_category, R.id.recipe_list_name}); 
      lv.setAdapter(adapter); 

     }else { 
      Toast.makeText(this, "No recipe!", Toast.LENGTH_SHORT).show(); 
     } 

因此,任何建議將其設置爲自動更新將是一個巨大的幫助。我一直在思考這個問題幾天,現在看着不同的例子,而不是什麼,但是沒有一個安裝程序非常像這個不允許我在一個文件中包含所有內容的安裝程序。

並且預先感謝您。

類別選擇圖像: Category picking Image

回答

1

有肯定更多的答案,但是這是一個可能的幫助,

Quick Example for the proposed solution

簡短的說明

MainActivity

//create a public static adapter 
public static ListAdapter adapter 

onCreateView()

//Create your adapter and set it to the right ListView 
ListView lv = findViewById(R.id.listView_in_xml); 
adapter = new SimpleAdapter(...) 
lv.setAdapter(adapter) 

CustomAdapter而你的情況我認爲是SimpleAdapter

//add a public method to be called so that the Adapter updates and displays the new data 
public void updateMethod(){ 
    //update your List<Recipe> that I would guess you have calling the database again 
    //if needed update your getCount() return value so that it returns the number of childs in your ListView which most of the cases is just the List<Recipe>.size() 
    //notifyDataSetChanged() 
} 

內部的DB HANDLER CLASS

//in every update, add, delete or any method that requires the ListView to Update just call the created method, 
MainActivity.CustomAdapter.updateMethod(); 

問題

你將不得不確保public static adapter已經被初始化並且不爲空,或者乾脆檢查adapter是否不null和更新,因爲如果適配器該活動尚未啓動,因此無需觸發updateMethod()

其他解決方案

而是創建一個public static adapter創建public static boolean,那麼只要數據進行修改的布爾值設置爲true,從數據庫中。 最後,每當你恢復你的活動時檢查該布爾值,並在需要時更新你的ListViewAdapter。

我知道工作原因更復雜的解決方案我用它

使用TaskAsyncTaskLoader它採用了LoaderMainActivity並實現LoaderManager.LoaderCallbacks

(可選)您可以使Loaderpublic static Loader並在您的DBHandler內觸發加載程序以再次加載數據或使用任何其他您需要的邏輯。工作的

證明建議的解決方案, enter image description here

+0

謝謝你的回答,我會盡快給你一個嘗試,爲遲到的迴應感到抱歉,我一直很忙。 – Koumintang

+0

我看到的主要問題是,我的SimpleAdapter被多次調用,它被設置爲屏幕左側的滑動導航欄。所以它適用於肉類,意大利麪類,飲料類等......我的更新方法最終會變得一樣長,然後用一堆檢查檢查哪些項更新的類別。 – Koumintang

+0

@Koumintang你是說你並沒有真正更新數據庫中的值,而是選擇了一個類別,然後ListView應該顯示數據庫中該類別的項目? – ArtiomLK

0

您可以播放從變動數據庫文件意圖你在OnCreate響應()適配器加載類

Intent intent = new Intent("key_to_identify_the_broadcast"); 
    Bundle bundle = new Bundle(); 
    bundle.putString("edttext", "changed"); 
    intent.putExtra("bundle_key_for_intent", bundle); 
    context.sendBroadcast(intent); 

後,然後就可以收到通過使用BroadcastReceiver類在您的片​​段中捆綁

private final BroadcastReceiver mHandleMessageReceiver = new 
BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Bundle bundle = 
      intent.getExtras().getBundle("bundle_key_for_intent"); 
      if(bundle!=null){ 
       String edttext = bundle.getString("edttext"); 
      } 
      //you can call any of your methods for using this bundle for your use case 
    } 
}; 

在您的適配器的onCreate()addi NG類,你需要先否則該廣播接收器不會被觸發

IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast"); 
getActivity().getApplicationContext(). 
       registerReceiver(mHandleMessageReceiver, filter); 

註冊的廣播接收器最後,你可以註銷接收器,以避免任何異常

@Override 
public void onDestroy() { 
    try { 

     getActivity().getApplicationContext(). 
      unregisterReceiver(mHandleMessageReceiver); 

    } catch (Exception e) { 
     Log.e("UnRegister Error", "> " + e.getMessage()); 
    } 
    super.onDestroy(); 
} 
+0

謝謝您的回覆,我會很快給它一個嘗試。對不起,我剛剛忙得很晚。 – Koumintang

相關問題