使用AsyncTask后更改了颜色

时间:2016-11-09 13:56:42

标签: android sqlite android-asynctask

我的应用中存在问题。这是一本电话簿。使用AsyncTask后,所有颜色都会改变!

这是使用AsyncTask前的截图:

enter image description here

这是使用AsyncTask后的屏幕截图:

enter image description here

我的应用程序出了什么问题?

1: 我的代码(使用AsyncTask):

public class MainActivity extends Activity {
ArrayList<Contact> contacts;
private ContactAdapter contactAdapter;
private DbWorker db;
private ListView listView;
private Context context;

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

    listView = (ListView) findViewById(R.id.listview);

    context = getApplicationContext();
    new DbAsyncTask(context).execute();

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(MainActivity.this, ChangeContactActivity.class);
            Contact contact = contactAdapter.getContact(position);
            intent.putExtra("name", contact.getContactName());
            intent.putExtra("phone", contact.getContactPhone());
            intent.putExtra("category", contact.getContactCategory());
            intent.putExtra("org", contact.getContactOrgName());
            intent.putExtra("id", contact.getContactId());

            startActivity(intent);
        }
    });

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
            startActivity(intent);
        }
    });

}

class DbAsyncTask extends AsyncTask<Void, Void, ArrayList<Contact>> {
    private Context ctx;

    public DbAsyncTask(Context ctx){
        this.ctx = ctx;
    }

    @Override
    protected ArrayList<Contact> doInBackground(Void... params) {
        db = new DbWorker(ctx);
        contacts = (ArrayList<Contact>) db.selectAllContacts();
        return contacts;
    }

    @Override
    protected void onPostExecute(ArrayList<Contact> contacts) {
        contactAdapter = new ContactAdapter(ctx, contacts);

        listView.setAdapter(contactAdapter);
    }
}

}

没有AsyncTask我提交:

listView = (ListView) findViewById(R.id.listview);
context = getApplicationContext();
new DbAsyncTask(context).execute();

并添加:

db = new DbWorker(this);
listView = (ListView) findViewById(R.id.listview);
contacts = (ArrayList<Contact>) db.selectAllContacts();
contactAdapter = new ContactAdapter(this, contacts);
listView.setAdapter(contactAdapter);

1 个答案:

答案 0 :(得分:0)

您正在将应用程序的上下文传递给您的异步,该异步没有关于您的主题/样式的线索。相反,您应该使用具有所需主题/样式信息的活动上下文。

因此,替换:

cfoutput

以下内容:

context = getApplicationContext();