2013-09-26 2 views
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(); 


    } 





} 

나는 지금 닫히고 강제로이 활동을 실행하고 날이 오류를 줄 때 : SSantos에 의해 제안 아래 내가하려고 할 때 지금 시작하지만,하는 활동을 얻었다

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 

나는이 오류와 가까운 또 다른 힘을 얻을 대화 엽니 다

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 
+0

어떤 라인이 BeerPage입니까 : 62입니까? – ssantos

+0

62 번째 줄의 NullPointer는 onCreate 메서드 호출 일 수 있습니까? 아마도 Theme가 없습니까? (스택 추적을 기반으로). AndroidManifest.xml 파일의 모양은 무엇입니까? – MiStr

+0

HTTP 호출/URL 생성을 위해 [AndroidQuery] (https://code.google.com/p/android-query/wiki/AsyncAPI)라고하는 간단한 프레임 워크를 권하고 싶습니다. – MiStr

답변

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 
    // ... 
} 
+0

이렇게하면 액티비티가 실행됩니다. 대화 상자가 시작하려고하면 오류가 발생합니다. 위 코드에서 새 오류를 추가했습니다. – Mike

+0

'DialogBuilder'를 사용하고 계십니까? 대화 상자를 표시하기 직전에 새 인스턴스를 다시 인스턴스화하지만이 대신 v.getContext()를 전달합니다. – ssantos

+0

이 그것을 시도하고 여전히 작동하지 않았다. 나는이 질문을 닫고 내 원래의 문제를 고쳐서이 질문에 대한 또 다른 질문을 할 것이기 때문에 대답을 받아 들일 것입니다. – Mike