Instantiate PagerAdapter Android - android

2Hi guys I'm trying to build an app using a horizontal pager and the support package for Android. I've made this exact code compile in another project but the last line of the second code example is not letting me compile. Eclipse is saying Cannot instantiate the type PagerAdapter
My imports
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
My code
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Tab1.class.getName()));
fragments.add(Fragment.instantiate(this, Tab2.class.getName()));
fragments.add(Fragment.instantiate(this, Tab3.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
Do you think there is something wrong with my imports or project set up - let me know if you need more information. This code has worked in other projects.
Thanks

PagerAdapter is an abstract class – you cannot instantiate it. You have to create a new class that inherits from PagerAdapter and use that instead.

Just create a new class that inherits from PagerAdapter and use it instead.
NB: Don't forget to remove the initial import
"import android.support.v4.view.PagerAdapter;"
and import the newly created class.

Related

Where do I place OnItemClickListener?

I have built a test app that shows few records on a listview.
Now I want to click on an item and see the info on the debug of android studio.
I know I'm supposed to create an OnItemClickListener but I'm not sure where I'm supposed to place it.
I tried placing it on the mainactivity, the app works, but the click function is never called, so there is something wrong.
I looked around Google for some help, but I couldn't wrap my mind around it.
It should be a straightforward action (I have a list, I click an item) but I am not able to make it work.
This what I tried so far:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listViewDemo);
List list = new LinkedList();
list.add(new Contatto("Antonio","Rossi","1234567890"));
list.add(new Contatto("Pino","Bianchi","2345678901"));
list.add(new Contatto("Peppe","Verdi","3456789012"));
list.add(new Contatto("Leo","Rossi","4567890123"));
list.add(new Contatto("Mario","Blu","5678901234"));
list.add(new Contatto("Aldo","Da Vinci","6789012345"));
CustomAdapter adapter = new CustomAdapter(this, R.layout.rowcustom,list);
listView.setAdapter(adapter);
OnItemClickListener clickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
Contatto c = (Contatto)adapter.getItem(position);
Log.d(c.getNome(),c.getTelefono());
}
};
listView.setOnItemClickListener(clickListener);
}
}
OnItemClickListener is not recognized, and getItem neither.
The autocorrect of android Studio proposes me to change to "AdapterView.OnItemClickListener", getItem has nooptions to be recognized.
I tried to add " implements OnItemClickListener" on the class declaration, but it doesn't work either (gives error, name is in red, no solutions are provided by the android studio).
At one point I was able to remove all errors, but the code still didn't work and I don't remember what I did, I was just fiddling.
You can put the OnClickListener in onCreate()
If you post your code, that would certainly help
There are a couple of things that are questionable about the code you posted.
You create OnItemClickListener but you don't have an import for AdapterView.OnItemClickListener. So are you sure you're using the right class?
Inside your onItemClick, you reference adapter, which is the local parameter of type AdapterView<?>, but AdapterView has no such method getItem(int). It can't be a reference to your CustomAdapter because that's not declared final.
Your use of Log.d(c.getNome(),c.getTelefono()); is wrong. The various log methods take a "tag" as the first parameter. It could be that you're not seeing the log messages because that's just wrong.
So, really, this shouldn't even compile. Please review your code and post the most recent, most correct, most compilable version you have. Including the code for you custom adapter and layout wouldn't hurt either.
Have you tried using your debugger to step through this code and seeing if a breakpoint at the click point gets hit?

Android FragmentTabHost questions

I looks like Android FragmentTabHost is poorly documented, so I am trying to understand basic things in this question.
1 Regarding code snippet: http://developer.android.com/reference/android/support/v4/app/FragmentTabHost.html
import com.example.android.supportv4.R;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
/**
* This demonstrates how you can implement switching between the tabs of a
* TabHost through fragments, using FragmentTabHost.
*/
public class FragmentTabs extends FragmentActivity {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
FragmentStackSupport.CountingFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
LoaderCursorSupport.CursorLoaderListFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
LoaderCustomSupport.AppListFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);
}
}
1.1 It shows the programmatic approach to adding tabs. Can I define avoid it? Can I just define everything in XML: number of tabs, their labels, their contents (links to fragment layouts also defined in XML)? If not why, because it looks like a hack to define application layout partially via static XML, programmatically (although the definition it is also static by its nature)?
1.2 Does this snippet imply any XML layout file? Is there an official example for it?
1.3 Supposing that this snippet DOES imply an XML layout file: what is realtabcontent and tabcontent? Should I have both? Why? It looks like some sort of hack again.
2 Here is an unofficial example of using FragmentTabHost http://maxalley.wordpress.com/2013/05/18/android-creating-a-tab-layout-with-fragmenttabhost-and-fragments/
2.1 Why LinearLayout should be put inside android.support.v4.app.FragmentTabHost? Is there an official documentation explaining that?
2.2 Why LinearLayout contains only one FrameLayout, not two like here Android FragmentTabHost - Not fully baked yet? ? Why we do not need #+id/realtabcontent and #android:id/tabs ?

Fragments not working correctly

I have came across a very strange problem, i am using Pager in android to navigate between different screens through fragments in android. also i am using another fragment class to create Layouts automatically in a grid,
for fragment 1, where i have used the pager and pageradapter i am using these imports
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
for the other fragment which i am using to populate images in a non linear Grid, i am using this import
import android.app.Fragment;
The issue is:
By using this import i am unable to add my fragments into the pageradapter. it keeps on giving me error.
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragment.newInstance("Tv Shows"));
fList.add(MyFragment.newInstance("Movies"));
fList.add(MyFragment.newInstance("Music Videos"));
return fList;
}
also i cannot initialize my pageadapter
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
it gives me error on this line to.
My Question is:
what is difference between the two imports
import android.support.v4.app.Fragment;
and
import android.app.Fragment;
is there any solution to the problem, ?
`import android.app.Fragment`
requires minimum API level your app requires is 11 or higher. to use in in application with API less than 11 you need to use support library. when using support library you should use
import android.support.v4.app.Fragment;

FATAL EXCEPTION: main android validation

I have an application in which i want to add validation, but when i run only validation page it works fine but when i rut it with this page it gives me error.
I think i am doing mistake where i am adding an imagebutton by which i call the validation page which name is propertysearch.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
Well the stacktrace says there's a NullPointerException at line 32 in your ViewPagerStyle1Activity. Look what call is at that line and you should know the culprit.
You are trying to find imageButton1 in your layout main, but it is actually located in your layout layout_one. The fix now depends on what you are actually plan to do with your fragment. You could just set the fragment layout as the layout for your ViewPagerStyle1Activity by replacing setContentView(R.layout.main); with setContentView(R.layout.layout_one); in its' onCreate method.
Update: maybe you should read a bit first about Android Activities, Layouts and Fragments. This is very basic stuff and you won't get far without learning it in and out.
Of course you can't find the imageButton1, if you hard-code findViewById to return null in your fragment.
private ImageButton findViewById(int imagebutton1) {
// TODO Auto-generated method stub
return null;
}
But I get the sense you really don't know what you are actually trying to do.

getLoaderManager().initLoader() doesn't accept 'this' as argument though the class (ListFragment) implements LoaderManager.LoaderCallbacks<Cursor>

I'm having trouble following a guide on using SQLite in Android. I'm using a ListFragment instead of a ListActivity(as in the example), so I have the ListFragment implement LoaderManager.LoaderCallbacks<Cursor> instead. Then, in the fillData() method in the ListFragment:
private void fillData() {
// Fields from the database (projection)
// Must include the _id column for the adapter to work
String[] from = new String[] { NotesSQLiteHelper.COLUMN_TITLE };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
getLoaderManager().initLoader(0, null, this); //error
adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.notes_row, null, from, to, 0);
setListAdapter(adapter);
}
I get the error:
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks<D>) in the type LoaderManager is not applicable for the arguments (int, null, NotesActivity.ArrayListFragment)
on the marked line even though this implements LoaderManager.LoaderCallbacks<Cursor>.
Thank you for any ideas.
You are not using the right implementations of CursorLoader and Loader.
Remove your old imports and use these ones:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
But I have the same Problem using SherlockActionBar:
As I have to extend SherlockListActivity there is NO method getSupportLoadManager().
Any ideas on this?
EDIT: follow this tutorial if you do not know how to use fragments. Create a new Class with extends SherlockFragment and move your display logic there. Make your old activity extend SherlockFragmentActivity and show the newly created SherlockFragment. This way I got it working. Thanks to #JakeWharton!
A few things to watch out for (from my recent experience battling with this):
If your minSDK is set to less than 11 (i.e. level 10 for Gingerbread) and you are using the Support Pack for backward compatibility, make sure you use
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
You mentioned this when you said you are using ListFragment, but it bears repeating: Do not extend Activity, otherwise the support package will not work. Instead, extend the FragmentActivity class or the ListFragment class.
For your imports, make sure you are using the correct versions if your minSDK < 11:
android.support.v4.app.FragmentActivity;
android.support.v4.app.LoaderManager;
android.support.v4.content.Loader;
Hope this helps you... or at least someone else...
Casting the third argument solved the problem in my case:
from
getLoaderManager().initLoader(0, null, this);
to
getLoaderManager().initLoader(0, null, (android.app.LoaderManager.LoaderCallbacks<Cursor>) this);
Note:
minSdk was 8 and i was using support library v4.
(android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>) this)
did not work.
getSupportLoaderManager() or getSupportLoadManager()
did not work.
This code was inside activity not fragment
It's late but maybe help some one.
if you use loader maneger in fragment and you min api is below HONEYCOMB
you shuld use this imports
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.app.Fragment;
and for initiate loader use this code
getActivity().getSupportLoaderManager().initLoader(/loader stuff*/);
hope this help some one.
Change your imports to
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
and use
getSupportLoaderManager().initLoader(0, null, this);
This is what you have:
getLoaderManager().initLoader(0, null, this);
This is what you should have:
LoaderManager.getInstance(this).initLoader(0, null, this);
Reason for the first one not working:
/**
* #deprecated Use
* {#link LoaderManager#getInstance(LifecycleOwner) LoaderManager.getInstance(this)}.
*/
My error was beacause this:
//import android.app.ListFragment; Error when doesnt import from support.v4
import android.support.v4.app.ListFragment;
In my case I had to have my Activity extend ActionBarActivity from the android.support.v7.app package. I was then able to use
getSupportLoaderManager().initLoader(0, null, this);
I'm using ActionBarSherlock with my app and I as well was running into this issue and worked through all the steps discussed by others in this question. However I was continuing to have the same problem after trying all the suggested resolutions.
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks<D>) in the type LoaderManager is not applicable for the arguments (int, null, this)
The issue was I had fallen into expecting Eclipse to tell me when I was missing something and it was telling me that but not in the way I was used to. Typically Eclipse in other cases would tell me I'm missing the overrides to make something work but it's not directly saying that here. I finally picked up on the "LoaderManager.LoaderCallbacks" being the issue and realized I had no callbacks for it thus this error was actually a very valid error. Adding the basic overrides resolved my issue and allowed me to move forward.
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// do work
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// data is not available anymore, delete reference
adapter.swapCursor(null);
}
I was having a similar issue where my AsyncTaskLoader was not returning my List, but my resolution was to change the call from .initLoader to .restartLoader.
So I actually never called .initLoader and just immediately called .restartLoader.
I had a onListItemClick listener in my fragment and every time backed out of the fragment and reloaded the onListItemClick and navigated through the app it kept crashing.
It might just be specific to my app but hopefully it helps others if they are having fragment backstack reload issues.
This was part of a file manager portion in my app so it is specific to clicking multiple onListItemClicks in the fragment you are loading.
I got around this by using a SherlockListFragment (or you could use ListFragment, I suppose), but have it contained within a Activity. I first created a generic FragmentHolderActivity class that looks like this:
FragmentHolderActivity.java
public class FragmentHolderActivity extends SherlockFragmentActivity {
public static final String FRAGMENT_LAYOUT_RESOURCE_ID = "fragment_layout_resource_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Integer fragmentLayoutResourceId = getIntent().getIntExtra(FRAGMENT_LAYOUT_RESOURCE_ID, Integer.MAX_VALUE);
Assert.assertNotSame(fragmentLayoutResourceId, Integer.MAX_VALUE);
setContentView(fragmentLayoutResourceId);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return false;
default:
return super.onOptionsItemSelected(item);
}
}
}
Then you need to create an XML file for your fragment.
your_list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.example.YourListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment" />
And here's the code you use to start the fragment:
Intent intent = new Intent();
intent.setClass(this, FragmentHolderActivity.class);
intent.putExtra(FragmentHolderActivity.FRAGMENT_LAYOUT_RESOURCE_ID, R.layout.your_list_fragment);
startActivity(intent);
You just tell the FragmentHolderActivity to use the your_list_fragment layout, which in turn loads the YourListFragment.java
You can then use: getSherlockActivity().getSupportLoaderManager().initLoader(...) in YourListFragment.java
Not sure if this is the correct approach, but it keeps all my logic in Fragments, which is nice.
Ran into the same problem. My minSdkVersion is 14, so cannot use android.support.v4 package.
I figured it by extending LoaderCallbacks, instead of LoaderManager.LoaderCallbacks and use these packages
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
If you have tried all the above methods and still facing the same error with the "this" parameter, then follow these steps :
Go to settings and enable imports on the fly option.(by default it'll
be enabled and you can do this by using Alt+Enter keys).
Cut the whole code of the activity which had implemented
LoaderCallback... and paste it in a text editor.
Then at last copy the whole code of that activity from the text editor
where you had pasted, without any import commands.( Only the code of
the class/activity).
You'll get lots of errors as you have imported nothing yet.
Just press Alt+Enter wherever you're getting the errors and it's
libraries will be imported automatically.
Note : Choose android.app... library for CursorLoaders.
Try these 2 lines it will work
android.support.v4.app.LoaderManager loaderManager = getSupportLoaderManager();
loaderManager.initLoader(LOADER_ID, null, this);
I am using minSDK 27 and had this same issue, I tried to cast like #Dexter suggest, but that gave an error saying cannot be cast to android.app.LoaderManager$LoaderCallbacks, so I then tried to use different import statements and this worked. I commented out the v4 versions and this is what I have now and the app is working:
//import android.support.v4.app.LoaderManager;
import android.app.LoaderManager;
import android.support.v4.app.NavUtils;
//import android.support.v4.content.CursorLoader;
import android.content.CursorLoader;
//import android.support.v4.content.Loader;
//import android.content.Loader;
Not quite sure when/how the v4 versions were imported.
0
After a long sacrifice i got this solution if you are using fragments then just use this code.
getActivity().getSupportLoaderManager().initLoader(1, null, YourActivity.this);
i hope this is helpful for you
I was trying to call initLoader() inside an activity. For me this worked
changing
getSupportLoaderManager().initLoader(LOADER_ID,null,this);
to
getLoaderManager().initLoader(LOADER_ID,null,this);
If you use API 28 or later, instead of getLoaderManager use:
getSupportLoaderManager().initLoader(id, null, this);
If you use API 29, instead of getLoaderManager use:
getSupportLoaderManager().initLoader(id, null, this);

Categories

Resources