application crashes when I move from one fragment to another - java

I have four fragments in my application. the first one gets GPS data for calculating speed which works fine. as soon as the application gets the gps data and move to other fragments it crashes. FYI, other fragments are all without any code.
here is my MainActivity class:
package ir.helpx.speedx;
import android.Manifest;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar =(Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new HomeFragment(), "Home");
viewPagerAdapter.addFragments(new CompassFragment(), "Compass");
viewPagerAdapter.addFragments(new HUDFragment(), "HUD");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"GPS permission granted", Toast.LENGTH_LONG).show();
// get Location from your device by some method or code
} else {
// show user that permission was denied. inactive the location based feature or force user to close the app
}
break;
}
}
}
and my MainActivity XML:
<?xml version="1.0" encoding="utf-8"?>
<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="ir.helpx.speedx.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="368dp"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="8dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="#layout/toolbar_layout"
/>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabLayout"
app:tabMode="fixed"
app:tabGravity="fill"
></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewPager"
></android.support.v4.view.ViewPager>
</android.support.design.widget.AppBarLayout>
</android.support.constraint.ConstraintLayout>
and here is my first Fragment called Home:
package ir.helpx.speedx;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements LocationListener{
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LocationManager mgr;
mgr = (LocationManager)getContext().getSystemService(getActivity().LOCATION_SERVICE);
mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
return inflater.inflate(R.layout.fragment_home, container, false);
}
//TextView msg1;
#Override
public void onLocationChanged(Location location) {
if (location==null){
TextView currentSpeed = null;
}
else {
float nCurrentSpeed = location.getSpeed();
TextView currentSpeed = (TextView) getView().findViewById(R.id.speed);
currentSpeed.setText((int)nCurrentSpeed*18/5+"");
//msg1=currentSpeed;
Toast.makeText(getActivity(), "Location Found!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
and here is the related XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ir.helpx.speedx.HomeFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/speed"
android:gravity="center"
android:textSize="180sp"
android:textStyle="bold"
android:textColor="#android:color/white"
android:id="#+id/speed"/>
</FrameLayout>
and here is my second Fragment:
package ir.helpx.speedx;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class HUDFragment extends Fragment {
public HUDFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_hud, container, false);
}
}
rest of the fragments are similar to
I have a toolbar XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minWidth="?attr/actionBarSize"
android:fitsSystemWindows="true"
android:id="#+id/toolBar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.v7.widget.Toolbar>
and finally my my ViewPagerAdapter:
package ir.helpx.speedx;
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 java.util.ArrayList;
/**
* Created by abe on 5/29/2017.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles){
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
Please HELP me! thank you

I think I could fix it by adding
viewPager.setOffscreenPageLimit(4);
to my MainActivity. I think that was because by default ViewPager retains only one page in the view hierarchy in an idle state. Please tell me if I did the right thing!

Related

Why can't I see any changes in my "Place" tab

I want each tab to to show something different. To start things off, I want to make changes to the Place tab. The problem is, none of the changes are being reflected in the Android Simulator.
Image of what I'm referring to
In this case, I want the text something to show up, but it's not. What am I doing wrong? I've also included code that might be relevant to this issue.
Here's MainActivity.java:
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.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements Place.OnFragmentInteractionListener, Profile.OnFragmentInteractionListener, Take.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Place"));
tabLayout.addTab(tabLayout.newTab().setText("Take"));
tabLayout.addTab(tabLayout.newTab().setText("Profile"));
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Here's fragment_place.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Place"
android:layout_centerInParent="true"
android:textSize="30dp"
android:id="#+id/textView" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="41dp"
android:layout_marginStart="41dp"
android:layout_marginTop="80dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Something" />
</RelativeLayout>
Here's PagerAdapter.java:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNoOfTabs;
public PagerAdapter(FragmentManager fm, int NumberOfTabs) {
super(fm);
this.mNoOfTabs = NumberOfTabs; // set global number of tabs to local number of tabs
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
Place place = new Place();
return place;
case 1:
Profile profile = new Profile();
return profile;
case 2:
Take take = new Take();
return take;
default:
return null;
}
}
#Override
public int getCount() {
return 0;
}
}
I don't see in your code where you provide the layout xml to the fragment
Change the lines to given code.
#Override
public int getCount() {
return mNoOfTabs ;
}
Also make sure you inflate the layout belong to Place (Fragment) onViewCreated() method

fragment and appcompact activity error

I tried to create a bar tabs in two activities (Testactivity and Page1 related with adapters for recylerview and listview...), but those activities classes are extended already to AppCompatActivity because I use some codes needs AppCompatActivity.
I try to write something like (public class Testactivity extends AppCompatActivity, Fragment) but it still shows the errors:
'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
this is my MainActivity class:
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 class:
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 class:
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>
when i run the project, 2 errors coming:
C:\Users\lenovo\Desktop\Nouveau dossier\MyApplication\app\src\main\java\com\example\lenovo\myapplication\Page1.java
error:'{'expected
and
C:\Users\lenovo\Desktop\Nouveau dossier\MyApplication\app\src\main\java\com\example\lenovo\myapplication\Testactivity.java
error:'{'expected
the { must be before fragment in
public class Page1 extends AppCompatActivity, Fragment
and
public class Testactivity extends AppCompatActivity, Fragment
Any help will be appreciated!
As the following error says:
'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
it is because Java language doesn't support multiple inheritance more about it at Why not multiple inheritance?
So, the following code is wrong:
public class Page1 extends AppCompatActivity, Fragment {
...
}
You need to extend the Page1 either with AppCompatActivity or Fragment but not both.
Because you want to use FragmentPagerAdapter with the following:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
...
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
...
}
}
which is need Fragment as the return of getItem(). So, you need to extend the Page1 and Testactivity with Fragment.

Error:(24, 51) error: incompatible types: FragmentAcitvity cannot be converted to Fragment

I am new in android programing. I want to add a facebook login page in my ting an error while adding a fragment in my main activity.
Here is My Fragment Class
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MyFragment extends Fragment {
private OnFragmentInteractionListener mListener;
TextView textView;
private CallbackManager mcallbackManager;
private FacebookCallback<LoginResult> mCallback= new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken= loginResult.getAccessToken();
Profile profile= Profile.getCurrentProfile();
if(profile != null){
textView.setText("Welcome "+ profile.getName());
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MyFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mcallbackManager=CallbackManager.Factory.create();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton=(LoginButton)view.findViewById(R.id.login_button);
loginButton.setReadPermissions("User_Friends");
loginButton.setFragment(this);
loginButton.registerCallback(mcallbackManager, mCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mcallbackManager.onActivityResult(requestCode,resultCode,data);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Fragment XML Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mma.androidfacebook3.MyFrgment"
>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="left|top" />
</RelativeLayout>
MainActivity XML Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="#+id/main_layout">
MainActivity class code
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
Fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment myfragment= new MyFragment();
FragmentManager fragmentManager= getFragmentManager();
FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.main_layout, myfragment, "dfs");
fragmentTransaction.commit();
}
}
Error
Error:(24, 51) error: incompatible types: MyFragment cannot be converted to Fragment
The minimum sdk viersion for this app is 9 and maximus sdk is 21.
It will be very helpfull if anyone suggest me how to solve this problem.
Thank You.
You need to import
import android.support.v4.app.Fragment
instead of
import android.app.Fragment;
in your MainActivity

ListFragment tabs program compiles without any errors but refuses to install

i'm a newbie to android programming.So please pardon me if i'm asking senseless questions.After following a couple of tutorials on how to create ListFragments,the program written compiles with no errors,but refuses to install on AVD.
Here is the error it gives
[2014-05-08 07:44:46 - TabsWithSwipe] Uploading TabsWithSwipe.apk onto device 'emulator- 5554'
[2014-05-08 07:44:46 - TabsWithSwipe] Installing TabsWithSwipe.apk...
[2014-05-08 07:48:59 - TabsWithSwipe] Failed to install TabsWithSwipe.apk on device 'emulator-5554!
[2014-05-08 07:48:59 - TabsWithSwipe] (null)
[2014-05-08 07:49:00 - TabsWithSwipe] Launch canceled!
Here are the individual codes if it would help elaborate the problem.
MainActivity.java
package com.example.tabswithswipe;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.example.tabswithswipe.adapter.TabsPagerAdapter;
#SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements ActionBar.TabListener{
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
//tab titles
private String[] tabs = {"Top Rated","Games","Movies"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//ADding TAbs
for (String tab_name : tabs)
{
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
//on swipping the viewpager make respective tab selected
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int position)
{
//on changing the page
//make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
public void onPageScrollStateChanged(int arg0)
{
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
Here's the class of TabsPagerAdapter
package com.example.tabswithswipe.adapter;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import com.example.tabswithswipe.GamesFragment;
import com.example.tabswithswipe.MoviesFragment;
import com.example.tabswithswipe.TopRatedFragment;
public class TabsPagerAdapter extends FragmentPagerAdapter{
public TabsPagerAdapter(FragmentManager fm){
super(fm);
}
public ListFragment getItem(int index)
{
switch(index)
{
case 0:
//Top Rated fragment activity
return new TopRatedFragment();
case 1:
//Games fragment activity
return new GamesFragment();
case 2:
//Movies fragment activity
return new MoviesFragment();
}
return null;
}
public int getCount()
{
//get item count,equal to number of tabs
return 3;
}
}
Here is one of the custom ListFragments called GameFragments
package com.example.tabswithswipe;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.support.v4.app.ListFragment;
#SuppressLint("NewApi")
public class GamesFragment extends ListFragment {
String[] list_items;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_games, container, false);
list_items = getResources().getStringArray(R.array.my_data_list);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,list_items));
return rootView;
}
}
Here is the xml for this gameFragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff8400"
android:orientation="vertical" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20dp"
android:layout_centerInParent ="true"/>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
The Other two customs listFragment classes and xml's are thesame.
I will appreciate any help out there
It looks like your emulator doesn't support the APIs you use, because the Android-version on your emulator is too low.
Try using an emulator with an android version > 4.0

Buttons within View Pager

I am trying to add buttons within a Fragment of PageView.
Please find attached the code that I am using for this application:
The specific code for the xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/banner_name"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:background="#drawable/button_banner"
android:gravity="center_vertical"
android:paddingLeft="10dip"
android:text="#string/equations"
android:textStyle="bold"
android:textColor="#ffffff" />
</LinearLayout>
<ScrollView
android:id="#+id/ScrollViewEquations"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/Button"
android:layout_width="fill_parent"
android:layout_height="25dip"
android:background="#drawable/custom_button"
android:gravity="center_vertical"
android:paddingLeft="25dip"
android:textColor="#516CE2"
android:text="#string/button" />
</LinearLayout>
</ScrollView>
</LinearLayout
this is the associated fragment code
package com.example.app;
import com.example.app![enter image description here][1].R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
public class EquationsMain extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.equations, container, false);
return view;
}
}
and this is the main code:
package com.example.app;
import com.example.app.R;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Window;
import android.view.WindowManager;
public class Main extends FragmentActivity {
private MyAdapter mAdapter;
private ViewPager mPager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mAdapter = new MyAdapter(getSupportFragmentManager());
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new EquationsMain();
case 1:
return new MaterialsMain();
case 2:
return new AboutMain();
default:
return null;
}
}
}
}

Categories