0

I am new to Android and trying to do an excersize from a book, but I keep getting an error saying that makeText is not allowed, but it is as far as I can see exactly as in the book. Does anyone have an idea whats wrong here?

package com.madebyjohann.contentproviders;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.provider.ContactsContract;
import android.database.Cursor;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button queryButton = (Button)findViewById(R.id.button1);
        queryButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                queryContact ();
            }

            private void queryContact() {
                // TODO Auto-generated method stub
                Cursor nameCursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
                while (nameCursor.moveToNext()) {
                    String contactName =
                            nameCursor.getString(nameCursor
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
                                    Toast.makeText(this, contactName, Toast.LENGTH_SHORT).show();
                }
                nameCursor.close();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
4

3 回答 3

0

MakeText 仅构建对象。您需要在结果对象上调用 show。

于 2013-09-22T20:56:12.780 回答
0

是的,这正是你应该做的。在您的 Toast 行中:

Toast.makeText(this, contactName, Toast.LENGTH_SHORT).show();

“this”指的是最内层的类,即您正在构建的 OnClickListener。

每当您有“new Something()”时,这意味着您正在实例化一个类。始终,在类中使用“this”将引用该实例 - 最内部的类。

OnClickListener() 类不是上下文,这就是 makeText() 失败的原因。第一个参数需要是一个 Context,并且由于 Activity 类扩展了一个 Context( public class MainActivity extends Activity),你可以在MainActivity.this这里添加它,它将是有效的。

于 2013-09-22T20:58:10.957 回答
0

我更改了以下内容,它似乎有效,但不确定这是否是我应该做的?

Toast.makeText(MainActivity.this, contactName, Toast.LENGTH_SHORT).show();
于 2013-09-22T20:38:08.113 回答