lazylist adapter issue while scrolling - java

public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View vi= convertView;
if(convertView==null){
viewHolder = new ViewHolder();
vi = inflater.inflate(R.layout.list_row, null);
viewHolder.content = (TextView)vi.findViewById(R.id.f_content);
viewHolder.cat_id = (TextView)vi.findViewById(R.id.c_id);
viewHolder.fact_id = (TextView)vi.findViewById(R.id.f_id);
vi.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> fact = new HashMap<String, String>();
fact = data.get(position);
// Setting all values in listview
viewHolder.fact_id.setText(fact.get("_id"));
viewHolder.cat_id.setText(fact.get("cat_id"));
viewHolder.content.setText(fact.get("fact_content"));
return vi;
}
I have created a LazyAdapter that extends a BaseAdaper to use with ListView.
The this adapter populates data in ListView. When I click on first 4 visible list items it prints the value of that item.
Problem is when I scroll down the list view and click on item 5. The app crashes saying null pointer exception. Log trace is here for reference.
05-13 23:10:43.943: E/AndroidRuntime(3360): FATAL EXCEPTION: main
05-13 23:10:43.943: E/AndroidRuntime(3360): java.lang.NullPointerException
05-13 23:10:43.943: E/AndroidRuntime(3360): at com.example.facts.MainActivity$3.onItemClick(MainActivity.java:100)
05-13 23:10:43.943: E/AndroidRuntime(3360): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
05-13 23:10:43.943: E/AndroidRuntime(3360): at android.widget.ListView.performItemClick(ListView.java:3569)
05-13 23:10:43.943: E/AndroidRuntime(3360): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1831)
05-13 23:10:43.943: E/AndroidRuntime(3360): at android.os.Handler.handleCallback(Handler.java:587)
05-13 23:10:43.943: E/AndroidRuntime(3360): at android.os.Handler.dispatchMessage(Handler.java:92)
05-13 23:10:43.943: E/AndroidRuntime(3360): at android.os.Looper.loop(Looper.java:150)
05-13 23:10:43.943: E/AndroidRuntime(3360): at android.app.ActivityThread.main(ActivityThread.java:4389)
05-13 23:10:43.943: E/AndroidRuntime(3360): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 23:10:43.943: E/AndroidRuntime(3360): at java.lang.reflect.Method.invoke(Method.java:507)
05-13 23:10:43.943: E/AndroidRuntime(3360): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
05-13 23:10:43.943: E/AndroidRuntime(3360): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
05-13 23:10:43.943: E/AndroidRuntime(3360): at dalvik.system.NativeStart.main(Native Method)
The Onclick Methods is like this:
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
RelativeLayout node = (RelativeLayout)parent.getChildAt(position);
TextView fact = (TextView) node.findViewById(R.id.c_id);
Log.d("ListItem Clicked", "id: " + id + " position: "
+ position + " artist " + fact.getText());
}
});

My suggestion would be to revisit your onItemClickListener implementation.
You should not need to access parent at all for what you are trying to do. Try this.
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView fact = (TextView) view.findViewById(R.id.c_id);
Log.d("ListItem Clicked", "id: " + id + " position: "
+ position + " artist " + fact.getText());
}
});
The view argument supplied in the method is actually the view being click on.
view; The view within the AdapterView that was clicked (this will be a view provided by the adapter)
Please refer to AdapterView.OnItemClickListener for more details.
The parent is there to help you identified which AdapterView that is being acted on. For example, say if you have two ListAdapter but only want to use one listener then it going to help you specify which is the one.

Related

android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams

There are other related issues on this but they do not address my situation (their error code has to do with some sort of recycling and/or bad cast calls by client code).
My situation is more complex.
I have some code where the user can pull up a library of photos.
The thing is, its working just fine on 7 phones that I have, all running API's 19+.
However I have a Google Nexus 4.3 that's running API 17. And I get this crash log which has none of my code, only library code. If you can advise how I might be able to code a work around I'd be all ears:
FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
at android.widget.GridView.onMeasure(GridView.java:1042)
at android.view.View.measure(View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
at android.view.View.measure(View.java:15848)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Update
My offending class is this:
//Special class that works with the UIL
//The holder gets re-used and gets the new properties from this
static class ReusableGridViewView extends FrameLayout
{
public ImageView imageView;
public ProgressBar progressBar;
public ReusableGridViewView(Context context)
{
super(context);
setLayoutParams(new LayoutParams((int)(0.325* ViewHelper.screenWidthPX(context)),(int)(0.325* ViewHelper.screenWidthPX(context))));
imageView = new ImageView(context);
progressBar = new ProgressBar(context);
addView(imageView);
addView(progressBar);
}
}
Im using the Ultimate Image Loader library and this is the code that uses the above class.
//I do NOT call this directly, the listview decides when re use a convert view and passes it accordingly
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
View view = convertView;
if (view == null)
{
view = new ReusableGridViewView(parent.getContext());
holder = new ViewHolder();
assert view != null;
holder.imageView = ((ReusableGridViewView)view).imageView;
holder.progressBar = ((ReusableGridViewView)view).progressBar;
holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
//System.out.println(" " + holder + " ||| " + holder.imageView);
ImageLoader.getInstance()
.displayImage(IMAGE_URLS[position], holder.imageView, options, new SimpleImageLoadingListener()
{
#Override
public void onLoadingStarted(String imageUri, View view)
{
holder.progressBar.setProgress(0);
holder.progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason)
{
holder.progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
holder.progressBar.setVisibility(View.GONE);
}
}, new ImageLoadingProgressListener()
{
#Override
public void onProgressUpdate(String imageUri, View view, int current, int total)
{
holder.progressBar.setProgress(Math.round(100.0f * current / total));
}
});
//set all as unselected
((ReusableGridViewView) view).removeSelectionBorder();
for(int i = 0; i < SELECTED_IMAGES.length; i++)
{
if(SELECTED_IMAGES[i] == position)
{
//set cell to selected
((ReusableGridViewView) view).addSelectionBorder();
}
}
return view;
}
So it turns out that on API < 17 FrameLayout can't be cast correctly to AbsListView params.
What I did was set AbsListView LayoutParams instead of FrameLayout params:
setLayoutParams(new AbsListView.LayoutParams(100,100));
I'm not sure if this is going to help you or what, but this crash used to happen for me once I was using AndroidSlidingUpPanel and adding a view inside of its content layout programmatically. After searching and trying many different solutions I came up with this solution; I added the following layout as the first child of the content layout and the crash was solved.
<android.widget.AbsListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_constraintTop_toTopOf="parent" />

java.lang.IndexOutOfBoundsException:Invalid index x, size is x

After 3 hours of try i decided to ask here and see if someone can provide me a solution for this error: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
here is my code
public class ParcelAdapter extends BaseAdapter{
private final Activity context;
ParcelPOJO.Data items=new ParcelPOJO.Data();
ParcelAdapter(Activity context, ParcelPOJO.Data items){
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.getLive().size();
}
#Override
public Object getItem(int position) {
return 0;
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
protected TextView eventCode;
protected TextView eventStatus;
protected TextView eventPrice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
if(convertView==null) {
convertView = inflater.inflate(R.layout.parcel_row, null);
}
final ViewHolder viewHolder = new ViewHolder();
viewHolder.eventCode = (TextView) convertView.findViewById(R.id.pPackage_code);
viewHolder.eventStatus = (TextView) convertView.findViewById(R.id.pPackedStatus);
viewHolder.eventPrice =(TextView)convertView.findViewById(R.id.pPrice);
convertView.setTag(viewHolder);
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.eventCode.setText(items.getLive().get(position).getCodeNumber());
holder.eventStatus.setText(items.getLive().get(position).getStatus());
holder.eventPrice.setText(items.getLive().get(position).getOrderStorageShowPrice());
holder.eventCode.setText(items.getProcessing().get(position).getCodeNumber());
holder.eventStatus.setText(items.getProcessing().get(position).getStatus());
holder.eventPrice.setText(items.getProcessing().get(position).getOrderStorageShowPrice());
holder.eventCode.setText(items.getPacked().get(position).getCodeNumber());
holder.eventStatus.setText(items.getPacked().get(position).getStatus());
holder.eventPrice.setText(items.getPacked().get(position).getOrderStorageShowPrice());
//line 119 holder.eventCode.setText(items.getSent().get(position).getCodeNumber());
holder.eventStatus.setText(items.getSent().get(position).getStatus());
holder.eventPrice.setText(items.getSent().get(position).getOrderStorageShowPrice());
holder.eventCode.setText(items.getReceived().get(position).getCodeNumber());
holder.eventStatus.setText(items.getReceived().get(position).getStatus());
holder.eventPrice.setText(items.getReceived().get(position).getOrderStorageShowPrice());
return convertView;
}
}
logcat
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at dedmd.dedmd.fragmentsparcel.Parcels$ParcelAdapter.getView(Parcels.java:119)
at android.widget.AbsListView.obtainView(AbsListView.java:2267)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1244)
at android.widget.ListView.onMeasure(ListView.java:1156)
at android.view.View.measure(View.java:15172)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
at android.view.View.measure(View.java:15172)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15172)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:762)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15172)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15172)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148)
at android.view.View.measure(View.java:15172)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1848)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1100)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1273)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:525)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
if i delete this line i get the same error but with Invalid index 1, size is 1
This method tells the adapter how many items there are:
#Override
public int getCount() {
return items.getLive().size();
}
so apparently the array items.getSent() is not as long as the array items.getLive() - so the Adapter tries to go to a position after the end of it and it is invalid.
EDIT:
In other words, your items object has several arrays. One of them is items.getLive() and another one is items.getSent()
If you construct the "items" object and those two arrays have different lengths, then you will have problems. So, you need to fix how the items object is constructed before you construct your Adapter
EDIT 2:
If you do not control the source of your data, then you need either:
You need to look at your object contract (API) or get the source to create one. Having an object with sets of variable length arrays may not be what the provider intends and you have found a bug.
If you don't have an API or it states that you should expect possible null values, then you should be prepared for them. Maybe like this:
if (items.getSent() != null && items.getSent(),get(poistion)) {
holder.eventCode.setText(items.getSent().get(position).getCodeNumber());
...
}

Unable to start activity ComponentInfo{..} : java.lang.NullPointerException via Crashlytics. Cannot reproduce

For ~20% of my user-base, they are getting a Unable to start activity ComponentInfo{..} : java.lang.NullPointerExceptionFATAL Exception. I monitor the exceptions remotely via Crashlytics, so I have the stacktrace. The only problem is, there is no line number.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.falk.fietsroutes.app/com.falk.fietsroutes.app.HomeActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2340)
at android.app.ActivityThread.access$800(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.NullPointerException
at com.falk.fietsroutes.app.SearchResultsFragment.onCreateView()
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1044)
at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1853)
at android.app.Activity.performCreate(Activity.java:5392)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2246)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2340)
at android.app.ActivityThread.access$800(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(NativeStart.java)
I've read many reports from people with the same error, which all came down to something in their code being null (ofcourse, because it's a nullpointer). But I can't track it down because I cannot reproduce it (I only have one device which seems to work fine), and the stack trace doesn't help.
At first sight I couldn't find anything that could be null in SearchResultsFragment.onCreateView() (because that is where the NPE gets thrown right?)
If any of you could point me in the right direction or know how I could get the line number where the exception, it would be appreciated!
Here is the code of SearchResultsFragment.onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Set orientation
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
// Get the rootview in the fragment
View rootView = inflater.inflate(R.layout.fragment_search_results, container, false);
// Get settings instance
mSettings = Settings.getInstance();
// Init the mRoutes arraylist
mRoutes = new ArrayList<Route>();
// Get the gridview and set the adapters (animation adapter and the gridview adapter)
GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
SearchResultCardsAdapter searchAdapter = new SearchResultCardsAdapter(getActivity(), inflater);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(searchAdapter);
swingBottomInAnimationAdapter.setAbsListView(gridView);
swingBottomInAnimationAdapter.setInitialDelayMillis(300);
mAdapter = swingBottomInAnimationAdapter;
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("Grid item click", "Clicked!");
Route route = mRoutes.get(i);
Intent routeDetailIntent = new Intent(getActivity(), RouteDetailActivity.class);
routeDetailIntent.putExtra("routeId", route.id);
// Analytics
Tracker t = ((AppDelegate) getActivity().getApplication()).getTracker(
AppDelegate.TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory("Routes")
.setAction("View")
.setLabel(Integer.toString(route.id))
.build());
startActivity(routeDetailIntent);
}
});
gridView.setAdapter(mAdapter);
// Set the infinite scroll listener
gridView.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to your AdapterView
loadMoreRoutes(page, totalItemsCount);
// or customLoadMoreDataFromApi(totalItemsCount);
}
});
// Show the progressbar
mProgressBar = (SmoothProgressBar)rootView.findViewById(R.id.search_results_progressbar);
mProgressBar.progressiveStart();
// Inflate the layout for this fragment
return rootView;
}
Maybe others will benefit from my mistake. The problem was that I used pro-guard and Android Studio to sign my Android App, and I had to keep-attributes some properties so Crashlytics could read the line number and class name.
-keepattributes SourceFile,LineNumberTable
Via

Why am I getting class cast exception? Android

I'm working on an android app that is supposed to load the gallery and grab an image and display it in an image view. I had it working but changed from Activities to Fragments to use the ViewPager and since then it has been crashing. I believe it is because I'm using a method intended for Activities on Fragments.
public class Fragment_1 extends Fragment {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Button buttonLoadImage = (Button) getView().findViewById(
R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.v("ButtonPress: ", "Pressed");
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Log.v("ButtonPress: ", "intent=" + i);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) getView().findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
The error I'm receiving is:
05-05 22:17:59.214: E/AndroidRuntime(32610): FATAL EXCEPTION: main
05-05 22:17:59.214: E/AndroidRuntime(32610): Process: com.example.hashtagged, PID: 32610
05-05 22:17:59.214: E/AndroidRuntime(32610): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hashtagged/com.example.hashtagged.Fragment_1}: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2131)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.access$800(ActivityThread.java:145)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.os.Handler.dispatchMessage(Handler.java:102)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.os.Looper.loop(Looper.java:136)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.main(ActivityThread.java:5142)
05-05 22:17:59.214: E/AndroidRuntime(32610): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610): at java.lang.reflect.Method.invoke(Method.java:515)
05-05 22:17:59.214: E/AndroidRuntime(32610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-05 22:17:59.214: E/AndroidRuntime(32610): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
05-05 22:17:59.214: E/AndroidRuntime(32610): at dalvik.system.NativeStart.main(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610): Caused by: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2122)
05-05 22:17:59.214: E/AndroidRuntime(32610): ... 11 more
Try inflate the View first on OnCreateView, like this:
private Button mButtonLoadImage;
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
mButtonLoadImage = (Button) view.findViewById(R.id.buttonLoadPicture);
return view;
}
And set onClickListener inside onViewCreated:
#Override public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mButtonLoadImage.setOnClickListener(onClickLoad);
}
//Good practice
private View.OnClickListener onClickLoad = new View.OnClickListener() {
#Override public void onClick(View view) {
//TODO action here
}
};
You are using onActivityResult() method of the activity class in your Fragment class. That is why you are getting this error. onActivityResult should be defined in your activity class of the your fragment class not on the fragment itself. See this link for how to do it.here

get selected object from listview

I will find a way to get a selected item in my list view and then to cast in my object type, but i get an error i think is to big to see whats is wrong. Can you help me ?
My code :
mListMenu = (ListView) findViewById(R.id.listView_tracks);
mListMenu.setAdapter(new TracksListAdapter(this, TrackManager.getAllTrackFromTel(new DataBaseHelper(this))));
mListMenu.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long arg3) {
Track selectedItem = (Track) adapter.getAdapter().getItem(position);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putLong("trackselected",selectedItem.getTrackid());
intent.putExtras(bundle);
//Envoi du resultat à l'origine
setResult(RESULT_OK, intent);
finish();
}
});
I get this error :
FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.Integer
at com.milesbox.sport.tracker.ListTracksActivity$1.onItemClick(ListTracksActivity.java:44)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3746)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:1980)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3691)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
at dalvik.system.NativeStart.main(Native Method)
Thank you FD_, when i say it was too big to see what is wrong, this is my method(getItem) that return an item that was wrong (copy paste too quick).

Categories