I am facing a strange issue in my android app and I am not able to figure it out. Is there anyone who can help me regarding this issue.
Let me describe about my app and issue.
I am getting all the images from gallery and displaying them on a gridview using adapter. Once displayed, I am sending an image from this gridview of Activity A to next activity on click of gridview item and assigning this image on an image view in Activity B... When I come back from Activity B to Activity A on pressing Bsck button, it works fine. But when I repeat this process three to four times, app is crashing. I don't know what is the issue. I am sure that the issue is in Activity A..
Here is the code of Activity A....
package info.androidhive.tabsswipe;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class ImageLoader extends Fragment implements LoaderCallbacks<Cursor> {
GridView gridView;
SimpleCursorAdapter mAdapter;
Cursor cursor;
Uri uri;
String ID;
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.videos, container, false);
gridView = (GridView) getActivity().findViewById(R.id.gridView1);
gridView.setAdapter(null);
mAdapter = null;
cursor = null;
uri = null;
ID = null;
intent = null;
mAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.gridview_item1,
null,
new String[] { "_data","_id"} ,
new int[] { R.id.video_thumbnail_imageview},
0
);
/** Setting adapter for the gridview */
gridView.setAdapter(mAdapter);
/** Loader to get images from the SD Card */
getActivity().getSupportLoaderManager().initLoader(0, null, this);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
cursor = (Cursor)parent.getItemAtPosition(position);
ID = cursor.getString(cursor.getColumnIndex("image_id"));
intent = new Intent(getActivity(),Testing_Activity.class);
intent.putExtra("Image_Path",ID);
startActivity(intent);
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
/** Getting uri to the Thumbnail images stored in the external storage */
uri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
/** Invoking the uri */
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
/** A callback method, invoked after the requested content provider returned all the data */
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
mAdapter.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
}
Any help regarding this issue will be highly appreciated. Thanks in Advance.
Related
This question already has answers here:
I'm having problems with running the code on my device [duplicate]
(3 answers)
Closed 4 years ago.
I am currently getting these errors when running my code on a device
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 9401
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:46)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
now based on what I see here are the libraries for the code its stating in the error. Please help im a beginner
Events.java
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.FragmentManager;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events,
container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View
view, int position, long id) {
Intent intent = new Intent(view.getContext(),
AddEvent.class);
Uri currentVehicleUri =
ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton)
getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),
AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity
context
EventContract.EventEntry.CONTENT_URI, // Provider
content URI to query
projection, // Columns to include in the
resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
Fragment Java(it says im getting an error around here:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
if (mHost != null) {
writer.print(prefix); writer.print("mHost=");
writer.println(mHost);
}
if (mParentFragment != null) {
writer.print(prefix); writer.print("mParentFragment=");
writer.println(mParentFragment);
In conclusion I'm trying to run the app but everytime I go into a certain section, in this case being Events.java being nav_events.xml layout, I keep getting the error and don't know how to fix it
Your error is found on line 46 of your Events.java file.
You're inflating a view and declaring it a ListView in Java (on line 46) when it seems to be a LinearLayout in your XML file.
Also right after that you're using getView(). You can only use that function correctly after onCreateView() has returned a View, definitely not within it.
EDIT after comment:
You haven't returned the View yet as you can't execute any code after a return statement.
Now without your layout file I can only speculate but probably replace
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
with
View rootView = (LinearLayout) inflater.inflate(R.layout.nav_events, container, false);
Then replace all occurrences of getView() in that code block with rootView.
And at the very end
return rootView;
I am unable to pass an intent in this case. Nothing is displayed on the screen or Logs from the movie_detail.java. I cannot figure out hat is wrong, please help!
MainActivityFragment.java
package com.example.coderahul.a9to12;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.Arrays;
public class MainActivityFragment extends Fragment {
private movieListAdapter movieListA;
MovieList[] movieLists = {
new MovieList("Cupcake - 1.5", "/is6QqgiPQlI3Wmk0bovqUFKM56B.jpg", "368596"),
new MovieList("Donut - 1.6", "/cGOPbv9wA5gEejkUN892JrveARt.jpg", "209112"),
new MovieList("Eclair - 2.0-2.1", "/9KQX22BeFzuNM66pBA6JbiaJ7Mi.jpg", "47933"),
new MovieList("Froyo - 2.2-2.2.3", "/z09QAf8WbZncbitewNk6lKYMZsh.jpg", "127380"),
new MovieList("GingerBread - 2.3-2.3.7", "/5N20rQURev5CNDcMjHVUZhpoCNC.jpg", "271110"),
new MovieList("Honeycomb - 3.0-3.2.6", "/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg", "135397"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg", "258489"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/tSFBh9Ayn5uiwbUK9HvD2lrRgaQ.jpg", "262504"),
new MovieList("Honeycomb - 3.0-3.2.6", "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", "87101"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/zSouWWrySXshPCT4t3UKCQGayyo.jpg", "293660"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/MZFPacfKzgisnPoJIPEFZUXBBT.jpg", "76341"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", "246655")
};
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieListA = new movieListAdapter(getActivity(), Arrays.asList(movieLists));
// Get a reference to the ListView, and attach this adapter to it.
GridView gridView = (GridView) rootView.findViewById(R.id.movies_grid);
gridView.setAdapter(movieListA);
final Context context = getActivity();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
MovieList detail = (MovieList) movieListA.getItem(position);
Intent intent = new Intent(context, movie_detail.class)
.putExtra(Intent.EXTRA_TEXT, detail.title);
context.startActivity(intent);
Log.v("Check", detail.title);
}
});
return rootView;
}
}
movie_detail.java
package com.example.coderahul.a9to12;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class movie_detail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail, container, false);
Log.v("Check", "Inside Intent");
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(detail);
}
return rootView;
}
}
}
movieListAdapter.java
package com.example.coderahul.a9to12;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class movieListAdapter extends ArrayAdapter<MovieList> {
private static final String LOG_TAG = movieListAdapter.class.getSimpleName();
/**
* This is our own custom constructor (it doesn't mirror a superclass constructor).
* The context is used to inflate the layout file, and the List is the data we want
* to populate into the lists
*
* #param context The current context. Used to inflate the layout file.
A List of AndroidFlavor objects to display in a list
*/
public movieListAdapter(Activity context, List<MovieList> movieList) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, movieList);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The AdapterView position that is requesting a view
* #param convertView The recycled view to populate.
* (search online for "android view recycling" to learn more)
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Gets the AndroidFlavor object from the ArrayAdapter at the appropriate position
MovieList movieList = getItem(position);
// Adapters recycle views to AdapterViews.
// If this is a new View object we're getting, then inflate the layout.
// If not, this view already has the layout inflated from a previous call to getView,
// and we modify the View widgets as usual.
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_item, parent, false);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext())
.load("http://image.tmdb.org/t/p/w185//" + movieList.link)
.resize(200, 200)
.centerCrop()
.into(iconView);
TextView versionNameView = (TextView) convertView.findViewById(R.id.movie_title);
versionNameView.setText(movieList.title);
return convertView;
}
}
You will be able to get your Intent in Activity's onCreate() method not in your fragment onCreateView() method because intent will be recevied by activity and not by fragment.
To get your intent in your movie_detail activity do it like this
static String detail="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent =getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
detail = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}
After doing this you can use detail String to set Text in your textview
In your fragment class
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(movie_detail.detail);
You must attach the fragment to your activity's layout in order to make you fragment visible in your activity
in your movie_detail activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
}
Bundle extra = new Bundle();
extra.putExtra(Intent.EXTRA_TEXT,detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
DetailFragment fragment = new DetailFragment();
fragment.setArguments(extra);
fragmentTransaction.replace(android.R.id.content, fragment);
}
And in your fragment get the arguments and set the details wherever necessary
I'm currently learning to work with fragments, so far I have been pretty successful, but have come up with the following error:
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: FATAL EXCEPTION: main
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: Process: com.example.wq.myapp, PID: 21831
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
10-14 15:24:55.309 21831-21831/? E/AndroidRuntime: at com.example.wq.myapp.PhoneMessages.onActivityCreated(PhoneMessages.java:44)
If anyone can explain what I'm doing wrong that would be greatly appreciated :)
Here is my fragment code:
package com.example.wq.myapp;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class PhoneMessages extends Fragment {
ListView lvMsgList;
// Cursor Adapter
SimpleCursorAdapter adapter1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone_messages, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://mms-sms/conversations");
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor a = getActivity().getContentResolver().query(inboxURI, new String[]{"*"}, null, null, "normalized_date desc");
// Attach Cursor with adapter and display in listView
adapter1 = new SimpleCursorAdapter(getActivity().getApplicationContext(), R.layout.row, a,
new String[]{"body", "date", "address", "thread_id"},
new int[]{R.id.lblMsg, R.id.lblDate, R.id.lblNumber, R.id.lblID}, 0);
lvMsgList.setAdapter(adapter1);
//set OnItemClickListener for listView, start ConvListActivity
lvMsgList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TVConvID = (TextView) view.findViewById(R.id.lblID);
String ConvID = TVConvID.getText().toString();
Intent i = new Intent(getActivity(), ConvListActivity.class);
i.putExtra("CID", ConvID);
startActivity(i);
}
});
getActivity().setTitle("Phone Messages");
}
}
You never inflated your listview so you are getting a null pointer. Also its better to do this in onCreateView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_phone_messages, container, false);
lvMsgList = (ListView) rootView.findViewById(R.id./*listview*/);
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://mms-sms/conversations");
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor a = getActivity().getContentResolver().query(inboxURI, new String[]{"*"}, null, null, "normalized_date desc");
// Attach Cursor with adapter and display in listView
adapter1 = new SimpleCursorAdapter(getActivity().getApplicationContext(), R.layout.row, a,
new String[]{"body", "date", "address", "thread_id"},
new int[]{R.id.lblMsg, R.id.lblDate, R.id.lblNumber, R.id.lblID}, 0);
lvMsgList.setAdapter(adapter1);
//set OnItemClickListener for listView, start ConvListActivity
lvMsgList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TVConvID = (TextView) view.findViewById(R.id.lblID);
String ConvID = TVConvID.getText().toString();
Intent i = new Intent(getActivity(), ConvListActivity.class);
i.putExtra("CID", ConvID);
startActivity(i);
}
});
getActivity().setTitle("Phone Messages");
return rootView;
}
I have been fighting with this error for a couple of hours and I am not able to continue. I need your help here!
I am trying to replace my previous TabNavigation at ActionBar by a ViewPager in SDK21, looking at comments within StackOverflow I found this webpage, where the use of PagerTabStrip is described with an example, so I tried to implement it in my activity, however I am getting an strange error.
I tried to google the problem and all the suggestions are not really applicable to my problem (wrong parameters in the constructor are the usual errors) . I also reproduced the error with a simple Activity in order to avoid anything I have in my previous activity, but the error keeps. I attach you here the code I replicated isolated:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestActivity extends Activity {
CustomPagerAdapter mCustomPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adding_users_to_list);
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), this.getApplicationContext());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomPagerAdapter);
}
class CustomPagerAdapter extends FragmentPagerAdapter {
Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// Create fragment object
Fragment fragment = new DemoFragment();
// Attach some data to the fragment
// that we'll use to populate our fragment layouts
Bundle args = new Bundle();
args.putInt("page_position", position + 1);
// Set the arguments on the fragment
// that will be fetched in the
// DemoFragment#onCreateView
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + (position + 1);
}
}
class DemoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout resource that'll be returned
View rootView = inflater.inflate(R.layout.fragment_users, container, false);
// Get the arguments that was supplied when
// the fragment was instantiated in the
// CustomPagerAdapter
Bundle args = getArguments();
((TextView) rootView.findViewById(R.id.text_option)).setText("Page " + args.getInt("page_position"));
return rootView;
}
}
}
I am getting in the call to the constructor the following error:
"The constructor TestActivity.CustomePageAdapter(FragmentManager, Context) is undefined"
In here:
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), this.getApplicationContext());
I have tried to introduce the Adapter outside and inside the activity definition and is still not working. Is likely to be something simple, but... I can't see it and I need other eyes. Any idea what I am doing wrong?
change the import of the activity to:
import android.support.v4.app.FragmentActivity;
Also change constructor to:
mCustomPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), this.getApplicationContext());
The reason is that your activity is used from the ADT:
import android.app.Activity;
and the Fragments used from the support package:
import android.support.v4.app.FragmentManager;
change the import of the activity to:
import android.support.v4.app.FragmentActivity;
This is my first time creating android app. and what i want to create now is to make a list and when a user click a name in the list the detail of the click name will show. I am trying to create simple cursor adapter. But an error occur
The constructor SimpleCursorAdapter(QuestionsNew, int, Cursor, String[], int[]) is undefined.
What do you think is the possible reason for this. Below is some part of my code
package tk.wew.wew;
import info.androidhive.sqlite.model.LocalStorage;
import info.androidhive.sqlite.model.Message;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import static tk.askd.askd.CommonUtilities.*;
public class QuestionsNew extends Fragment {
Cursor cursor;
ListView nameList;
protected ListAdapter adapter;
// TextView tvCompany = (TextView)
// findViewById(R.id.tvContactListCompany);
private static final String TAG = "Question";
private ListView list;
private static List questions;
ArrayList<String> senders = new ArrayList<String>();
ArrayList<String> shortMsg = new ArrayList<String>();
ArrayList<Integer> imageId = new ArrayList<Integer>();
SimpleCursorAdapter myCursorAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
//CommonUtilities.sendAQuestion(getActivity(), "msg123Kjjj11", "richmund_10023", "lofrancs1231", "Apil ka?");
questions = CommonUtilities.getAllQuestions(getActivity(), "N", null);
if(questions.size() > 0){
view = inflater.inflate(R.layout.questions_main_layout, container, false);
AskdDatabaseHelper msg_db = new AskdDatabaseHelper(getActivity());
List<Message> messages = msg_db.getAllQuestions("N", "lofrancs1231");
Cursor cursor = msg_db.getAllQuestions3();
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { "KEY_MSG_MESSAGE_ID","KEY_MSG_MESSAGE" };
int[] toViewIDs = new int[] { R.id.KEY_MSG_MESSAGE_ID, R.id.KEY_MSG_MESSAGE_ID };
/* SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.message_list_item, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);*/
myCursorAdapter = new SimpleCursorAdapter(QuestionsNew.this,
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
ListView contactList = (ListView) getView().findViewById(R.id.lvContacts);
contactList.setAdapter(myCursorAdapter);
for(int m=0; m<questions.size(); m++){
senders.add(messages.get(m).getFromUser());
shortMsg.add(messages.get(m).getMessage());
imageId.add(R.drawable.ic_launcher);
}
} else {
view = inflater.inflate(R.layout.fragments_question_new, container, false);
((TextView)view.findViewById(R.id.textView)).setText("No New Questions");
}
return view;
}
#Override
public void onStart(){
super.onStart();
Log.v(TAG, ": New onStart");
if(questions.size() > 0){
list = (ListView) getView().findViewById(R.id.list);
CustomLst adapter = new CustomLst(getActivity(), senders, imageId, shortMsg);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// Cursor listCursor = (Cursor) parent.getItemAtPosition(position);
// Cursor listCursor = (Cursor) parent.getAdapter().getItem(position);
// Log.d("TAG", (String) parent.getItemAtPosition(id));
Toast.makeText(getActivity(),
"Position:"+ parent.getItemIdAtPosition((int) id), Toast.LENGTH_LONG)
.show();
// int message = listCursor.getInt(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID));
/*
Intent intent = new Intent(getActivity(), QuestionDetail.class);
intent.putExtra("Message_ID", listCursor.getString(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID)));
startActivity(intent);
// ListView clicked item index
int Position = position;
// ListView clicked item value
String itemValue = (String) list.getItemAtPosition(Position);
// show alert
// Toast.makeText(getActivity(),
// "Position:" + Position + " Listitem:" + itemValue, Toast.LENGTH_LONG)
// .show();
*/
}
});
} else {
Log.e(TAG, "No new question");
}
}
}
Change your constructor as below
myCursorAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
The first param is a Context. This QuestionsNew.this is not a valid context. Fragment does not extend Context.
Activity
java.lang.Object
↳ android.content.Context // check this
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity // check this
Fragment
java.lang.Object
↳ android.app.Fragment // check this
So get context in fragment use getActivity()
public final Activity getActivity ()
Added in API level 11 Return the Activity this fragment is currently
associated with.
Also
SimpleCursorAdapter(Context context, int layout, Cursor c, String[]
from, int[] to) This constructor was deprecated in API level 11. This
option is discouraged, as it results in Cursor queries being performed
on the application's UI thread and thus can cause poor responsiveness
or even Application Not Responding errors. As an alternative, use
LoaderManager with a CursorLoader.
It is same when you use ArrayAdapter in Fragment class. The first param to the constructor of ArrayAdapter is a valid context. So even in that case you need to use getActivity() instead of FragmentName.this.