Android - The constructor is undefined error

2019-08-31 10:25发布

问题:

I want to pass data in fragment activity to another class. But, it makes an error that "The constructor Intent(new View.OnClickListener(){}, Class) is undefined".

with this code

'Intent intent = new Intent(this, WebSocket_Connector.class);'

Here is the code..how can I pass the 'id' string value?

public class Myoffers_Fragment extends Fragment {

    private final WebSocketConnection mConnection = new WebSocketConnection();

    public static Fragment newInstance(Myoffers context, int pos, float scale)
    {
        Bundle b = new Bundle();
        b.putInt("pos", pos);
        b.putFloat("scale", scale);
        return Fragment.instantiate(context, Myoffers_Fragment.class.getName(), b);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }

        LinearLayout l = (LinearLayout) inflater.inflate(R.layout.mf, container, false);

        int pos = this.getArguments().getInt("pos");
        TextView tv = (TextView) l.findViewById(R.id.text);
        tv.setText("Product " + pos);



        ImageButton product_photo = (ImageButton) l.findViewById(R.id.myoffer_image);


        if (pos == 0) {
            product_photo.setImageResource(R.drawable.myoffers_0);
            product_photo.setOnClickListener(new ImageButton.OnClickListener(){
                public void onClick(View v){
                    String id1 = "Product0";
                    Intent intent = new Intent(this, WebSocket_Connector.class);
                    intent.putExtra("KeyToAccessData", id1);
                    startActivity(intent);
                    Log.d(TAG, "Current product is : " + id1);
                    Log.d(TAG, id1 + "is sent to server!");
                }
            });
        }

回答1:

one of the Intent constrcutor takes a paramter a Context and a .class object. So your this has to be a valid context or an Activity. From the documentation:

Parameters

  1. packageContext A Context of the application package implementing this class.
  2. cls The component class that is to be used for the intent.

Change

new Intent(this, WebSocket_Connector.class); 

with

new Intent(getActivity(), WebSocket_Connector.class);


回答2:

Why dont you try this

Intent intent = new Intent(Myoffers_Fragment.this, WebSocket_Connector.class);