Binary XML file line #13 :Error inflating class fragment - java

Can anyone please help me resolve this error?
What I'm trying to do is to get current location using google play services and display city name in edit text inside a fragment.
MainActivity.java
package com.example.mylocationwiki;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
String cityname="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkPlayServices()) {
buildGoogleApiClient();
}
try {
getLocation();
}
catch (Exception e) {
e.printStackTrace();
}
if(cityname!=null)Log.d("pathanor thik agey ", cityname);
new FragmentA(cityname);
}
private void getLocation() throws Exception{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Geocoder gc=new Geocoder(this,Locale.getDefault());
List<Address> addresses=gc.getFromLocation(latitude, longitude, 1);
cityname=addresses.get(0).getLocality();
if(cityname!=null)Log.d("calculate holo ", cityname );
new FragmentA(cityname);
} else{
}
return;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
try {
getLocation();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
}
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:background="#00BBFF"
android:gravity="center"
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="com.example.mylocationwiki.MainActivity" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.mylocationwiki.FragmentA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" /></RelativeLayout>
FragmentA.java
package com.example.mylocationwiki;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentA extends Fragment implements View.OnClickListener{
String cityname="";
Button button;
EditText field;
FragmentA(String cityname){
cityname=this.cityname;
if(cityname!=null)Log.d("received ", cityname);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button=(Button) getActivity().findViewById(R.id.button1);
field=(EditText)getActivity().findViewById(R.id.editText1);
field.setText(cityname);
}
#Override
public void onClick(View v) {
//
}
}
fragment_a.xml
<?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="#FFBB00" >
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="37dp"
android:text="Button" />
</RelativeLayout>
What I have tried so far:
Read this this link :
similar question on SO and made the following changes in my project:
1) Included the following imports:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
2) Made sure that MainActivity extends FragmentActivity
3) Decared getActivity() method inside onActivityCreated() method as nicely suggested here
4) Even the following part is included in my manifest as suggested Here
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Still I fail to resolve the issue. Any more insights please?
Thanks!

I guess the reason is that you don't have a default constructor in your Fragment class. You overloaded the constructor, but Fragment needs an empty one.
Empty Constructor for Extended Fragment
If you need to receive arguments in your fragment, do it using a Bundle:
public static YourFragment getInstance(String argument)
{
YourFragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("argument", argument);
fragment.setArguments(bundle);
return fragment;
}
And from activity:
YourFragment fragment = YourFragment.getInstance(argument);
getFragmentManager().beginTransaction().add(R.id.container, fragment, "fragmentTag").commit();
R.id.container has to be an id of your RelativeLayout (remove <fragment/> from it).
If you still want to use a <fragment/> in xml, then here is a suggestion, how to pass an argument there: If I declare a fragment in an XML layout, how do I pass it a Bundle?

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.

application crashes when I move from one fragment to another

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!

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

How to display selected installed applications in grid view

**I have this code to show the installed applications in Android. I also want to display the selected applications by the user in Grid view. How can I do that in this code?
And is there always a need for adapter for grid-view also?**
This is my first activity:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Startup extends Activity {
Button bIns, bSel;
ArrayList<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bIns = (Button) findViewById(R.id.bList);
bSel = (Button) findViewById(R.id.bGrid);
}
public void viewList(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
public void viewGrid(View view) {
myList = (ArrayList<String>) getIntent().getSerializableExtra("mySelectedList");
Intent intent = new Intent(getApplicationContext(), Last.class);
intent.putExtra("mySelectedList",myList);
startActivity(intent);
}
}
This is my second activity:
package com.abhi.test;
import java.util.ArrayList;
import com.abhi.test.ApplicationAdapter;
import java.util.List;
import com.example.applist.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
Button button;
Bundle bundle;
CheckBox checkbox;
ArrayList<ApplicationInfo> selectedapplication = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
button = (Button) findViewById(R.id.button);
checkbox = (CheckBox) findViewById(R.id.cb_app);
new LoadApplications().execute();
//Intent intent = new Intent(this,Last.class);
}
public void selectedApps(View view) {
//new ApplicationAdapter().selApps();
selectedapplication = ApplicationAdapter.finalList;
Intent intent = new Intent(MainActivity.this, Startup.class);
intent.putExtra("mySelectedList",selectedapplication);
startActivity(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (packageManager.getLaunchIntentForPackage(info.packageName) != null)
{
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.row, applist);
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
}
}
Array adapter for second activity:
package com.abhi.test;
import java.util.ArrayList;
import java.util.List;
import com.example.applist.R;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
int position1;
CheckBox checkBox;
private PackageManager packageManager;
public ArrayList<Boolean> checkList = new ArrayList<Boolean>();
private OnCheckedChangeListener listener;
public static ArrayList<ApplicationInfo> finalList = null;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
for (int i = 0; i < appsList.size(); i++)
{
checkList.add(false);
}
}
#Override
public int getCount() {
if (appsList != null) {
return appsList.size();
} else {
return 0;
}
}
#Override
public ApplicationInfo getItem(int position) {
if (appsList != null) {
return appsList.get(position);
} else {
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override //ibuilt function getView()--responsinle for making views
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if ( view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Understand
view = layoutInflater.inflate(R.layout.row, null);
}
ApplicationInfo data = appsList.get(position);
if (data != null) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
position1=position;
checkBox = (CheckBox) view.findViewById(R.id.cb_app); //understand
checkBox.setTag(Integer.valueOf(position)); // set the tag so we can identify the correct row in the listener
checkBox.setChecked(checkList.get(position)); // set the status as we stored it
checkBox.setOnCheckedChangeListener(mListener); // set the listener
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
/* if(checkBox.isChecked())
{
finalList.add(data);
Toast.makeText(getContext(), "App Added", Toast.LENGTH_LONG).show();
}*/
}
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkList.set((Integer)buttonView.getTag(),isChecked); // get the tag so we know the row and store the status
}
};
}
This is the last activity in which I want to show the selected applications by the user:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
public class Last extends Activity{
GridView gridview;
ArrayList<ApplicationInfo> appList;
String[] appName = new String[100];
String[] appPack = new String[100];
String[] appComp = new String[100];
ArrayList<String> appInfo = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.last);
gridview = (GridView) findViewById(R.id.gridview);
appList = (ArrayList<ApplicationInfo>) getIntent().getSerializableExtra("mylist");
for(int i=0;i<appList.size();i++)
{
appName[i] = appList.get(i).name;
appPack[i] = appList.get(i).packageName;
appComp[i] = appName[i]+appPack[i];
appInfo.add(appComp[i]);
}
/* ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<ApplicationInfo>(this,
android.R.layout.simple_list_item_1, appInfo);
gridview.setAdapter(adapter);*/
}
}
XML for the first activity:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<Button
android:id="#+id/bList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewList"
android:text="#string/bInstalledApps" />
<Button
android:id="#+id/bGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewGrid"
android:text="#string/bSelectedApps" />
</LinearLayout>
XML for the second activity:
<?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" >
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="selectedApps"
android:text="Done"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/button" />
</RelativeLayout>
row.xml for adapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/appdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cb_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:scaleX="1.50"
android:scaleY="1.50" />
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingLeft="5dp" >
<TextView
android:id="#+id/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
<TextView
android:id="#+id/app_paackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
XML for the last activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</LinearLayout>
A GridView is a collection of views in a grid. The Android system doesn't magically know what views you want to be in it. This is where the adapter comes in. By setting an adapter for a GridView, you tell the GridView several things about how you want it to display views including how many views there are and what each view looks like. So yes, all GridViews need adapters.

Categories