0

我正在尝试使用自定义按钮创建自定义对话框。我让对话框在没有按钮的情况下单独工作,并且在研究了我需要对话框构建器的按钮之后。我试过这样:

package com.example.beerportfoliopro;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.beerportfolio.beerportfoliopro.R;
import com.example.beerportfoliopro.Search.ReadJSONResult;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RatingBar.OnRatingBarChangeListener;


public class BeerPage extends ActionbarMenu  {

    BeerData e;
    Dialog dialog = null;
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.beer_page);

        //get data from listview
        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        e = b.getParcelable("myBeerObject"); 


      //test shared prefs


        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);

        //set image
        ImageView im1 = (ImageView) findViewById(R.id.image);
        if(e.largeLabel.equals("N/A")){
            //set image as png
            im1.setImageResource( R.drawable.noimage);
        }

        else{
            ImageDownloadTask imageD = new ImageDownloadTask(im1);
            imageD.execute(e.largeLabel);
        }

        //check if user has beer
        String url = "anotherURL";
        String userURLComp = "u=" + userID;
        String beerID = "&b=" + e.beerId;

        url = url + userURLComp + beerID;


        new CheckBeerJSON(this,e.beerId).execute(url);


        String url2 = "myURL";
        new GetBeerRateJSON(this,e.beerId).execute(url2);

        //inflate loder image
        LayoutInflater mInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout addButton = (LinearLayout)((Activity) this).findViewById(R.id.addBeerLayout);
        addButton.addView(mInflater.inflate(R.layout.checkingportfolio, null)); 

        //prepare buttons
        //Button buttonBrewery = (Button) findViewById(R.id.buttonBrewery);
        //Button buttonStyle = (Button) findViewById(R.id.buttonStyle);

        //prepare text things
        TextView tv1 = (TextView) findViewById(R.id.beerTitle);
        TextView tv2 = (TextView) findViewById(R.id.beerDescription);
        TextView tv_ibu = (TextView) findViewById(R.id.IBU);
        TextView tv_abv = (TextView) findViewById(R.id.abv);
        TextView tv_glass = (TextView) findViewById(R.id.glass);
        TextView tv_breweryName = (TextView) findViewById(R.id.beerBreweryName);
        TextView tv_styleName = (TextView) findViewById(R.id.beerStyleName);

        //set text thinsg
        tv1.setText(e.beerName); 
        tv2.setText(e.beerDescription); 

        String breweryButton = "Brewery: ";
        String styleButton = "Style: ";

        tv_breweryName.setText(e.beerBreweryName);
        tv_styleName.setText(e.beerStyle);


        breweryButton = breweryButton + e.beerBreweryName;
        styleButton = styleButton + e.beerStyle;


        //buttonBrewery.setText(breweryButton);
        //buttonStyle.setText(styleButton);


        tv_ibu.setText(e.beerIBU);
        tv_abv.setText(e.beerABV);
        tv_glass.setText(e.beerGlass);

        //Toast.makeText(this,  e.mediumLabel, Toast.LENGTH_SHORT).show();





    }

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

        return true;
    }

    //view brewery function
    public void viewBrewery(View view) {

        // launch new brewery page class
        Intent i = new Intent(this, BreweryPage.class);
        i.putExtra("myBeerObject",  e);   
        i.setClass(this, BreweryPage.class);


        startActivity(i); 


     }



public void viewStyle(View view) {

        // launch new brewery page class
        Intent i = new Intent(this, BreweryPage.class);
        i.putExtra("myBeerObject",  e);   
        i.setClass(this, StylePage.class);


        startActivity(i); 


     }

//view brewery function
    public void viewTasteTags(View view) {

        // launch new brewery page class
        Intent i = new Intent(this, BreweryPage.class);
        i.putExtra("myBeerObject",  e);   
        i.setClass(this, TasteTags.class);
        startActivity(i); 


     }

public String encodeThisWord(String word){

    try {
        word = URLEncoder.encode(word, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        return word;

}

public void addBeer(View view){

    //get user info
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String userName = prefs.getString("userName", null);
    String userID = prefs.getString("userID", null);


    //get beer details
    String url = "http://www.beerportfolio.com/app_addBeer.php?";
    String urlUserID = "u=" + userID;
    String urlBeerID = "&bID=" + e.beerId;
    String urlBeerName = "&bName=" + encodeThisWord(e.beerName);




    //construct url for adding beer
    url = url + urlUserID + urlBeerID + urlBeerName;

    Log.d("url", url);

    //execute async on url to add to brewery
    new AddBeer(this).execute(url);

    //to do: change to start rater
    LinearLayout ll = (LinearLayout) findViewById(R.id.addBeerLayout);
    ll.removeAllViews();

    //add rater

    LayoutInflater inflater = (LayoutInflater)this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
    LinearLayout addButton = (LinearLayout)this.findViewById(R.id.addBeerLayout);
    addButton.addView(inflater.inflate(R.layout.addrate_layout, null)); 

    addListenerOnRatingBar(this);



}

private void addListenerOnRatingBar(BeerPage beerPage) {
    RatingBar ratingBar = (RatingBar) this.findViewById(R.id.beerRatingBar);

    ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
        public void onRatingChanged(RatingBar ratingBar, float rating,
            boolean fromUser) {

            //next async task to update online database
            float stars = ratingBar.getRating();

            //get user details
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(BeerPage.this);
            String userID = prefs.getString("userID", null);

            //get beer id
            String beerID = e.beerId;

            //get rating
            String urlRate = "r=" + String.valueOf(ratingBar.getRating());
            String urlUserID = "&u=" + userID;
            String urlBeerID = "&b=" + beerID;

            //construct url
            String url2 = "http://www.beerportfolio.com/app_rateUpdate.php?";

            url2 = url2 + urlRate + urlUserID + urlBeerID;

            Log.d("addRateing", url2);

            //async task to update rating in database
            new UpdateRating(BeerPage.this).execute(url2);





        }
    });



}

    public void rateDialog(View v){
        // custom dialog

        AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
// Add the buttons
        builder.setPositiveButton("save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
            }
        });
        builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
            }
        });
// Set other dialog properties


// Create the AlertDialog
        AlertDialog dialog = builder.create();

        dialog.setContentView(R.layout.rate_stars);
        dialog.setTitle("Rate this Beer");
        dialog.show();


    }





}

当我运行此活动时,它现在强制关闭并给我这个错误:

09-26 16:37:50.166  18581-18581/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.beerportfolio.beerportfoliopro/com.example.beerportfoliopro.BeerPage}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2248)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
        at android.app.ActivityThread.access$600(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:155)
        at android.app.ActivityThread.main(ActivityThread.java:5536)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.NullPointerException
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:132)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:66)
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
        at android.app.AlertDialog$Builder.<init>(AlertDialog.java:359)
        at com.example.beerportfoliopro.BeerPage.<init>(BeerPage.java:62)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1319)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1070)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2239)
        ... 11 more
09-26 16:37:50.176   

下面 SSantos 的建议让活动开始,但现在当我尝试打开对话框时,我得到另一个力量关闭此错误:

09-26 17:57:32.107  31185-31185/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
        java.lang.IllegalStateException: Could not execute method of the activity
        at android.view.View$1.onClick(View.java:3609)
        at android.view.View.performClick(View.java:4102)
        at android.view.View$PerformClick.run(View.java:17126)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:155)
        at android.app.ActivityThread.main(ActivityThread.java:5536)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at android.view.View$1.onClick(View.java:3604)
        ... 11 more
        Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
        at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:322)
        at com.android.internal.app.AlertController.installContent(AlertController.java:242)
        at android.app.AlertDialog.onCreate(AlertDialog.java:336)
        at android.app.Dialog.dispatchOnCreate(Dialog.java:364)
        at android.app.Dialog.show(Dialog.java:261)
        at com.example.beerportfoliopro.BeerPage.rateDialog(BeerPage.java:326)
        ... 14 more
4

1 回答 1

1

假设line 62

AlertDialog.Builder builder = new AlertDialog.Builder(this);

很有可能你在错误的地方实例化了你的对话框。尝试将其声明为

AlertDialog.Builder builder;

onCreate并在方法内实例化它。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.beer_page);

    builder = new AlertDialog.Builder(this);

    // The rest of your stuff
    // ...
}
于 2013-09-26T20:53:44.727 回答