Android:notifyDataSetChanged()仅适用于第二次调用

时间:2014-07-06 21:28:36

标签: android listview adapter notifydatasetchanged

好的,所以我的机智就此结束了。

我已将列表数据更新功能封装在名为' refreshData'的函数中。适配器内部。然后我在onActivityResult内部的适配器上调用此函数(为结果设置的活动在onStop上设置完成标志。此完成标志应该确定哪些样式(颜色和文本)应用于列表视图中的特定列表项基本上,用户选择" 1"并进入新活动,关闭该活动,并且" 1"设置为在onStop上完成。返回列表活动,列表视图应该提供" 2"同时设置" 1"完成(视觉提示)。

我遇到的问题是,更新只发生在用户点击列表项以转到新活动并接近返回的第二次。没有失败,listview将仅更新SECOND时间。我不知道为什么会这样。任何帮助表示赞赏。

感谢。

公共类SceneAdapter扩展了ArrayAdapter {

Context context;
int layoutResourceId;
ArrayList<SceneItem> data;
Typeface font;
UserDatabaseHelper uDatabase;
int chapter_number;

public SceneAdapter(Context context, int layoutResourceId, int chapter, String FONT) {
    super(context, layoutResourceId);
    this.context = context;
    this.layoutResourceId = layoutResourceId;
    this.chapter_number = chapter;
    this.data = getData(chapter);
    this.font = Typeface.createFromAsset(context.getAssets(), FONT);
}

public int getCount() {
    return data.size();
}

@Override
public int getViewTypeCount() {
    int typeCount = 2;
    return typeCount;
}

private ArrayList<SceneItem> getData(int chapter) {
    // bucket to return data
    ArrayList<SceneItem> container = new ArrayList<SceneItem>();

    // titles (need to replace with master database call eventually)
    String[] scenesListJapanese = getSceneTitlesInJapanese(chapter);
    String[] scenesListEnglish = getSceneTitlesInEnglish(chapter);

    // ready database for data retrieval
    initializeUserDatabaseForUse();

    // query for data
    Cursor query = uDatabase.getAllScenesForChapter(chapter + 1);

    // testing line, take out when done
    Log.v("query length: ", ""+ query.getCount());

    // fill data
    for (int i = 0; i < scenesListJapanese.length; i++) {
        SceneItem item = new SceneItem(""+(i+1), scenesListEnglish[i], scenesListJapanese[i],
                query.getInt(4), query.getInt(3));
        container.add(item);
        Log.v("status for chapter " + (chapter + 1) + ": ", "available: " + query.getInt(4)
                + ", completed: " + query.getInt(3));
        query.moveToNext();
    }

    // close db connection
    query.close();

    return container;
}



public void refreshData() {
    data.clear();
    this.data = getData(chapter_number);
    Log.v("refresh data called: ", "NOW!");
}


public boolean areAllItemsEnabled() {
    return false;
}

public boolean isEnabled(int position) {
    if(data.get(position).available == 1 || position == 0) {
        return true;
    } else {
        return false;
    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    SceneHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new SceneHolder();
        holder.chapterNumber = (TextView)row.findViewById(R.id.scene_number);
        holder.englishTitleBox = (TextView)row.findViewById(R.id.scene_title_english);
        holder.japaneseTitleBox = (TextView)row.findViewById(R.id.scene_title_japanese);
        holder.englishTitleBox.setTypeface(font);
        holder.japaneseTitleBox.setTypeface(font);
        row.setTag(holder);
    } else {
        holder = (SceneHolder)row.getTag();
    }

    Resources res = context.getResources();
    if(isEnabled(position)) {
        holder.englishTitleBox.setTextColor(res.getColor(R.color.gray_subtext));
        holder.chapterNumber.setBackgroundResource(R.drawable.number_gray);
        holder.japaneseTitleBox.setTextColor(res.getColor(R.color.gray_text));
        holder.chapterNumber.setTextColor(res.getColor(R.color.white_text));
        row.setBackgroundColor(res.getColor(R.color.transparent));
    } else {
        holder.englishTitleBox.setTextColor(res.getColor(R.color.standard_gray));
        holder.chapterNumber.setBackgroundResource(R.drawable.number_transparent);
        holder.japaneseTitleBox.setTextColor(res.getColor(R.color.standard_gray));
        holder.chapterNumber.setTextColor(res.getColor(R.color.standard_gray));
        row.setBackgroundColor(res.getColor(R.color.action_gray_end));
    }

    SceneItem item = data.get(position);
    holder.chapterNumber.setText(item.scene);
    holder.englishTitleBox.setText(item.titleEnglish);
    holder.japaneseTitleBox.setText(item.titleJapanese);
    return row;
}

static class SceneHolder
{
    TextView englishTitleBox;
    TextView japaneseTitleBox;
    TextView chapterNumber;
}

// Get english scene titles based on chapter number
private String[] getSceneTitlesInEnglish(int position) {
    // generate and return list
}

// Get japanese scene titles based on chapter number
private String[] getSceneTitlesInJapanese(int position) {
    // generate and return list
}

public void initializeUserDatabaseForUse() {
    // init database
}

}

呼叫活动代码:

公共类SceneSelectActivity扩展了Activity {

ListView mListView; // list view to display scene data
int chapterNumber; // chapter number to use for displaying scenes
Intent passedIntent; // passed intent containing data on which chapter was selected
UserDatabaseHelper uDatabase; // user database reference
SceneAdapter sceneAdapter; // adapter reference
static final int REQUEST_CODE = 1; // request code for activity result

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scene_select);

    // Setup necessary variables and views for this activity
    initializeUserDatabaseForUse();
    handleSetup();

    Button backButton = (Button)findViewById(R.id.scene_back_button);
    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode,resultCode, data);

    sceneAdapter.refreshData();
    sceneAdapter.notifyDataSetChanged();

}

@Override
public void onResume() {
    super.onResume();

}

// Handle set up of activity views and variables
private void handleSetup() {

    // passed intent holding data on which chapter was selected
    passedIntent = getIntent();

    // chapter number to be used in deciding what data/views to set up
    chapterNumber = getChapterNumber(passedIntent);

    // setup list data, and views
    setDataForThisScene(chapterNumber);
    setMainImage(chapterNumber);
}

// Obtain chapter number from passed intent
private int getChapterNumber(Intent i) {
    // ensure the data is a valid number for a chapter
    return i.getIntExtra("chapter_number", 0);

}

// Set up data to be used for list view
private void setDataForThisScene(int position) {
    // set chapter splash content
    Resources res = getResources();
    TextView splashJ = (TextView)findViewById(R.id.scene_splash_title_j);
    TextView splashE = (TextView)findViewById(R.id.scene_splash_title_e);
    final String title_english[] = res.getStringArray(R.array.chapters_english);
    final String title_japanese[] = res.getStringArray(R.array.chapters_japanese);
    splashJ.setText(title_japanese[chapterNumber]);
    splashE.setText(title_english[chapterNumber]);
    TextView completionView = (TextView) findViewById(R.id.scene_progress);
    completionView.setText(getCompletionStatus(chapterNumber + 1));

    // setup scene list
    mListView = (ListView) findViewById(R.id.scene_list);
    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(SceneSelectActivity.this, DialogueActivity.class);
            i.putExtra("chapter_number", chapterNumber);
            i.putExtra("scene_number", position);
            startActivityForResult(i, REQUEST_CODE);
            //startActivity(i);
            // LIST ON CLICK ITEM EVENTS
        }
    });
    //SceneAdapter sceneAdapter = new SceneAdapter(this, R.layout.scene_list_item, sceneData, "custom_font_regular.otf");
    sceneAdapter = new SceneAdapter(this, R.layout.scene_list_item, chapterNumber, "custom_font_regular.otf");
    mListView.setAdapter(sceneAdapter);
}

private String getCompletionStatus(int chapter) {
    Cursor query = uDatabase.getAllScenesForChapter(chapter);
    int completed = 0;
    for(int i = 0; i < query.getCount(); i++) {
        if(query.getInt(3) != 0) {
            completed += 1;
        }
        query.moveToNext();
    }
    query.close();
    return completed * 100 / query.getCount() + "%";
}

// fill in image for chapter bg
private void setMainImage(int chapterNumber) {
    // generate image
}

// initialize database
public void initializeUserDatabaseForUse() {
    // init database
}

}

&lt; refreshData&#39;内的LOG.v函数DOES每次关闭详细活动时都会被调用,并且用户返回到此列表视图活动。虽然每次都会调用它,但列表只会更新用户重复操作的第二次。

0 个答案:

没有答案