如何在按下自定义ListView的行中的按钮时显示对话框?

时间:2014-12-16 20:18:41

标签: android listview android-listview android-dialog android-context

所以我试图在按下一个按钮时显示一个对话框,该按钮出现在我的Custom ListView的每一行中。

我的列表适配器代码如下:

public class HomeTimelineAdapter extends ArrayAdapter<Status> {

    private LayoutInflater inflater;
    private int tvrId;
    private List<Status> listItems;
    Dialog dialog;
    Status item;


    public HomeTimelineAdapter(Context context, int textViewResourceId, List<Status> objects) {
        super(context, textViewResourceId, objects);
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        tvrId = textViewResourceId;
        listItems = objects;
        dialog=new Dialog(context);   //This Line is giving an error how do I give context here.
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            ViewHolder holder;
            item = listItems.get(position);
            if (convertView == null) {
                convertView = inflater.inflate(tvrId, null);

                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.user_text);
                holder.add_journey = (Button) convertView.findViewById(R.id.journey);
                holder.add_journey.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        showdialog();
                    }
                });
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(item.getUser().getScreenName() + " : " + item.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder {

        public TextView text;
        public Button add_journey;
    }


    void showdialog() {
        dialog.setTitle("Journey");
        dialog.setContentView(R.layout.dialog);
        TextView text=(TextView) dialog.findViewById(R.id.textView);
        final EditText tag_name=(EditText) dialog.findViewById(R.id.editText);
        Button done =(Button) dialog.findViewById(R.id.button);
        text.setText("Journey Tag");
        done.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                DBItem items=new DBItem(tag_name.getText().toString(),item.getId());
                items.save();
            }
        });
        dialog.show();
    }
}

我的活动类的代码:

public class AndroidTwitterGoogleApiJavaClientActivity extends Activity {

    private SharedPreferences prefs;
    private TextView textView; 
    private HomeTimelineAdapter adapter;
    private ListView listview; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listview = (ListView) findViewById(R.id.listview);

        this.prefs = PreferenceManager.getDefaultSharedPreferences(this);

        Button launchOauth = (Button) findViewById(R.id.btn_launch_oauth);
        Button clearCredentials = (Button) findViewById(R.id.btn_clear_credentials);

        textView = (TextView) findViewById(R.id.response_code);

        launchOauth.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent().setClass(v.getContext(),OAuthAccessTokenActivity.class));
            }
        });

        clearCredentials.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clearCredentials();
                performApiCall();
            }

        });

        performApiCall();

    }

    private void clearCredentials() {
        new SharedPreferencesCredentialStore(prefs).clearCredentials();
    }

    /**
     * Performs an authorized API call.
     */
    private void performApiCall() {
        new ApiCallExecutor().execute();
    }

    private class ApiCallExecutor extends AsyncTask<Uri, Void, Void> {

        @Override
        protected Void doInBackground(Uri...params) {

            try {
//              String tweet = "Tweet sent at " + new Date();
//              TwitterUtils.sendTweet(prefs, tweet);
                ResponseList<twitter4j.Status> userTimeline = TwitterUtils.getUserTimeline(prefs);
                List<twitter4j.Status> statusList = new ArrayList<twitter4j.Status>();
                for (twitter4j.Status status : userTimeline) {

                    statusList.add(status);
                }
                adapter = new HomeTimelineAdapter(AndroidTwitterGoogleApiJavaClientActivity.this,R.layout.tweet_row,statusList);

            } catch (Exception ex) {
                adapter = new HomeTimelineAdapter(AndroidTwitterGoogleApiJavaClientActivity.this,R.layout.tweet_row,new ArrayList<twitter4j.Status>());
                ex.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            listview.setAdapter(adapter);
            adapter.notifyDataSetChanged();

        }

    }


}

我的Logcat:

12-17 22:41:14.926    5439-5453/com.ecs.sample E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.ecs.sample, PID: 5439
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:864)
     Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
            at android.os.Handler.<init>(Handler.java:200)
            at android.os.Handler.<init>(Handler.java:114)
            at android.app.Dialog.<init>(Dialog.java:114)
            at android.app.Dialog.<init>(Dialog.java:138)
            at com.ecs.sample.HomeTimelineAdapter.<init>(HomeTimelineAdapter.java:31)
            at com.ecs.sample.AndroidTwitterGoogleApiJavaClientActivity$ApiCallExecutor.doInBackground(AndroidTwitterGoogleApiJavaClientActivity.java:87)
            at com.ecs.sample.AndroidTwitterGoogleApiJavaClientActivity$ApiCallExecutor.doInBackground(AndroidTwitterGoogleApiJavaClientActivity.java:70)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:864)
12-17 22:41:15.616    5439-6612/com.ecs.sample W/dalvikvm﹕ threadid=18: thread exiting with uncaught exception (group=0x41623e18)
12-17 22:41:15.626    5439-6612/com.ecs.sample E/AndroidRuntime_2_crash﹕ crash in the same process: AsyncTask #2
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:864)
     Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
            at android.os.Handler.<init>(Handler.java:200)
            at android.os.Handler.<init>(Handler.java:114)
            at android.app.Dialog.<init>(Dialog.java:114)
            at android.app.Dialog.<init>(Dialog.java:138)
            at com.ecs.sample.HomeTimelineAdapter.<init>(HomeTimelineAdapter.java:31)
            at com.ecs.sample.AndroidTwitterGoogleApiJavaClientActivity$ApiCallExecutor.doInBackground(AndroidTwitterGoogleApiJavaClientActivity.java:87)
            at com.ecs.sample.AndroidTwitterGoogleApiJavaClientActivity$ApiCallExecutor.doInBackground(AndroidTwitterGoogleApiJavaClientActivity.java:70)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:864)
12-17 22:41:15.666    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo+,hn 15(0x6170692e747769),sn(),family 0,flags 4
12-17 22:41:15.666    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo-,err=8
12-17 22:41:15.666    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo+,hn 15(0x6170692e747769),sn(),family 0,flags 1024
12-17 22:41:15.666    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo-, 1
12-17 22:41:15.666    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo_proxy+
12-17 22:41:15.686    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo_proxy-, success
12-17 22:41:15.686    5439-6625/com.ecs.sample I/global﹕ call createSocket() return a new socket.
12-17 22:41:15.686    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo+,hn 13(0x3139392e35392e),sn(),family 0,flags 4
12-17 22:41:15.686    5439-6625/com.ecs.sample D/libc﹕ [NET] getaddrinfo-, SUCCESS
12-17 22:41:17.486    5439-5453/com.ecs.sample D/Process﹕ killProcess, pid=5439

行对话框=新对话框(上下文);正在使我的整个应用程序崩溃,因为列表视图无法加载。如果我评论列表显示的整行,但按下按钮应用程序崩溃,因为对话框没有上下文。如何在listadapter类中提供应用程序上下文?已经尝试过this.getapplicationcontext(),任何建议都会有所帮助。

由于

1 个答案:

答案 0 :(得分:0)

How do I give application context inside the listadapter class ? Have already tried this.getapplicationcontext()您需要Activity-Context来显示对话框。不是Application-Context ..这两个是不同的!只需将YourActivityClassName.this传递给您的对话框即可!然后会出现对话框!