java.lang.ClassCastException: com.pdf.ViewPdf нельзя преобразовать в android.app.Activity

Я заполняю CustomListView CustomAdapter и помещаю прослушиватель на LinearLayout, потому что, когда я нажимаю, открывается AlertDialog и спрашиваю меня, хочу ли я перейти к другому Activity, который открывает pdf.

Поэтому я поместил прослушиватель в метод getView() и Intent в метод onClick моего AlerDialog.

Мой класс CustomAdapter расширяет Activity и реализует ListAdapter. Поэтому я не понимаю, почему он не может пойти на другое занятие.

Это мой класс CustomAdapter:

 package com.listpoint;

import java.util.ArrayList;
import java.util.HashMap;

import com.main.R;
import com.pdf.ViewPdf;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class CustomListingCrossAdapter extends Activity implements ListAdapter {
public Integer selectedPosition = null;

public LayoutInflater m_inflater;
public Context ctx;
public ArrayList<HashMap<String, String>> listItem; 
public CustomListingCrossHolder holder;
public ListView listView;
public AsyncTaskSet asyncTaskSet;

public CustomListingCrossAdapter(Context newCtx, ArrayList<HashMap<String, String>> newListItem, ListView listView) {
    this.ctx = newCtx;
    this.listItem = newListItem;
    this.m_inflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);      
    this.listView = listView;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return this.listItem.size();
}

@Override
public Object getItem(int position) {
    return this.listItem.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public boolean hasStableIds() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final HashMap<String, String> object = (HashMap<String, String>) this.getItem(position);
    final ListCrossingPoint listCrossingPointClass = new ListCrossingPoint();   
    selectedPosition = position;
    if (convertView == null) {
      holder = new CustomListingCrossHolder();  

      convertView = m_inflater.inflate(R.layout.list_type_tournee, null);


      holder.producer_id = (TextView) convertView.findViewById(R.id.producer_id);
      holder.product_code = (TextView) convertView.findViewById(R.id.product_code);
      holder.begin_hour = (TextView) convertView.findViewById(R.id.begin_hour);
      holder.end_hour = (TextView) convertView.findViewById(R.id.end_hour);
      holder.tel = (TextView) convertView.findViewById(R.id.tel);
      holder.fax = (TextView) convertView.findViewById(R.id.fax);
      holder.adress = (TextView) convertView.findViewById(R.id.adress);
      holder.order = (TextView) convertView.findViewById(R.id.order);
      holder.downtime = (TextView) convertView.findViewById(R.id.downtime);       
      holder.miscellaneous = (TextView) convertView.findViewById(R.id.miscellaneous);
      holder.infos = (TextView) convertView.findViewById(R.id.infos);        
      holder.linear_divers = (LinearLayout) convertView.findViewById(R.id.linear_mis);
      holder.linear_infos = (LinearLayout) convertView.findViewById(R.id.linear_infos);
      holder.linear_pdf = (LinearLayout) convertView.findViewById(R.id.linear_pdf);



      convertView.setTag(holder);

     } else {
      holder = (CustomListingCrossHolder) convertView.getTag();
     }

     holder.producer_id.setText(this.listItem.get(position).get("producer_id")); 
     holder.product_code.setText(this.listItem.get(position).get("product_code")); 
     holder.begin_hour.setText(this.listItem.get(position).get("begin_hour")); 
     holder.end_hour.setText(this.listItem.get(position).get("end_hour")); 
     holder.tel.setText(this.listItem.get(position).get("tel")); 
     holder.fax.setText(this.listItem.get(position).get("fax")); 
     holder.adress.setText(this.listItem.get(position).get("adress")); 
     holder.order.setText(this.listItem.get(position).get("order"));
     holder.downtime.setText(this.listItem.get(position).get("downtime"));
     holder.miscellaneous.setText(this.listItem.get(position).get("miscellaneous")); 
     holder.infos.setText(this.listItem.get(position).get("infos")); 

     /////////Listener to modify miscellaneous parts/////////////
     holder.linear_divers.setOnClickListener(new View.OnClickListener() 
        {               
            public void onClick(View v) 
            {       
                Log.i("Point ","n°"+object.get("id_point"));
                AlertDialog.Builder adb = new AlertDialog.Builder(ctx);     

                final EditText input = new EditText(ctx);
                input.setText(object.get("miscellaneous")+"\n\n");
                adb.setView(input);
                adb.setTitle("Divers");
                adb.setIcon(android.R.drawable.ic_menu_edit);                   
                adb.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton)
                    {                 
                      object.put("miscellaneous", input.getText().toString().trim());                    
                      listView.invalidateViews();   
                      asyncTaskSet = new AsyncTaskSet(ctx,object.get("id_point"),input.getText().toString().trim(),"1");
                      asyncTaskSet.execute();  
                    }
                });
                adb.setNegativeButton("Annuler", null);
                adb.create().show();                    
            }                   
        });         
     /////////Listener to modify infos parts/////////////
     holder.linear_infos.setOnClickListener(new View.OnClickListener() 
        {               
            public void onClick(View v) 
            {                                     
                AlertDialog.Builder adb = new AlertDialog.Builder(ctx);     

                final EditText input = new EditText(ctx);
                input.setText(object.get("infos")+"\n\n");
                adb.setView(input);
                adb.setTitle("Infos collecte");
                adb.setIcon(android.R.drawable.ic_menu_edit);

                adb.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton)
                    {   
                      object.put("infos", input.getText().toString().trim());                    
                      listView.invalidateViews();   
                      asyncTaskSet = new AsyncTaskSet(ctx,object.get("id_point"),input.getText().toString().trim(),"2");
                      asyncTaskSet.execute(); 
                    }
                });
                adb.setNegativeButton("Annuler", null);
                adb.create().show();                    
            }                   
        }); 


     /////////LISTENER TO GO TO THE OTHER ACTIVITY/////////////
     holder.linear_pdf.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) 
            {                   

                AlertDialog.Builder adb = new AlertDialog.Builder(ctx); 
                adb.setTitle("Edition du PDF");
                adb.setIcon(android.R.drawable.ic_menu_info_details);
                adb.setMessage("Etes-vous sûr de vouloir éditer ce point de passage ?");
                adb.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton)
                    {                 
                        Log.i("Point de passage"," id point : "+ object.get("id_point"));   

                        Intent intentPDF = new Intent(ctx, ViewPdf.class);
                        intentPDF.putExtra("id_point", object.get("id_point"));
                        ctx.startActivity(intentPDF);

                        //it's here where there is the problem//
                    }
                });
                adb.setNegativeButton("Annuler", null);
                adb.create().show();                    
            }               
        });         
      //////////////////////////////////////////////////////////



return convertView;
    } 


@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return 1;
}

@Override
public boolean isEmpty() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean areAllItemsEnabled() {
    // TODO Auto-generated method stub
    return true;
}

@Override
public boolean isEnabled(int position) {
    // TODO Auto-generated method stub
    return true;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
    // TODO Auto-generated method stub

}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    // TODO Auto-generated method stub

}

private class CustomListingCrossHolder {
    TextView producer_id;
    TextView adress;
    TextView order;
    TextView infos;
    TextView miscellaneous;
    TextView product_code;
    TextView begin_hour;
    TextView end_hour;
    TextView downtime;
    TextView fax;
    TextView tel;       
    LinearLayout linear_divers;
    LinearLayout linear_infos;
    LinearLayout linear_pdf;
}       
}

и это ошибка в моем LogCat:

03-25 10:15:27.860: E/AndroidRuntime(1924): FATAL EXCEPTION: main
03-25 10:15:27.860: E/AndroidRuntime(1924): java.lang.RuntimeException: Unable to   instantiate activity ComponentInfo{com.main/com.pdf.ViewPdf}: java.lang.ClassCastException:   com.pdf.ViewPdf cannot be cast to android.app.Activity
03-25 10:15:27.860: E/AndroidRuntime(1924):     at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at     android.app.ActivityThread.access$600(ActivityThread.java:130)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at android.os.Looper.loop(Looper.java:137)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at android.app.ActivityThread.main(ActivityThread.java:4745)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at java.lang.reflect.Method.invokeNative(Native Method)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at java.lang.reflect.Method.invoke(Method.java:511)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-25 10:15:27.860: E/AndroidRuntime(1924):     at dalvik.system.NativeStart.main(Native Method)
03-25 10:15:27.860: E/AndroidRuntime(1924): Caused by: java.lang.ClassCastException: com.pdf.ViewPdf cannot be cast to android.app.Activity
03-25 10:15:27.860: E/AndroidRuntime(1924):     at android.app.Instrumentation.newActivity(Instrumentation.java:1053)

Однако я сделал тот же код в своем onPostExecute, чтобы перейти к соединению с моим ListView без расширения Activity


person Thomas Trabelsi    schedule 25.03.2014    source источник
comment
Почему вы бесполезно расширяете Activity ??   -  person kalyan pvs    schedule 25.03.2014
comment
@kalyanpvs да, я знаю, что это не важно, но я хотел попробовать, если возможно... =)   -  person Thomas Trabelsi    schedule 25.03.2014
comment
@ThomasTrabelsi похоже, что ViewPdf не является классом Activity   -  person Raghunandan    schedule 25.03.2014
comment
почему вы хотели .. здесь нет требования, чтобы вы не использовали какие-либо методы жизненного цикла Activity ??   -  person kalyan pvs    schedule 25.03.2014
comment
Я думаю, вы устанавливаете CustomListingCrossAdapter в Listview, который не расширяет BaseAdapter, он расширяет Activity, поэтому он дает вам исключение classClast.   -  person kalyan pvs    schedule 25.03.2014
comment
ИЗВИНИТЕ всем, все работало хорошо, это только я глуп.. Как будто я перезапускаю проект, я забываю реализовать свой класс viewPdf ... извините, извините   -  person Thomas Trabelsi    schedule 25.03.2014
comment
@Raghunandan, когда я вижу ваш комментарий, я сказал, что я очень, очень глуп, потому что я сразу понимаю проблемы ..   -  person Thomas Trabelsi    schedule 25.03.2014
comment
Поэтому, если кто-то ищет, как изменить текстовое представление сразу после касания linear_layout или пользовательского адаптера, есть код, который работает   -  person Thomas Trabelsi    schedule 25.03.2014


Ответы (1)


Извините всех, но я просто забыл реализовать свой класс ViewPdf... И теперь все работает хорошо. Поэтому, если кто-то хочет создать CustomAdapter, вы можете использовать приведенный ниже код, если кто-то хочет попытаться изменить непосредственно после нажатия на линейный макет текстовое представление с помощью AlertDialog, вы можете использовать приведенный ниже код, в противном случае, все равно спасибо.

Мой класс CustomAdapter:

package com.listpoint;

import java.util.ArrayList;
import java.util.HashMap;

import com.main.R;
import com.pdf.ViewPdf;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class CustomListingCrossAdapter implements ListAdapter {
public Integer selectedPosition = null;

public LayoutInflater m_inflater;
public Context ctx;
public ArrayList<HashMap<String, String>> listItem; 
public CustomListingCrossHolder holder;
public ListView listView;
public AsyncTaskSet asyncTaskSet;

public CustomListingCrossAdapter(Context newCtx, ArrayList<HashMap<String, String>> newListItem, ListView listView) {
    this.ctx = newCtx;
    this.listItem = newListItem;
    this.m_inflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);      
    this.listView = listView;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return this.listItem.size();
}

@Override
public Object getItem(int position) {
    return this.listItem.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public boolean hasStableIds() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final HashMap<String, String> object = (HashMap<String, String>) this.getItem(position);
    final ListCrossingPoint listCrossingPointClass = new ListCrossingPoint();   
    selectedPosition = position;
    if (convertView == null) {
      holder = new CustomListingCrossHolder();  

      convertView = m_inflater.inflate(R.layout.list_type_tournee, null);


      holder.producer_id = (TextView) convertView.findViewById(R.id.producer_id);
      holder.product_code = (TextView) convertView.findViewById(R.id.product_code);
      holder.begin_hour = (TextView) convertView.findViewById(R.id.begin_hour);
      holder.end_hour = (TextView) convertView.findViewById(R.id.end_hour);
      holder.tel = (TextView) convertView.findViewById(R.id.tel);
      holder.fax = (TextView) convertView.findViewById(R.id.fax);
      holder.adress = (TextView) convertView.findViewById(R.id.adress);
      holder.order = (TextView) convertView.findViewById(R.id.order);
      holder.downtime = (TextView) convertView.findViewById(R.id.downtime);       
      holder.miscellaneous = (TextView) convertView.findViewById(R.id.miscellaneous);
      holder.infos = (TextView) convertView.findViewById(R.id.infos);        
      holder.linear_divers = (LinearLayout) convertView.findViewById(R.id.linear_mis);
      holder.linear_infos = (LinearLayout) convertView.findViewById(R.id.linear_infos);
      holder.linear_pdf = (LinearLayout) convertView.findViewById(R.id.linear_pdf);



      convertView.setTag(holder);

     } else {
      holder = (CustomListingCrossHolder) convertView.getTag();
     }

     holder.producer_id.setText(this.listItem.get(position).get("producer_id")); 
     holder.product_code.setText(this.listItem.get(position).get("product_code")); 
     holder.begin_hour.setText(this.listItem.get(position).get("begin_hour")); 
     holder.end_hour.setText(this.listItem.get(position).get("end_hour")); 
     holder.tel.setText(this.listItem.get(position).get("tel")); 
     holder.fax.setText(this.listItem.get(position).get("fax")); 
     holder.adress.setText(this.listItem.get(position).get("adress")); 
     holder.order.setText(this.listItem.get(position).get("order"));
     holder.downtime.setText(this.listItem.get(position).get("downtime"));
     holder.miscellaneous.setText(this.listItem.get(position).get("miscellaneous")); 
     holder.infos.setText(this.listItem.get(position).get("infos")); 

     /////////Listener to modify miscellaneous parts/////////////
     holder.linear_divers.setOnClickListener(new View.OnClickListener() 
        {               
            public void onClick(View v) 
            {       
                Log.i("Point ","n°"+object.get("id_point"));
                AlertDialog.Builder adb = new AlertDialog.Builder(ctx);     

                final EditText input = new EditText(ctx);
                input.setText(object.get("miscellaneous")+"\n\n");
                adb.setView(input);
                adb.setTitle("Divers");
                adb.setIcon(android.R.drawable.ic_menu_edit);                   
                adb.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton)
                    {                 
                      object.put("miscellaneous", input.getText().toString().trim());                    
                      listView.invalidateViews();   
                      asyncTaskSet = new AsyncTaskSet(ctx,object.get("id_point"),input.getText().toString().trim(),"1");
                      asyncTaskSet.execute();  
                    }
                });
                adb.setNegativeButton("Annuler", null);
                adb.create().show();                    
            }                   
        });         
     /////////Listener to modify infos parts/////////////
     holder.linear_infos.setOnClickListener(new View.OnClickListener() 
        {               
            public void onClick(View v) 
            {                                     
                AlertDialog.Builder adb = new AlertDialog.Builder(ctx);     

                final EditText input = new EditText(ctx);
                input.setText(object.get("infos")+"\n\n");
                adb.setView(input);
                adb.setTitle("Infos collecte");
                adb.setIcon(android.R.drawable.ic_menu_edit);

                adb.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton)
                    {   
                      object.put("infos", input.getText().toString().trim());                    
                      listView.invalidateViews();   
                      asyncTaskSet = new AsyncTaskSet(ctx,object.get("id_point"),input.getText().toString().trim(),"2");
                      asyncTaskSet.execute(); 
                    }
                });
                adb.setNegativeButton("Annuler", null);
                adb.create().show();                    
            }                   
        }); 


     /////////LISTENER TO GO TO THE OTHER ACTIVITY/////////////
     holder.linear_pdf.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) 
            {                   

                AlertDialog.Builder adb = new AlertDialog.Builder(ctx); 
                adb.setTitle("Edition du PDF");
                adb.setIcon(android.R.drawable.ic_menu_info_details);
                adb.setMessage("Etes-vous sûr de vouloir éditer ce point de passage ?");
                adb.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton)
                    {                 
                        Log.i("Point de passage"," id point : "+ object.get("id_point"));   

                        Intent intentPDF = new Intent(ctx, ViewPdf.class);
                        intentPDF.putExtra("id_point", object.get("id_point"));
                        ctx.startActivity(intentPDF);

                        //it's here where there is the problem//
                    }
                });
                adb.setNegativeButton("Annuler", null);
                adb.create().show();                    
            }               
        });         
      //////////////////////////////////////////////////////////



return convertView;
    } 


@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return 1;
}

@Override
public boolean isEmpty() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean areAllItemsEnabled() {
    // TODO Auto-generated method stub
    return true;
}

@Override
public boolean isEnabled(int position) {
    // TODO Auto-generated method stub
    return true;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
    // TODO Auto-generated method stub

}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    // TODO Auto-generated method stub

}

private class CustomListingCrossHolder {
    TextView producer_id;
    TextView adress;
    TextView order;
    TextView infos;
    TextView miscellaneous;
    TextView product_code;
    TextView begin_hour;
    TextView end_hour;
    TextView downtime;
    TextView fax;
    TextView tel;       
    LinearLayout linear_divers;
    LinearLayout linear_infos;
    LinearLayout linear_pdf;
}       
}
person Thomas Trabelsi    schedule 25.03.2014