error: 不兼容的类型:MainFragment 无法转换为 Activity

huangapple go评论159阅读模式
英文:

error: incompatible types: MainFragment cannot be converted to Activity

问题

Java类 "MainFragment"

package com.example.licenta23;

import android.Manifest;
import android.app.AppComponentFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;

public class MainFragment extends Fragment {

    EditText actv1, edtModel, actv2, actv3, actv4, edtFabricatie, edtPret;
    Button btnChoose, btnAdd, btnList;
    ImageView imageView3;

    final int REQUEST_CODE_GALLERY = 999;

    public static SQLiteHelper sqLiteHelper;

    private static final String[] CAROSERIE = new String[] {
            "Cabrio", "Berlina", "Coupe", "Pick-up", "Hatchback", "Break", "Off-road", "Minibus", "Monovolum", "SUV"
    };

    private static final String[] COMBUSTIBIL = new String[] {
            "Benzina", "Diesel", "GPL", "Electric", "Hibrid"
    };

    private static final String[] CULOARE = new String[] {
            "Alb", "Negru", "Gri", "Argintiu", "Albastru", "Rosu", "Verde", "Auriu", "Galben", "Portocaliu", "Maro", "Bej", "Alta culoare"
    };


    private List<MarcaItem> marcaList;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);


        fillMarcaList();


        AutoCompleteTextView editText = view.findViewById(R.id.actv1);
        AutoCompleteMarcaAdapter adapter = new AutoCompleteMarcaAdapter(getActivity(), marcaList);
        editText.setAdapter(adapter);

        AutoCompleteTextView editText2 = view.findViewById(R.id.actv2);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, CAROSERIE);
        editText2.setAdapter(adapter2);

        AutoCompleteTextView editText3 = view.findViewById(R.id.actv3);
        ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, COMBUSTIBIL);
        editText3.setAdapter(adapter3);

        AutoCompleteTextView editText4 = view.findViewById(R.id.actv4);
        ArrayAdapter<String> adapter4 = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, CULOARE);
        editText4.setAdapter(adapter4);



        return view;
    }

    private void fillMarcaList() {
        marcaList = new ArrayList<>();
        marcaList.add(new MarcaItem("Alfa Romeo", R.drawable.alfa_romeo));
        marcaList.add(new MarcaItem("Audi", R.drawable.audi));
        marcaList.add(new MarcaItem("Bmw", R.drawable.bmw));
        marcaList.add(new MarcaItem("Chevrolet", R.drawable.chevrole));
        marcaList.add(new MarcaItem("Citroen", R.drawable.citroen));
        marcaList.add(new MarcaItem("Dacia", R.drawable.dacia));
        marcaList.add(new MarcaItem("Dodge", R.drawable.dodge));
        marcaList.add(new MarcaItem("Fiat", R.drawable.fiat));
        marcaList.add(new MarcaItem("Ford", R.drawable.ford));
        marcaList.add(new MarcaItem("Honda", R.drawable.honda));
        marcaList.add(new MarcaItem("Hyundai", R.drawable.hyundai));
        marcaList.add(new MarcaItem("Jaguar", R.drawable.jaguar));
        marcaList.add(new MarcaItem("Jeep", R.drawable.jeep));
        marcaList.add(new MarcaItem("Kia", R.drawable.kia));
        marcaList.add(new MarcaItem("Land Rover", R.drawable.landrover));
        marcaList.add(new MarcaItem("Lexus", R.drawable.lexus));
        marcaList.add(new MarcaItem("Mazda", R.drawable.mazda));
        marcaList.add(new MarcaItem("Mercedes-Benz", R.drawable.mercedes));
        marcaList.add(new MarcaItem("Mini Cooper", R.drawable.minicooper));
        marcaList.add(new MarcaItem("Mitsubishi", R.drawable.mitsubishi));
        marcaList.add(new MarcaItem("Nissan", R.drawable.nissan));
        marcaList.add(new MarcaItem("Opel", R.drawable.opel));
        marcaList.add(new MarcaItem("Peugeot", R.drawable.peugeot));
        marcaList.add(new MarcaItem("Pontiac", R.drawable.pontiac));
        marcaList.add(new MarcaItem("Porche", R.drawable.porche));
        marcaList.add(new MarcaItem("Renault", R.drawable.renault));
        marcaList.add(new MarcaItem("Rover", R.drawable.rover));
        marcaList.add(new MarcaItem("Seat", R.drawable.seat));
        marcaList.add(new MarcaItem("Skoda", R.drawable.skoda));
        marcaList.add(new MarcaItem("Smart", R.drawable.smart));
        marcaList.add(new MarcaItem("Subaru", R.drawable.subaru));
        marcaList.add(new MarcaItem("Suzuki", R.drawable.suzuki));
        marcaList.add(new MarcaItem("Toyota", R.drawable.toyota));
        marcaList.add(new MarcaItem("Voltwagen", R.drawable.voltwagen));
        marcaList.add(new MarcaItem("Volvo", R.drawable.volvo));

        init();

        sqLiteHelper = new SQLiteHelper(this, "CarDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS CAR (Id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "alegemarca VARCHAR, model VARCHAR, caroserie VARCHAR, combustibil VARCHAR, culoare VARCHAR, " +
                "fabricatie VARCHAR, pret VARCHAR image BLOG)");

        btnChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(
                        MainFragment.this,
                        new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_GALLERY
                );

            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void init(){
        actv1 = (EditText) getView().findViewById(R.id.actv1);
        edtModel = (EditText) getView().findViewById(R.id.edtModel);
        actv2 = (EditText) getView().findViewById(R.id.actv2);
        actv3 = (EditText) getView().findViewById(R.id.actv3);
        actv4 = (EditText) getView().findViewById(R.id.actv4);
        edtFabricatie = (EditText) getView().findViewById(R.id.edtFabricatie);
        edtPret = (EditText) getView().findViewById

<details>
<summary>英文:</summary>

Java class &quot;MainFragment&quot;

    package com.example.licenta23;

    import android.Manifest;
    import android.app.AppComponentFactory;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.AutoCompleteTextView;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;

    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.core.app.ActivityCompat;
    import androidx.fragment.app.Fragment;

    import java.util.ArrayList;
    import java.util.List;

    public class MainFragment extends Fragment {

    EditText actv1, edtModel, actv2, actv3, actv4, edtFabricatie, edtPret;
    Button btnChoose, btnAdd, btnList;
    ImageView imageView3;

    final int REQUEST_CODE_GALLERY = 999;

    public static SQLiteHelper sqLiteHelper;

    private static final String[] CAROSERIE = new String[] {
            &quot;Cabrio&quot;, &quot;Berlina&quot;, &quot;Coupe&quot;, &quot;Pick-up&quot;, &quot;Hatchback&quot;, &quot;Break&quot;, &quot;Off-road&quot;, &quot;Minibus&quot;, &quot;Monovolum&quot;, &quot;SUV&quot;
    };

    private static final String[] COMBUSTIBIL = new String[] {
            &quot;Benzina&quot;, &quot;Diesel&quot;, &quot;GPL&quot;, &quot;Electric&quot;, &quot;Hibrid&quot;
    };

    private static final String[] CULOARE = new String[] {
            &quot;Alb&quot;, &quot;Negru&quot;, &quot;Gri&quot;, &quot;Argintiu&quot;, &quot;Albastru&quot;, &quot;Rosu&quot;, &quot;Verde&quot;, &quot;Auriu&quot;, &quot;Galben&quot;, &quot;Portocaliu&quot;, &quot;Maro&quot;, &quot;Bej&quot;, &quot;Alta culoare&quot;
    };


    private List&lt;MarcaItem&gt; marcaList;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);


        fillMarcaList();


        AutoCompleteTextView editText = view.findViewById(R.id.actv1);
        AutoCompleteMarcaAdapter adapter = new AutoCompleteMarcaAdapter(getActivity(), marcaList);
        editText.setAdapter(adapter);

        AutoCompleteTextView editText2 = view.findViewById(R.id.actv2);
        ArrayAdapter&lt;String&gt; adapter2 = new ArrayAdapter&lt;String&gt;(getActivity(),
                android.R.layout.simple_list_item_1, CAROSERIE);
        editText2.setAdapter(adapter2);

        AutoCompleteTextView editText3 = view.findViewById(R.id.actv3);
        ArrayAdapter&lt;String&gt; adapter3 = new ArrayAdapter&lt;String&gt;(getActivity(),
                android.R.layout.simple_list_item_1, COMBUSTIBIL);
        editText3.setAdapter(adapter3);

        AutoCompleteTextView editText4 = view.findViewById(R.id.actv4);
        ArrayAdapter&lt;String&gt; adapter4 = new ArrayAdapter&lt;String&gt;(getActivity(),
                android.R.layout.simple_list_item_1, CULOARE);
        editText4.setAdapter(adapter4);



        return view;
    }

    private void fillMarcaList() {
        marcaList = new ArrayList&lt;&gt;();
        marcaList.add(new MarcaItem(&quot;Alfa Romeo&quot;, R.drawable.alfa_romeo));
        marcaList.add(new MarcaItem(&quot;Audi&quot;, R.drawable.audi));
        marcaList.add(new MarcaItem(&quot;Bmw&quot;, R.drawable.bmw));
        marcaList.add(new MarcaItem(&quot;Chevrolet&quot;, R.drawable.chevrole));
        marcaList.add(new MarcaItem(&quot;Citroen&quot;, R.drawable.citroen));
        marcaList.add(new MarcaItem(&quot;Dacia&quot;, R.drawable.dacia));
        marcaList.add(new MarcaItem(&quot;Dodge&quot;, R.drawable.dodge));
        marcaList.add(new MarcaItem(&quot;Fiat&quot;, R.drawable.fiat));
        marcaList.add(new MarcaItem(&quot;Ford&quot;, R.drawable.ford));
        marcaList.add(new MarcaItem(&quot;Honda&quot;, R.drawable.honda));
        marcaList.add(new MarcaItem(&quot;Hyundai&quot;, R.drawable.hyundai));
        marcaList.add(new MarcaItem(&quot;Jaguar&quot;, R.drawable.jaguar));
        marcaList.add(new MarcaItem(&quot;Jeep&quot;, R.drawable.jeep));
        marcaList.add(new MarcaItem(&quot;Kia&quot;, R.drawable.kia));
        marcaList.add(new MarcaItem(&quot;Land Rover&quot;, R.drawable.landrover));
        marcaList.add(new MarcaItem(&quot;Lexus&quot;, R.drawable.lexus));
        marcaList.add(new MarcaItem(&quot;Mazda&quot;, R.drawable.mazda));
        marcaList.add(new MarcaItem(&quot;Mercedes-Benz&quot;, R.drawable.mercedes));
        marcaList.add(new MarcaItem(&quot;Mini Cooper&quot;, R.drawable.minicooper));
        marcaList.add(new MarcaItem(&quot;Mitsubishi&quot;, R.drawable.mitsubishi));
        marcaList.add(new MarcaItem(&quot;Nissan&quot;, R.drawable.nissan));
        marcaList.add(new MarcaItem(&quot;Opel&quot;, R.drawable.opel));
        marcaList.add(new MarcaItem(&quot;Peugeot&quot;, R.drawable.peugeot));
        marcaList.add(new MarcaItem(&quot;Pontiac&quot;, R.drawable.pontiac));
        marcaList.add(new MarcaItem(&quot;Porche&quot;, R.drawable.porche));
        marcaList.add(new MarcaItem(&quot;Renault&quot;, R.drawable.renault));
        marcaList.add(new MarcaItem(&quot;Rover&quot;, R.drawable.rover));
        marcaList.add(new MarcaItem(&quot;Seat&quot;, R.drawable.seat));
        marcaList.add(new MarcaItem(&quot;Skoda&quot;, R.drawable.skoda));
        marcaList.add(new MarcaItem(&quot;Smart&quot;, R.drawable.smart));
        marcaList.add(new MarcaItem(&quot;Subaru&quot;, R.drawable.subaru));
        marcaList.add(new MarcaItem(&quot;Suzuki&quot;, R.drawable.suzuki));
        marcaList.add(new MarcaItem(&quot;Toyota&quot;, R.drawable.toyota));
        marcaList.add(new MarcaItem(&quot;Voltwagen&quot;, R.drawable.voltwagen));
        marcaList.add(new MarcaItem(&quot;Volvo&quot;, R.drawable.volvo));

        init();

        sqLiteHelper = new SQLiteHelper(this, &quot;CarDB.sqlite&quot;, null, 1);

        sqLiteHelper.queryData(&quot;CREATE TABLE IF NOT EXISTS CAR (Id INTEGER PRIMARY KEY AUTOINCREMENT, 
        alegemarca VARCHAR, model VARCHAR, caroserie VARCHAR, combustibil VARCHAR, culoare VARCHAR, 
        fabricatie VARCHAR, pret VARCHAR image BLOG)&quot;);

        btnChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(
                        MainFragment.this,
                        new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_GALLERY
                );

            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void init(){
        actv1 = (EditText) getView().findViewById(R.id.actv1);
        edtModel = (EditText) getView().findViewById(R.id.edtModel);
        actv2 = (EditText) getView().findViewById(R.id.actv2);
        actv3 = (EditText) getView().findViewById(R.id.actv3);
        actv4 = (EditText) getView().findViewById(R.id.actv4);
        edtFabricatie = (EditText) getView().findViewById(R.id.edtFabricatie);
        edtPret = (EditText) getView().findViewById(R.id.edtPret);
        btnChoose = (Button) getView().findViewById(R.id.btnChoose);
        btnAdd = (Button) getView().findViewById(R.id.btnAdd);
        btnList = (Button) getView().findViewById(R.id.btnList);
        imageView3 = (ImageView) getView().findViewById(R.id.imageView3);
     }

    }


 SQL database &quot;SQLiteHelper.java&quot; 

    package com.example.licenta23;

    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.database.sqlite.SQLiteStatement;

    import androidx.annotation.Nullable;

    public class SQLiteHelper extends SQLiteOpenHelper {

    public SQLiteHelper(@Nullable MainFragment context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public void queryData(String sql){
        SQLiteDatabase database = getWritableDatabase();
        database.execSQL(sql);
    }

    public void insertData(String alegemarca, String model, String caroserie, String combustibil, String culoare, String fabricatie, String pret, byte[] image) {
        SQLiteDatabase database = getWritableDatabase();
        String sql = &quot;INSERT INTO CAR VALUES (NULL, ?, ?, ?)&quot;;

        SQLiteStatement statement = database.compileStatement(sql);
        statement.clearBindings();

        statement.bindString(1, alegemarca);
        statement.bindString(2, model);
        statement.bindString(3, caroserie);
        statement.bindString(4, combustibil);
        statement.bindString(5, culoare);
        statement.bindString(6, fabricatie);
        statement.bindString(7, pret);
        statement.bindBlob(8, image);

        statement.executeInsert();
    }

    public Cursor getData(String sql){
        SQLiteDatabase database = getReadableDatabase();
        return database.rawQuery(sql, null);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

     }
    }


And, my error is: 

    C:\Users\tibim\AndroidStudioProjects\licenta23\app\src\main\java\com\example\licenta23\MainFragment.java:130: error: incompatible types: MainFragment cannot be converted to Activity
                        MainFragment.this,



</details>


# 答案1
**得分**: 1

首先将您的构造函数助手更改如下移除MainFragment并设置Context):

```java
public SQLiteHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

接下来,在您的片段中初始化活动如下:

private AppCompatActivity activity;

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    if (context instanceof AppCompatActivity) {
        activity = (AppCompatActivity) context;
    }
}

然后,将您的助手和点击监听器更改为以下以获取权限:

//...
sqLiteHelper = new SQLiteHelper(activity, "CarDB.sqlite", null, 1);

//...
btnChoose.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        ActivityCompat.requestPermissions(
            // 这里进行更改
            activity,
            new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_CODE_GALLERY
        );
    }
});
英文:

first of all change your constructor helper like this(remove MainFragment and set Context):

 public SQLiteHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}

next in your fragment inicialize activity like this:

   private AppCompatActivity activity;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof AppCompatActivity) {
activity = (AppCompatActivity) context;
}
}

next change your helper and clicklistener for permission:

  //...
sqLiteHelper = new SQLiteHelper(activity, &quot;CarDB.sqlite&quot;, null, 1);
//...
btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
//this change
activity,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});

huangapple
  • 本文由 发表于 2020年4月4日 22:41:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61029763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定