片段和appcompact活动错误

时间:2017-10-27 20:16:44

标签: java android android-fragments

我尝试在与TestactivityPage1 ...的适配器相关的两个活动(recylerviewlistview)中创建一个条形标签,但这些活动类是已经扩展到AppCompatActivity,因为我使用的代码需要AppCompatActivity。 我尝试编写类似(public class Testactivity extends AppCompatActivity, Fragment)的内容,但它仍然显示错误:

'onStop()' in 'android.support.v7.app.appcompatactivity' clashes with 'onStop()' in 'android.support.v4.app.fragment'; attempting to assign weaker access privileges 'protected'; was 'public' class cannot extend multiple classes

这是我的MainActivity课程:

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());


    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).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.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
      switch (position){
          case 0 :
              Testactivity tab1 = new Testactivity();
              return tab1;
          case 1 :
              Page1 tab2 = new Page1();
              return tab2;
          default:
              return null;
      }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "ACCUEIL";
            case 1:
                return "MON COMPTE";

        }
           return null;
    }
}
}

Testactivity上课:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Testactivity extends AppCompatActivity, Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_testactivity, 
container, false);
    return rootView;
}
ArrayList<articles> arrayList;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testactivity);
    arrayList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.ListView1);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            new ReadJSON().execute("http://wach.ma/mobile/home.php");
        }
    });
}

class ReadJSON extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }

    @Override
    protected void onPostExecute(String content) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(content);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = jsonObject.getJSONArray("articles");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject articlesobject = null;
            try {
                articlesobject = jsonArray.getJSONObject(i);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            try {
                arrayList.add(new articles(
                        articlesobject.getString("picture"),
                        articlesobject.getString("title")

                ));
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            CustomListAdaper adaper = new CustomListAdaper(
                    getApplicationContext(), R.layout.custom_list_layout, 
arrayList
            );
            lv.setAdapter(adaper);
        }

    }


    private String readURL(String theURL) {
        StringBuilder content = new StringBuilder();
        try {
            URL url = new URL(theURL);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new 
InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}
}

Page1课程:

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;


public class Page1  extends AppCompatActivity, Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_page1, container, 
false);
    return rootView;
}
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
EditText txt_email, txt_mdp;
Button btn_enter;
Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_page1);
    openHelper=new DatabaseHelper(this);
    db = openHelper.getReadableDatabase();
    txt_email=(EditText)findViewById(R.id.txt_email);
    txt_mdp=(EditText)findViewById(R.id.txt_mdp);
    btn_enter=(Button)findViewById(R.id.btn_enter);
    btn_enter.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            String mdp = txt_mdp.getText().toString();
            String e = txt_email.getText().toString();
            cursor = db.rawQuery("SELECT *FROM " + DatabaseHelper.TABLE_NAME 
+ " WHERE " + DatabaseHelper.COL_5 + "=? AND " + DatabaseHelper.COL_4 + 
"=?", new String[]{e, mdp});
            if (cursor != null)
            {
                if (cursor.getCount() > 0) {
                    cursor.moveToNext();
                    Toast.makeText(getApplicationContext(), "Bienvenue", 
Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(Page1.this, 
Testactivity.class));
                }
                else
                    {
                    Toast.makeText(getApplicationContext(), "Erreur", 
Toast.LENGTH_SHORT).show();
                }
            }



        }

    });}

public void btn_i (View v)
{
    Intent intent = new Intent(Page1.this, Page2.class);
    startActivity(intent);
}


}

activity_testactivity xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"

 tools:context="com.example.lenovo.myapplication.MainActivity$PlaceholderFragment">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo2" />

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true" />
</LinearLayout>

</RelativeLayout>

activity_page1 xml:

<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.lenovo.myapplication.MainActivity$PlaceholderFragment">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout
    android:layout_width="368dp"
    android:layout_height="495dp"
    android:orientation="vertical"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/logo2" />

        <EditText
            android:id="@+id/txt_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Email (adresse  éléctronique)"
            android:inputType="textPersonName"
            android:visibility="visible" />

        <EditText
            android:id="@+id/txt_mdp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Mot de passe"
            android:inputType="textPersonName"
            android:visibility="visible" />

        <Button
            android:id="@+id/btn_enter"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_dark"
            android:text="Connexion"
            android:textColor="@android:color/background_light"
            android:visibility="visible" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            tools:layout_editor_absoluteX="17dp"
            tools:layout_editor_absoluteY="258dp">

            <Button
                android:id="@+id/btn_mdpo"
                android:layout_width="100dp"
                android:layout_height="75dp"
                android:layout_weight="0.18"
                android:text="Mot de passe oublié" />

            <Button
                android:id="@+id/btn_i"
                android:layout_width="100dp"
                android:layout_height="75dp"
                android:layout_weight="0.18"
                android:onClick="btn_i"
                android:text="Créer un compte" />
        </LinearLayout>

    </LinearLayout>
</LinearLayout>

</LinearLayout>

</android.support.constraint.ConstraintLayout>

当我运行项目时,会出现2个错误:

 C:\Users\lenovo\Desktop\Nouveau dossier\MyApplication\app\src\main\java\com\example\lenovo\myapplication\Page1.java
error:'{'expected

 C:\Users\lenovo\Desktop\Nouveau dossier\MyApplication\app\src\main\java\com\example\lenovo\myapplication\Testactivity.java
error:'{'expected

{必须在片段之前

 public class Page1  extends AppCompatActivity, Fragment 

 public class Testactivity  extends AppCompatActivity, Fragment 

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

如以下错误所示:

  'android.support.v7.app.appcompatactivity'中的'onStop()'与'android.support.v4.app.fragment'中的'onStop()'冲突;试图分配较弱的访问权限'protected';是'公共'类不能扩展多个类

这是因为Java语言在Why not multiple inheritance?

不支持多重继承

因此,以下代码是错误的:

public class Page1  extends AppCompatActivity, Fragment {
  ...
}

您需要使用AppCompatActivity或Fragment扩展Page1,但不能同时扩展。{/ p>

因为您希望FragmentPagerAdapter使用以下内容:

public class SectionsPagerAdapter extends FragmentPagerAdapter {
  ...
  public SectionsPagerAdapter(FragmentManager fm) {
    super(fm);
  }

  @Override
  public Fragment getItem(int position) {
    ...
  }
}

需要片段作为getItem()的返回。因此,您需要使用片段扩展Page1Testactivity