NullPointerException when scrolling ListView with images loaded from JSON - java

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);
}
}
}

Related

at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)

I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:353) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful

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());
}

Unable to start Activity Componentinfo (Adapter Constructor)

I tried to create a simple listview. I've done it many times & this is the first time i face such errors. Tried this in both Eclipse Luna & indigo. Both have the same error.
Here is where i create an instant of the adapter :
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class ActivityMain extends Activity {
public ArrayList<StructRemedy> remedies = new ArrayList<StructRemedy>();
private ListView lstContent;
public AdapterRemedy adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
adapter = new AdapterRemedy(remedies);
randomPopulation();
lstContent.setAdapter(adapter);
}
private void randomPopulation() {
for (int i = 0; i < 30; i++) {
StructRemedy remedy = new StructRemedy();
remedy.title = "Remedy" + i;
remedy.description = "Desc" + i;
remedy.rateValue = (float) (Math.random() * 5);
remedy.type = "tisane";
remedy.use = "Headaches";
remedies.add(remedy);
}
adapter.notifyDataSetChanged();
}
}
Now the error log (The error referes to the line where i create the constructor , u know the "super" line) :
06-08 10:03:27.875: E/AndroidRuntime(2715): FATAL EXCEPTION: main
06-08 10:03:27.875: E/AndroidRuntime(2715): java.lang.RuntimeException: Unable to start activity ComponentInfo{ahmad.azimi.app.herbal_remedies/test.test1.app.herbal_remedies.ActivityMain}: java.lang.NullPointerException
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.os.Handler.dispatchMessage(Handler.java:99)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.os.Looper.loop(Looper.java:137)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 10:03:27.875: E/AndroidRuntime(2715): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 10:03:27.875: E/AndroidRuntime(2715): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 10:03:27.875: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 10:03:27.875: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 10:03:27.875: E/AndroidRuntime(2715): at dalvik.system.NativeStart.main(Native Method)
06-08 10:03:27.875: E/AndroidRuntime(2715): Caused by: java.lang.NullPointerException
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
06-08 10:03:27.875: E/AndroidRuntime(2715): at test.test1.app.herbal_remedies.AdapterRemedy.<init>(AdapterRemedy.java:22)
06-08 10:03:27.875: E/AndroidRuntime(2715): at test.test1.app.herbal_remedies.ActivityMain.onCreate(ActivityMain.java:22)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.Activity.performCreate(Activity.java:5104)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-08 10:03:27.875: E/AndroidRuntime(2715): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
This is the adapter :
import java.util.ArrayList;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
public class AdapterRemedy extends ArrayAdapter<StructRemedy> {
public AdapterRemedy(ArrayList<StructRemedy> remedies) {
super(G.context, R.layout.adapter_notes, remedies);
}
private static class ViewHolder {
public TextView txtTitle;
public TextView txtType;
public TextView txtFor;
public RatingBar rating;
public ViewGroup layoutRoot;
public ImageView imgLogo;
public ViewHolder(View view) {
layoutRoot = (ViewGroup) view.findViewById(R.id.layoutRoot);
txtTitle = (TextView) view.findViewById(R.id.txtTitle);
txtType = (TextView) view.findViewById(R.id.txtType);
txtFor = (TextView) view.findViewById(R.id.txtFor);
rating = (RatingBar) view.findViewById(R.id.rate);
imgLogo = (ImageView) view.findViewById(R.id.imgLogo);
}
public void fill(final ArrayAdapter<StructRemedy> adapter, final StructRemedy item, final int position) {
txtTitle.setText(item.title);
txtType.setText(item.type);
txtFor.setText(item.use);
rating.setRating(item.rateValue);
//imgLogo.setImageBitmap(bm);
layoutRoot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(G.currentActivity, ActivitySelect.class);
intent.putExtra("POSITION", position);
G.currentActivity.startActivity(intent);
}
});
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
StructRemedy item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.adapter_notes, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
}
Try this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
randomPopulation();
}
Put adapter = new AdapterRemedy (remedies ) ; after randomPopulation. Or set adapter in randomPopulation method.
And remove adapter.notifyDataSetchanged() from randomPopulation.
Do some changes in your adapter code :
public AdapterRemedy(ArrayList<StructRemedy> remedies) {
super(G.context, R.layout.adapter_notes, remedies);
}
Change it to this :
public AdapterRemedy(context,ArrayList<StructRemedy> remedies) {
super(context, R.layout.adapter_notes, remedies);
}
And in randomPopulation :
adapter = new AdapterRemedy(this,remedies);
lstContent.setAdapter(adapter);
adapter.notifyDataSetChanged();
Change your onCreate() like ,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
randomPopulation();
adapter = new AdapterRemedy(remedies);
lstContent.setAdapter(adapter);
}
Call randomPopulation() before the adater Initialization. remove
adapter.notifyDataSetChanged();

AppCompatActivity OutOfMemoryError

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

Android get Status Bar Height giving java.lang.ExceptionInInitializerError

Additional Information (the original question below)
After following #ρяσѕρєяK advice in the comments section, I am getting the same error on another file (SizeNotifierRelativeLayout.java) and the error occurs at line 44, which is super.onLayout(changed, l, t, r, b);. The code for this file and the logcat are as follows:
SizeNotifierRelativeLayout.java
package com.app.name.widgets;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.widget.RelativeLayout;
import com.app.name.AndroidUtilities;
public class SizeNotifierRelativeLayout extends RelativeLayout {
private Rect rect = new Rect();
public SizeNotifierRelativeLayoutDelegate delegate;
public abstract interface SizeNotifierRelativeLayoutDelegate {
public abstract void onSizeChanged(int keyboardHeight);
}
public SizeNotifierRelativeLayout(Context context) {
super(context);
}
public SizeNotifierRelativeLayout(Context context, android.util.AttributeSet attrs) {
super(context, attrs);
}
public SizeNotifierRelativeLayout(Context context, android.util.AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (delegate != null) {
View rootView = this.getRootView();
int usableViewHeight = rootView.getHeight() - AndroidUtilities.statusBarHeight - AndroidUtilities.getViewInset(rootView);
this.getWindowVisibleDisplayFrame(rect);
int keyboardHeight = usableViewHeight - (rect.bottom - rect.top);
delegate.onSizeChanged(keyboardHeight);
}
}
}
logcat
10-15 09:09:57.918 23530-23530/? W/System.err﹕ at com.app.name.widgets.SizeNotifierRelativeLayout.onLayout(SizeNotifierRelativeLayout.java:44)
10-15 09:09:57.927 23530-23530/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.AbsListView.obtainView(AbsListView.java:2247)
at android.widget.ListView.makeAndAddView(ListView.java:1849)
at android.widget.ListView.fillDown(ListView.java:678)
at android.widget.ListView.fillFromTop(ListView.java:739)
at android.widget.ListView.layoutChildren(ListView.java:1664)
at android.widget.AbsListView.onLayout(AbsListView.java:2050)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1021)
at com.app.name.widgets.SizeNotifierRelativeLayout.onLayout(SizeNotifierRelativeLayout.java:44)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2230)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1994)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1181)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4942)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Orginal Question-> I have a statusbar get height function which is giving me a
FATAL EXCEPTION: main java.lang.ExceptionInInitializerError
The error is set of when MyActivity calls the
AndroidUtilities.statusBarHeight = getStatusBarHeight();
The function corresponding error:
at com.app.name.AndroidUtilities.(AndroidUtilities.java:31)
is
density = App.getInstance().getResources().getDisplayMetrics().density;
As I am relatively new to Android and Java, I would appreciate pointers as to what I am missing. Thanks!
MyActivity.java
package com.app.name;
import com.app.name.widgets.SizeNotifierRelativeLayout;
public class MyActivity extends ActionBarActivity implements ISideNavigationCallback, SizeNotifierRelativeLayout.SizeNotifierRelativeLayoutDelegate, NotificationCenter.NotificationCenterDelegate {
private SizeNotifierRelativeLayout sizeNotifierRelativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
AndroidUtilities.statusBarHeight = getStatusBarHeight();
sizeNotifierRelativeLayout = (SizeNotifierRelativeLayout) findViewById(R.id.chat_layout);
sizeNotifierRelativeLayout.delegate = this;
NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
}
/**
* Get the system status bar height
* #return
*/
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
}
App.java
package com.app.name;
import android.app.Application;
import android.os.Handler;
public class App extends Application {
private static App Instance;
public static volatile Handler applicationHandler = null;
#Override
public void onCreate() {
super.onCreate();
Instance=this;
applicationHandler = new Handler(getInstance().getMainLooper());
NativeLoader.initNativeLibs(App.getInstance());
}
public static App getInstance()
{
return Instance;
}
}
AndroidUtilities.java
package com.app.name;
public class AndroidUtilities {
public static float density = 1;
public static int statusBarHeight = 0;
public static Point displaySize = new Point();
static {
density = App.getInstance().getResources().getDisplayMetrics().density;
checkDisplaySize();
}
}
logcat
10-15 07:57:41.119 15076-15076/? W/System.err? at com.app.name.MyActivity.onCreate(MyActivity.java:197)
10-15 07:57:41.130 15076-15076/? W/System.err? at com.app.name.AndroidUtilities.<clinit>(AndroidUtilities.java:31)
10-15 07:57:41.145 15076-15076/? E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at com.app.name.MyActivity.onCreate(MyActivity.java:197)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.app.name.AndroidUtilities.<clinit>(AndroidUtilities.java:31)
            at com.app.name.MyActivity.onCreate(MyActivity.java:197)
            at android.app.Activity.performCreate(Activity.java:5122)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
            at android.app.ActivityThread.access$600(ActivityThread.java:165)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
            at android.os.Handler.dispatchMessage(Handler.java:107)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5370)
            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:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)

Categories

Resources