AppCompatActivity OutOfMemoryError - java

I wanna add toolbar to my android app, however I got "FATAL EXCEPTION: main
java.lang.OutOfMemoryError" when I changed Activity to AppCompatActivity. Here is my code, I don't know why changing a line makes an out of memory error.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class Notifications extends AppCompatActivity {
//public class Notifications extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
//Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
//setSupportActionBar(myToolbar);
//String[] notificationsDates = {"12Jan 2016", "14Feb 2016", "22Feb 2016", "18Dec 2015", "2Nov 2015", "20Oct 2015", "15Oct 2015"};
//String[] estimationTimes = {"9:00 am", "10:00 am", "11:00 am", "9:00 am", "10:00 am", "10:00 am", "11:00 am"};
final SingleNotification[] notifications = {
new SingleNotification("12Jan2016","9:00 am",R.drawable.fedex,false),
new SingleNotification("14Feb2016","10:00 am",R.drawable.ups,false),
new SingleNotification("22Feb2016","11:00 am",R.drawable.purolator,true),
new SingleNotification("18Dec2015","9:00 am",R.drawable.dhl,true),
new SingleNotification("2Nov2015","10:00 am",R.drawable.fedex,true),
new SingleNotification("20Oct2015","10:00 am",R.drawable.ups,true),
new SingleNotification("15Oct2015","11:00 am",R.drawable.ups,true)
};
ListAdapter listAdapter = new CustomeAdapter(this, notifications);
ListView notificationListView = (ListView) findViewById(R.id.notificationsList);
notificationListView.setAdapter(listAdapter);
notificationListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String date = String.valueOf(notifications[position].getDeliveryDate());
Toast.makeText(Notifications.this, date, Toast.LENGTH_LONG).show();
}
}
);
}
//String[] notificationsDate = {"Delivery Data: 17Feb2015"};
//String[] notificationsTime = {" Estimated Time: "};
}
here is CustomAdapter:
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.res.Resources;
import android.app.Activity;
public class CustomeAdapter extends ArrayAdapter<SingleNotification> {
CustomeAdapter(Context context, SingleNotification[] notifications) {
super(context, R.layout.custome_row, notifications);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View customView = layoutInflater.inflate(R.layout.custome_row, parent, false);
SingleNotification notification = getItem(position);
LinearLayout singleNotificationLayout = (LinearLayout) customView.findViewById(R.id.singleNotificationLayout);
TextView deliveryDateText = (TextView) customView.findViewById(R.id.delivaryDataText);
TextView notificationNumberText = (TextView) customView.findViewById(R.id.notificationNumberText);
TextView estimationTimeText = (TextView) customView.findViewById(R.id.estimationTimeText);
ImageView logoImage = (ImageView) customView.findViewById(R.id.logoImage);
deliveryDateText.setText(notification.getDeliveryDate());
notificationNumberText.setText(String.valueOf(position + 1));
estimationTimeText.setText(notification.getEstimationTime());
logoImage.setImageResource(notification.getImageID());
if (notification.getIsDelivered())
singleNotificationLayout.setBackgroundColor(Color.parseColor("#6d6d6d"));
else
singleNotificationLayout.setBackgroundColor(Color.parseColor("#FF40459A"));
return customView;
}
}
here is the log:
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:501)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:354)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
at android.content.res.Resources.loadDrawable(Resources.java:1970)
at android.content.res.Resources.getDrawable(Resources.java:660)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:175)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:168)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:51)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:72)
at android.widget.AbsListView.obtainView(AbsListView.java:2143)
at android.widget.ListView.makeAndAddView(ListView.java:1831)
at android.widget.ListView.fillDown(ListView.java:674)
at android.widget.ListView.fillSpecific(ListView.java:1332)
at android.widget.ListView.layoutChildren(ListView.java:1630)
at android.widget.AbsListView.onLayout(AbsListView.java:1994)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1021)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1037)
at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:747)
at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1156)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:760)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14008)
at android.view.ViewGroup.layout(ViewGroup.java:4373)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1892)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1711)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
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:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)

So the problem as you can see is in your adapter (at com...timesavvi.CustomeAdapter.getView(CustomeAdapter.java:36)).
The culprit would seem to be logoImage.setImageResource(notification.getImageID()); (which I assume is ln 36)
What this will mean is the image to which getImageID points is a very large file which is not suitable for the device. You should use scaled images for the various densities and not use particularly large dimensions in order to avoid this issue.
Bear in mind as well that in an adpater any code you write can be called dozens of times, depending on how many rows you have in your recycler/list view and that if you are decoding from a network resource, it may continue to do that in the background for rows which arent even on the screen any more, so you need to manage such calls if you use them

Related

Android resources - failure getting entry

I rewrote my app to a new project to have the code tidier and also use pre-defined fullscreen activity from Android Studio. The app was working perfectly fine (at least past the point when it crashes now). The app populates a gridview from an SQLite database via custom CursorAdaper, and the error seems to be there, more specifically - it looks like a problem with the layout that should be populated (A linear view of fixed dimensions, 2 children - ImageView and TextView.
Ichecked the resource from the first line in R.java and this value is assigned to the name of the layout that should be inflated by the cursor. Any idea how to fix it?
W/ResourceType: Failure getting entry for 0x7f040031 (t=3 e=49) (error -75)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.madry.mtg, PID: 21183
android.content.res.Resources$NotFoundException: Resource ID #0x7f040031
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:198)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2114)
at android.content.res.Resources.getLayout(Resources.java:1115)
at android.view.LayoutInflater.inflate(LayoutInflater.java:424)
at com.madry.mtg.MyCursorAdapter.newView(MyCursorAdapter.java:33)
at android.widget.CursorAdapter.getView(CursorAdapter.java:285)
at android.widget.AbsListView.obtainView(AbsListView.java:2433)
at android.widget.GridView.onMeasure(GridView.java:1065)
at android.view.View.measure(View.java:19785)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1117)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
at android.view.View.measure(View.java:19785)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19785)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:19785)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
at android.view.View.measure(View.java:19785)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19785)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
at android.view.View.measure(View.java:19785)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:690)
at android.view.View.measure(View.java:19785)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1362)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1611)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1250)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6311)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6217)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
The MyCursorAdapter class
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import static com.madry.mtg.MyDBHandler.COLUMN_COLOUR;
import static com.madry.mtg.MyDBHandler.COLUMN_POWER;
import static com.madry.mtg.MyDBHandler.COLUMN_TAP;
import static com.madry.mtg.MyDBHandler.COLUMN_TS;
public class MyCursorAdapter extends CursorAdapter{
private LayoutInflater cursorInflater;
public MyCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return cursorInflater.inflate(R.layout.token, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
Log.d("adapter", "zaczelo wiazac");
Symbol symbol = new Symbol();
String sciezka = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_COLOUR));
symbol.setPath(sciezka);
int path = symbol.getPath();
ImageView clr = (ImageView) view.findViewById(R.id.imageView);
clr.setImageResource(path);
int tap = cursor.getInt((cursor.getColumnIndexOrThrow(COLUMN_TAP)));
if (tap == 0){
view.setRotation(0);
} else {
view.setRotation(20);
}
TextView stats = (TextView) view.findViewById(R.id.textView2);
String p = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_POWER))+
"/" + cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TS));
stats.setText(p);
}
}

Android display SD card files throws java.lang.NullPointerException

This is the MainActivity file. When I run it in the emulator and phone, logcat displays a crash due to a NullPointerException. I've read a lot about not letting the user or another activity pass "null" value to my method but could not get around this.
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I used a listview with id= "filelist" in layout
ListView lv;
ArrayList<String> FilesInFolder;
FilesInFolder = GetFiles(Environment.getExternalStorageDirectory().getPath()+ "/sdcard/");
lv = (ListView)findViewById(R.id.filelist);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
This is the logcat:
07-02 01:09:40.500 4407-4407/com.amenhotep.filelister W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
07-02 01:09:40.501 4407-4407/com.amenhotep.filelister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amenhotep.filelister, PID: 4407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amenhotep.filelister/com.amenhotep.filelister.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.amenhotep.filelister.MainActivity.GetFiles(MainActivity.java:44)
at com.amenhotep.filelister.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
the problem is in your sdcard path, use this code to get path of sdcard
String DIR_SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
and there is no need to add "/sdcard/" to it, also change your GetFiles method, and remove mkdirs() because sdcard exists before.
look at this example
File sdcard_files_and_folders[] = new File(DIR_SDCARD).listFiles();
for (File fileOrFolder: sdcard_files_and_folders) {
// do any thing that you want, add them to list or...
Log.i("FILE", fileOrFolder.toString());
}

NullPointerException when scrolling ListView with images loaded from JSON

I've an error, when using ListView in Android, which is populated with images. Images urls are from tumblr JSON and android query loads them. Error message which I get is:
12-12 21:55:38.032 4334-4334/com.example.tumblrviewer E/InputEventReceiver﹕ Exception dispatching input event.
12-12 21:55:38.040 4334-4334/com.example.tumblrviewer D/dalvikvm﹕ GC_FOR_ALLOC freed 760K, 12% free 9993K/11292K, paused 5ms, total 6ms
12-12 21:55:38.040 4334-4334/com.example.tumblrviewer E/MessageQueue-JNI﹕ java.lang.NullPointerException
at com.example.tumblrviewer.MenuArrayAdapter.getView(MenuArrayAdapter.java:76)
at android.widget.AbsListView.obtainView(AbsListView.java:2161)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillGap(ListView.java:639)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4970)
at android.widget.AbsListView.onGenericMotionEvent(AbsListView.java:3680)
at android.view.View.dispatchGenericMotionEventInternal(View.java:7479)
at android.view.View.dispatchGenericMotionEvent(View.java:7460)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchGenericMotionEvent(PhoneWindow.java:1974)
at com.android.internal.policy.impl.PhoneWindow.superDispatchGenericMotionEvent(PhoneWindow.java:1428)
at android.app.Activity.dispatchGenericMotionEvent(Activity.java:2460)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchGenericMotionEvent(PhoneWindow.java:1928)
at android.view.View.dispatchPointerEvent(View.java:7566)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:132)
at android.os.Looper.loop(Looper.java:124)
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)
12-12 21:55:38.044 4334-4334/com.example.tumblrviewer D/AndroidRuntime﹕ Shutting down VM
12-12 21:55:38.044 4334-4334/com.example.tumblrviewer W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4bd3648)
12-12 21:55:38.052 4334-4334/com.example.tumblrviewer E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.tumblrviewer.MenuArrayAdapter.getView(MenuArrayAdapter.java:76)
at android.widget.AbsListView.obtainView(AbsListView.java:2161)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillGap(ListView.java:639)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4970)
at android.widget.AbsListView.onGenericMotionEvent(AbsListView.java:3680)
at android.view.View.dispatchGenericMotionEventInternal(View.java:7479)
at android.view.View.dispatchGenericMotionEvent(View.java:7460)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:1819)
at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1772)
at android.view.View.dispatchGenericMotionEvent(View.java:7453)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchGenericMotionEvent(PhoneWindow.java:1974)
at com.android.internal.policy.impl.PhoneWindow.superDispatchGenericMotionEvent(PhoneWindow.java:1428)
at android.app.Activity.dispatchGenericMotionEvent(Activity.java:2460)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchGenericMotionEvent(PhoneWindow.java:1928)
at android.view.View.dispatchPointerEvent(View.java:7566)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3883)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3778)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5419)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5399)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5370)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5493)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:132)
at android.os.Looper.loop(Looper.java:124)
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)
it points to MenuArrayAdapter line 76, which contains:
mAQ.id(viewHolder.mImageView).image(item.photos[0].photoUrl.uri, false, false, 600, 0, null, Constants.FADE_IN);
and I'm pretty sure this object is not null, because error occurs random, each time with different item in ArrayAdapter. It happens when I scroll ListView fast, up and down. I see that images does not have a time to load. Can it be related with a problem with memory? that there is too much data in the memory and app crashes? If so, what would be a good solution, if I want to stay with infinite scroll - I don't want to add "load more" button in the bottom, as e.g. Instagram does not have such button and it can load lots of images.
full code of this class is as follows:
package com.example.tumblrviewer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.example.tumblrviewer.model.HomeResponse;
import com.example.tumblrviewer.model.Item;
import org.json.JSONException;
import org.json.JSONObject;
public class MenuArrayAdapter extends ArrayAdapter<Item> {
private final LayoutInflater mInflater;
private final int mResourceId;
private AQuery mAQ;
private int postOffset;
public MenuArrayAdapter(Context context, int resource) {
super(context, resource);
mInflater = LayoutInflater.from(context);
mResourceId = resource;
mAQ = new AQuery(context);
postOffset=0;
//loadImages(postOffset);
}
public void setPosts(Item[] posts) {
//clear();
for (Item item : posts) {
add(item);
}
if (isEmpty()) {
notifyDataSetInvalidated();
} else {
notifyDataSetChanged();
}
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(mResourceId, viewGroup, false);
viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.tumblr_photo_iv);
//viewHolder.mTagsLayout=(LinearLayout) convertView.findViewById(R.id.tags_layout);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Item item = getItem(i);
//if ( item.photos[0].photoUrl.uri != null) {
mAQ.id(viewHolder.mImageView).image(item.photos[0].photoUrl.uri, false, false, 600, 0, null, Constants.FADE_IN);
//}
return convertView;
}
private class ViewHolder {
ImageView mImageView;
//LinearLayout mTagsLayout;
}
}
There is also main activity
package com.example.tumblrviewer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.tumblrviewer.model.HomeResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class WeHaveTheMunchiesActivity extends Activity {
private AQuery mAQ;
private TextView mResultTextView;
private ListView mListView;
private MenuArrayAdapter mItemArrayAdapter;
private int postOffset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_viewer);
mListView = (ListView) findViewById(R.id.items_lv);
mAQ = new AQuery(this);
mItemArrayAdapter = new MenuArrayAdapter(this, R.layout.item_on_list);
mListView.setAdapter(mItemArrayAdapter);
postOffset=0;
loadImages(postOffset);
mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount ){
if(postOffset <= 10662
&& mListView.getChildAt(mListView.getChildCount() - 1) != null
&& mListView.getLastVisiblePosition() == mListView.getAdapter().getCount() - 1
&& mListView.getChildAt(mListView.getChildCount() - 1).getBottom() <= mListView.getHeight()) {
Toast.makeText(getApplicationContext(), "Bottom!", Toast.LENGTH_LONG).show();
loadImages(postOffset);
System.out.println("postOffset "+postOffset);
}
}
}
});
}
private void loadImages(int offset) {
String url = Constants.TUMBLR_API_BLOG_URL + Constants.TUMBLR_API_BLOG_HOSTNAME +
Constants.TUMBLR_API_CONTENT_TYPE + Constants.TUMBLR_API_KEY_NAME +
Constants.TUMBLR_API_KEY + "&offset=" + Integer.toString(offset);
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
cb.url(url).type(JSONObject.class).weakHandler(this, "itemsCallback");
mAQ.ajax(cb);
postOffset=postOffset+20;
}
public void itemsCallback(String url, JSONObject json, AjaxStatus status) throws JSONException {
//Toast.makeText(getApplicationContext(), status.getRedirect(), Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), status.getCode(), Toast.LENGTH_LONG).show();
//mResultTextView.setText(status.getMessage());
if (json != null) {
HomeResponse homeResponse = HomeResponse.fromJsonObject(json.getJSONObject("response"));
System.out.print(homeResponse.items);
mItemArrayAdapter.setPosts(homeResponse.items);
}
}
}

Android custom listview click - How to call an intent without crashing?

All right, so I've been a few hours on this, and can't get it to work.
Basically, I wanna call an intent from a clickable listview. I'm displaying car models and it's code on a list, when you click, you're supposed to be taken to another screen to edit the car's properties, however, I'm beggining to think it's impossible
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, arrayListCarros);
mainListView.setAdapter( listAdapter );
db.close();
mainListView.setClickable(true);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(listagemcarro.this,com.example.trabalhosql.edicao.class);
startActivity(i);
}
});
The rest of the code:
public class listagemcarro extends Activity {
Button buttonCadastro;
Button buttonListagem;
Button buttonBusca;
Button button1;
Intent itListagem = new Intent();
Intent itCadastro = new Intent();
Intent itBusca = new Intent();
//Intent itEdicao = new Intent();
Intent itEdicao2 = new Intent();
String id="";
public SQLiteDatabase db;
public String BANCO = "banco.db";
public String TABELA = "carro";
int posicao=123123;
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
public void toast(int position){
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, position, Toast.LENGTH_SHORT);
toast.show();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listagemcarro);
Intent itRecebeParametros = getIntent();
if(itRecebeParametros != null){
id = itRecebeParametros.getStringExtra("id");
}
db = openOrCreateDatabase(BANCO, Context.MODE_PRIVATE, null);
Cursor linhas = db.query(TABELA, new String[] {"ID_PESSOA, MODELO"},"id_pessoa = '"+id+"'", null, null, null, null);
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayList <String>arrayListCarros = new ArrayList<String> ();
if(linhas.moveToFirst()){
do{
arrayListCarros.add(linhas.getString(0) +" " + linhas.getString(1));
}
while(linhas.moveToNext());
}
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, arrayListCarros);
mainListView.setAdapter( listAdapter );
db.close();
mainListView.setClickable(true);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(listagemcarro.this,com.example.trabalhosql.edicao.class);
startActivity(i);
}
});
}
error
11-19 23:18:09.136: W/dalvikvm(1784): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
11-19 23:18:09.136: E/AndroidRuntime(1784): Uncaught handler: thread main exiting due to uncaught exception
11-19 23:18:09.147: E/AndroidRuntime(1784): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trabalhosql/com.example.trabalhosql.edicao}: java.lang.NullPointerException
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.os.Looper.loop(Looper.java:123)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.main(ActivityThread.java:4363)
11-19 23:18:09.147: E/AndroidRuntime(1784): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 23:18:09.147: E/AndroidRuntime(1784): at java.lang.reflect.Method.invoke(Method.java:521)
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-19 23:18:09.147: E/AndroidRuntime(1784): at dalvik.system.NativeStart.main(Native Method)
11-19 23:18:09.147: E/AndroidRuntime(1784): Caused by: java.lang.NullPointerException
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.example.trabalhosql.edicao.onCreate(edicao.java:42)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
11-19 23:18:09.147: E/AndroidRuntime(1784): ... 11 more
edicao.class
package com.example.trabalhosql;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class edicao extends Activity {
String id="";
String modeloCarro = "";
TextView textViewCarroEscolhido;
public SQLiteDatabase db;
public String BANCO = "banco.db";
public String TABELA = "carro";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listagemcarro);
Intent itRecebeParametros = getIntent();
if(itRecebeParametros != null){
id = itRecebeParametros.getStringExtra("id");
modeloCarro = itRecebeParametros.getStringExtra("modeloCarro");
}
textViewCarroEscolhido = (TextView) findViewById(R.id.textViewCarroEscolhido);
textViewCarroEscolhido.setText(modeloCarro);
}
}
EDIT
I'm guessing that this part of the edicao class is incorrect:
setContentView(R.layout.listagemcarro);
That itself might not have thrown the error, but trying to finding views (like your textView) in it that don't exist would.
textViewCarroEscolhido is null. Make sure that it exists in listagemcarro.xml
In case anyone comes here for calling intents in drawing situations such as canvas. Ensure you are not calling the intent multiple times. In my situation the invalidate() method kept getting called and made many intent calls. Ensure to use some sort of flip mechanism to stop invalidate() from being called. Will work like a charm.

Android: Application has stopped unexpectedly (What is the best way to further investigate?)

My test application contains a ListActivity that populate the content from Contacts. Error from LogCat does not explain the source of the exception since there are no project files involved.
It stops unexpectedly if running on an ADV or on a device (two different phones tested).
IMPORTANT NOTE: Error is thrown exactly WHEN the user scrolls the list to see more items: when two or three more items are shown. (Always crashes at the same point on the list, and both: scrolling with a finger or with a trackball).
What is the best way to investigate further?
10-13 13:21:00.662: E/AndroidRuntime(8031): FATAL EXCEPTION: main
10-13 13:21:00.662: E/AndroidRuntime(8031): java.lang.NullPointerException
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.widget.AbsListView.obtainView(AbsListView.java:1304)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.widget.ListView.makeAndAddView(ListView.java:1727)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.widget.ListView.fillDown(ListView.java:652)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.widget.ListView.fillGap(ListView.java:623)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.widget.AbsListView.trackMotionScroll(AbsListView.java:2944)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:2485)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.os.Handler.handleCallback(Handler.java:587)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.os.Handler.dispatchMessage(Handler.java:92)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.os.Looper.loop(Looper.java:123)
10-13 13:21:00.662: E/AndroidRuntime(8031): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-13 13:21:00.662: E/AndroidRuntime(8031): at java.lang.reflect.Method.invokeNative(Native Method)
10-13 13:21:00.662: E/AndroidRuntime(8031): at java.lang.reflect.Method.invoke(Method.java:521)
10-13 13:21:00.662: E/AndroidRuntime(8031): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
10-13 13:21:00.662: E/AndroidRuntime(8031): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-13 13:21:00.662: E/AndroidRuntime(8031): at dalvik.system.NativeStart.main(Native Method)
UPDATE: The code of the adapter:
package com.stripedbee.warayu;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ContactAdapter extends ArrayAdapter<Contact> {
private final List<Contact> _contacts;
private final Activity _context;
public ContactAdapter(Activity context, List<Contact> contacts) {
super(context, R.layout.contact_list_item, contacts);
this._contacts = contacts;
this._context = context;
}
static class ViewHolder {
protected TextView display_name;
protected TextView number;
protected TextView number_type;
private Contact contact;
protected void setContact(Contact contact) {
this.display_name.setText(contact.get_display_name());
this.number.setText(contact.get_number());
this.number_type.setText(contact.get_number_type());
this.contact = contact;
}
protected Contact getContact() {
return contact;
}
}
#Override
public Contact getItem(int position) {
return this._contacts.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflater = this._context.getLayoutInflater();
view = inflater.inflate(R.layout.contact_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.display_name = (TextView) view
.findViewById(R.id.txtDisplayName);
viewHolder.number = (TextView) view.findViewById(R.id.txtNumber);
viewHolder.number_type = (TextView) view
.findViewById(R.id.txtNumberType);
viewHolder.setContact(_contacts.get(position));
view.setTag(viewHolder);
}
return view;
}
}
You return a null view from your getView method when the convertView is not null(when the user starts scrolling for example). Your getView method should be like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = this._context.getLayoutInflater();
view = inflater.inflate(R.layout.contact_list_item, parent, false);
holder = new ViewHolder();
viewHolder.display_name = (TextView) view
.findViewById(R.id.txtDisplayName);
viewHolder.number = (TextView) view.findViewById(R.id.txtNumber);
viewHolder.number_type = (TextView) view
.findViewById(R.id.txtNumberType);
view.setTag(viewHolder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
holder.setContact(_contacts.get(position));
return view;
}

Categories

Resources