1

사용자 정의 Adapter이 있고 사용자의 getView() 메소드 내에 사용자가 Button을 클릭 할 때 경고 대화 상자를 시작하려고하는데 오류가 발생합니다. 나는 누군가가 여기에 사용자 정의 어댑터의 getView 내에서 DialogFragment를 시작합니다

내 사용자 정의 어댑터 여기 나를 도울 수 있기를 바랍니다 :

package com.example.android.testappsfeatures; 

import android.content.Context; 
import android.graphics.Color; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentTransaction; 
import android.support.v7.app.AppCompatActivity; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import java.text.NumberFormat; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Date; 


/** 
* Created by korchix on 05.02.17. 
*/ 

public class UserAdapter extends ArrayAdapter<UserCard> { 

    Context context = getContext().getApplicationContext();  

    public UserAdapter(Context context, ArrayList<UserCard> userCards) { 
     super(context, 0, userCards); 
    } 


    // override getView because where are using other view than just TV alone. 
    @Override 
    public View getView(final int position, View convertView, final ViewGroup parent) { 
     // get the data item for this position 
     final UserCard newUser = getItem(position); 
     final ViewHolder holder = new ViewHolder(); 
     // check if an existing view is being reused, otherwise inflate the view 
     if(convertView == null){ 
      convertView = LayoutInflater.from(getContext()).inflate(R.layout.user_layout, parent, false); 
     } 

     View userCardbackgroundColor = convertView.findViewById(R.id.userCard); 
     userCardbackgroundColor.setBackgroundColor(Color.WHITE); 


     // Lookup view for data population 
     holder.userNameTV = (TextView) convertView.findViewById(R.id.name_textView); 
     holder.userNameTV.setText(newUser.getUserName()); 

     holder.gutHabenTV = (TextView) convertView.findViewById(R.id.guthaben_textView); 
     holder.gutHabenTV.setText(NumberFormat.getCurrencyInstance().format(Double.parseDouble(newUser.getGuthaben()))); 

     holder.timeStampTV = (TextView) convertView.findViewById(R.id.datumUhrzeit_textVie); 
     holder.timeStampTV.setText(newUser.getTimeStamp()); 

     holder.plusButton = (Button) convertView.findViewById(R.id.plusButton_Layout); 
     holder.plusButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

     **// HERE IS THE PROBLEM** 
       FragmentManager fm = ((AppCompatActivity) context).getSupportFragmentManager(); 
       FragmentTransaction fragmentTransaction = fm.beginTransaction(); 
       AddBalanceDialog addBalanceDialog = new AddBalanceDialog(); 
       fragmentTransaction.replace(R.id.containerLayoutID, addBalanceDialog); 
       fragmentTransaction.commit(); 

      } 
     }); 
     return convertView; 
    } 
} 



class ViewHolder { 
    TextView userNameTV; 
    TextView gutHabenTV; 
    TextView timeStampTV; 
    Button plusButton; 
    Button minusButton; 
} 

그리고 이것은 내가 plusButton.setOnClickListener(new View.OnClickListener()

를 클릭했을 때이 오류가있어 AlertDialog (DialogFragment)

package com.example.android.testappsfeatures; 

import android.app.AlertDialog; 
import android.app.Dialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.support.v4.app.DialogFragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 

/** 
* Created by korchix on 04.02.17. 
*/ 

public class AddBalanceDialog extends DialogFragment { 
    Context context; 
    InputUserDataDialog inputUserDataDialog = new InputUserDataDialog(); 




    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     context = getActivity().getApplicationContext(); 
     //user Dialog class for convenient dialog construction 
     AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); 
     // get the layoutInflater 
     LayoutInflater inflater = getActivity().getLayoutInflater(); 
     // inflate our custom Layout for the dialog to a View 
     View view = inflater.inflate(R.layout.add_guthaben, null); 

     final TextView guthabenTV = (TextView) view.findViewById(R.id.guthaben_textView); 

     final EditText addGuthabenET = (EditText) view.findViewById(R.id.add_guthaben_LayoutET); 

     // inform the dialog it has a custom View 
     dialog.setView(view); 

     // when positiv button clicked 
     dialog.setPositiveButton(R.string.dialog_ok_buttom, new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       String input = addGuthabenET.getText().toString(); 

       guthabenTV.setText(input); 


       // hier muss noch was 
       // gemacht werden 
      } 
     }) 
       .setNegativeButton(R.string.dialog_cancel_button, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         // discard the input -> don't make any change 
         dialog.cancel(); 

        } 
       }); 

     return dialog.create(); 
    } 

} 

코드입니다

E/AndroidRuntime: FATAL EXCEPTION: main 
                         Process: com.example.android.testappsfeatures, PID: 30548 
java.lang.ClassCastException: android.app.Application cannot be cast to android.support.v7.app.AppCompatActivity 
at com.example.android.testappsfeatures.UserAdapter$1.onClick(UserAdapter.java:83) 
at android.view.View.performClick(View.java:4756) 
at android.view.View$PerformClick.run(View.java:19749) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 

내가 여기 읽었을 때 컨텍스트와 관련된 문제인 경우 Application Context을 제공하지만 Activity context을 제공해야합니다.이 작업을 수행하는 방법을 모르겠습니다.

다음은 응용 프로그램 컨텍스트를 전달하는 당신이 잘못되는 FragmentActivity로 다시 캐스팅하려고 내 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.android.testappsfeatures"> 

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity 
      android:name=".InputGuthabenActivity" 
      android:label="@string/addGuthabenTitle" 
      android:theme="@style/Theme.AppCompat.Light.Dialog.Alert" /> 
    </application> 

</manifest> 
+0

그냥'getApplicationContext을 제거 :) 일이()'비트 –

+0

@Mehmet 은 내가 getApplicationContext을 제거()하지만 난 같은 오류가 발생합니다 : java.lang.ClassCastException가를 : android.app.Application이 될 수 없다 FragmentManager fm = ((AppCompatActivity) context)에서 android.support.v7.app.AppCompatActivity 으로 캐스트하십시오. .getSupportFragmentManager(); – korchix

+0

와인을 가리키고 있습니까? –

답변

0

입니다. Activity 참조를 직접 전달할 수도 있습니다.

변경

context = getActivity().getApplicationContext(); 

어댑터의 생성자에서

context = getActivity(); 
+0

내가 할 수없는 이유 Context context = getActivity(); 오류가 발생했습니다. Methode 'getActivity()'을 (를) 해석 할 수 없습니다. – korchix

+1

@korchix 이미 사용 중입니다. 어떻게 해결 될 수 없습니까? –

+0

OKOK : 은 내가 getApplicationContext() 을 제거하지만 난 같은 에로을 얻을 : java.lang.ClassCastException가 : android.app.Application이 FragmentManager의 FM =에 android.support.v7.app.AppCompatActivity 캐스트 할 수없는 ((AppCompatActivity) 컨텍스트) .getSupportFragmentManager(); – korchix

0

하려면 context 매개 변수가있다. 이 값을 field으로 지정하고 this.context = context;으로 선언하십시오. 그런 다음 어댑터에 컨텍스트가 필요할 때마다이 컨텍스트를 사용하십시오.

+0

나는 이것을했다 : 'public class UserAdapter extends ArrayAdapter { 컨텍스트 mContext; 공용 UserAdapter (컨텍스트 컨텍스트, ArrayList userCards) { super (컨텍스트, 0, userCards); this.mContext = context; }' 하지만 같은 오류가 발생했습니다 : java.lang.ClassCastException : android.app.Application을 android.support.v7.app.AppCompatActivity로 캐스팅 할 수 없습니다. – korchix

+0

코드의 나머지 부분을 변경 했습니까? "그런 다음 어댑터에 컨텍스트가 필요할 때마다이 컨텍스트를 사용하십시오." 나는 또한 당신이 아무것도 던지면 안된다는 것을 암시합니다. –

+0

아마 http://stackoverflow.com/questions/3572463/what-is-context-on-android, http://stackoverflow.com/questions/5018545를 읽어야합니다./getapplication-vs-getapplicationcontext 및 http://stackoverflow.com/questions/6229052/difference-in-context-this-and-getcontext –

0

마지막으로 확인했습니다. 내가 그것을 어떻게했는지 대답에 관심이있는 사람들을 위해, 여기 : 내가 ArrayAdapter와를 인스턴스화 MainActivity.class에서

을, 나는이

UserAdapter userAdapter = new UserAdapter(this, arrayOfUsersNames, fm); 

와 나는 같은 thisgetApplicationContext에서 컨텍스트를 변경 버튼을 클릭하는 온 클릭()에서 다음이

public class UserAdapter extends ArrayAdapter<UserCard>{ 
    Context mContext; 
    AddBalanceDialog addBalanceDialog = new AddBalanceDialog(); 
    FragmentManager mFragmentManager; 

    public UserAdapter(Context context, ArrayList<UserCard> userCards, FragmentManager fragmentManager) { 

     super(context, 0, userCards); 
     mContext = context; 
     mFragmentManager = fragmentManager; 
    } 

처럼 내 UserAdapter의 생성자에 FragmentManager를 추가, 내가 경고 대화을 보여,이 코드 줄을 추가3210 'addBalanceDialog.show(mFragmentManager, "test"); ' 하고