ListView.setAdapter NullPointerException - java

I was doing my homework for coursera course, when i catch NPE. Can't fix this problem for several days and can't continue without fixing. Google doesn't help.
UPDATED CODE DOWN THE PAGE
Here is my code:
MainActivity
List<Selfie> selfies = new ArrayList<Selfie>();
private CustomAdapter ADAPTER = new CustomAdapter(this, selfies);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
File youDir = new File("/sdcard/DailySelfie/");
outer : for (File f : youDir.listFiles()) {
//try to find selfie in files
if (f.isFile()) {
for (Selfie selfie : selfies) {
if (selfie.getSelfieName() == f.getName()) {
continue outer;
}
else { continue;}
}
//code below works only if file doesn't exist in selfies.
Bitmap myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
try {
selfies.add(new Selfie(f.getName(), myBitmap));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Selfie:
public class Selfie {
private Bitmap selfieBitmap;
private String selfieName;
public Selfie(String selfieName, Bitmap selfieBitmap) {
this.selfieName = selfieName;
this.selfieBitmap = selfieBitmap;
}
public String getSelfieName() {
return selfieName;
}
public Bitmap getSelfieBitmap() {
return selfieBitmap;
}
}
CustomAdapter:
private Context context;
private List<Selfie> selfies = new ArrayList<Selfie>();
public CustomAdapter(Context context, List<Selfie> selfies) {
this.context = context;
this.selfies = selfies;
}
#Override
public int getCount() {
return selfies.size();
}
#Override
public Object getItem(int position) {
return selfies.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
Selfie selfie = selfies.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = new View(context);
//get layout from row.xml
rowView = inflater.inflate(R.layout.row, null);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
imageView.setImageBitmap(selfie.getSelfieBitmap());
TextView textView = (TextView) rowView.findViewById(R.id.text);
textView.setText(selfie.getSelfieName());
}
return convertView;
}
}
ADB:
04-27 13:17:58.792: E/AndroidRuntime(1979): FATAL EXCEPTION: main
04-27 13:17:58.792: E/AndroidRuntime(1979): java.lang.NullPointerException
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.AbsListView.obtainView(AbsListView.java:2179)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.ListView.makeAndAddView(ListView.java:1840)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.ListView.fillDown(ListView.java:675)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.ListView.fillFromTop(ListView.java:736)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.ListView.layoutChildren(ListView.java:1655)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.AbsListView.onLayout(AbsListView.java:2012)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.View.layout(View.java:14289)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewGroup.layout(ViewGroup.java:4562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1660)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.LinearLayout.onLayout(LinearLayout.java:1436)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.View.layout(View.java:14289)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewGroup.layout(ViewGroup.java:4562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.View.layout(View.java:14289)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewGroup.layout(ViewGroup.java:4562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:502)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.View.layout(View.java:14289)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewGroup.layout(ViewGroup.java:4562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.View.layout(View.java:14289)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewGroup.layout(ViewGroup.java:4562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.View.layout(View.java:14289)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewGroup.layout(ViewGroup.java:4562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.View.layout(View.java:14289)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewGroup.layout(ViewGroup.java:4562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.Choreographer.doFrame(Choreographer.java:532)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.os.Handler.handleCallback(Handler.java:730)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.os.Handler.dispatchMessage(Handler.java:92)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.os.Looper.loop(Looper.java:137)
04-27 13:17:58.792: E/AndroidRuntime(1979): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-27 13:17:58.792: E/AndroidRuntime(1979): at java.lang.reflect.Method.invokeNative(Native Method)
04-27 13:17:58.792: E/AndroidRuntime(1979): at java.lang.reflect.Method.invoke(Method.java:525)
04-27 13:17:58.792: E/AndroidRuntime(1979): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-27 13:17:58.792: E/AndroidRuntime(1979): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-27 13:17:58.792: E/AndroidRuntime(1979): at dalvik.system.NativeStart.main(Native Method)
Seems that I have a NPE at lv.setAdapter(ADAPTER);. Found same problems on StackOverflow, but no solution helped me.
UPDATE: rewrote my code, so it's now
List<Selfie> selfies;
ListView lv;
private CustomAdapter ADAPTER;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selfies = new ArrayList<Selfie>();
lv = (ListView) findViewById(R.id.listView);
ADAPTER = new CustomAdapter(this, selfies);
}
#Override
protected void onResume() {
super.onResume();
...
lv.setAdapter(ADAPTER);
}
still have same problem - NPE. I tried to move "lv =.. ; ADAPTER =..." to onResume, tried to put it to start of onResume - it doesn't help :(

Add
private CustomAdapter ADAPTER = new CustomAdapter(this, selfies);
into onCreate method because this context is use in class methods.i.e. rewrite as
private CustomAdapter ADAPTER;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ADAPTER = new CustomAdapter(this, selfies);
}

I believe the NPE relates to your ListView. Try to structure your app so that you declare class variables and initialise them in onCreate(). That way, you reference them later on (as you do in onResume()).
List<Selfie> selfies;
private CustomAdapter ADAPTER;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.listView);
selfies = new ArrayList<Selfie>();
ADAPTER = new CustomAdapter(this, selfies);
lv.setAdapter(ADAPTER);
}
#Override
protected void onResume() {
super.onResume();
/*
*I don't quite see the purpose in this below section,
*as you can account for a null ArrayList in your adapter class
*/
if (ADAPTER.getCount() >= 0) {
lv.setAdapter(ADAPTER);
}
}
Also, to explain the comment I made above a little better, you can account for null data in your adapter getCount() by treating null data as a 0 size list:
getCount() {
if (selfies == null || selfies.isEmpty()) {
return 0;
}
return selfies.size;
}
Edit: If the problem is confined to your adapter, then it may be an NPE coming from getView(). You can try the code below:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
Selfie selfie = selfies.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row, parent, false);
} else {
rowView = convertView;
}
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
imageView.setImageBitmap(selfie.getSelfieBitmap());
TextView textView = (TextView) rowView.findViewById(R.id.text);
textView.setText(selfie.getSelfieName());
return rowView;
}

Check if this returns anything other than null:
ListView lv = (ListView) findViewById(R.id.listView);
Could be that it cannot find the list.

Since you are calling ListView lv = (ListView) findViewById(R.id.listView); in onResume, setContentView has not been called. onResume is always called before onCreate, so your ListView is not currently in the context. Hence the NullPointerException.
Change your Activity code to this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView) findViewById(R.id.listView);
}
#Override
protected void onResume() {
super.onResume();
}

The problem is about the this you have setteded, when you initialazed the new Custom.... You have to initilizate it onCreate() ! (I mean for MainActivity class )

your arraylist of selfies is empty because i see nothing added?
also your class Selfie only has getter but no setters, so how do u set a selfie to your arraylist of selfies then?

The answer is that in my getView() code i returned convertView but inflated rowView. So convertView stays null. PPartisan showed me my mistake and gave worked code(below). To up the rating i must have 15 reputation, and i don't have. Could somebody, please, up his rating and his right answer?
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
Selfie selfie = selfies.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row, parent, false);
} else {
rowView = convertView;
}
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
imageView.setImageBitmap(selfie.getSelfieBitmap());
TextView textView = (TextView) rowView.findViewById(R.id.text);
textView.setText(selfie.getSelfieName());
return rowView;
}

Related

How to rectify this error iin Recyclerview with database

When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}

i can't get Item Detail

I am learning android development and i have a problem displaying contact detail in my app.
When I click an item of contact activity, the app hangs.
Could you help me please?
This is the activity App of Contact List.
public class ListViewActivity3 extends AppCompatActivity {
ListView listView;
List<ContactHelper> listAdapter;
public static final String Key_Postion = "keyPosition" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listAdapter = new ArrayList<ContactHelper>();
listAdapter.clear();
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listView = (ListView) findViewById(R.id.listviewCustomAdapter);
listView.setAdapter(new AdapterCustom(ListViewActivity3.this, R.layout.listviewitem1, listAdapter));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i3 = new Intent(ListViewActivity3.this, ContactDetailItem.class);
i3.putExtra(Key_Postion, position);
startActivity(i3);
}
});
}
}
and this the ConatctDetailItem
public class ContactDetailItem extends AppCompatActivity {
TextView n, ph, surn;
ImageView imgC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_detail_item);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
n = (TextView) findViewById(R.id.contactName);
surn = (TextView) findViewById(R.id.contactSurname);
ph = (TextView) findViewById(R.id.contactPhone);
imgC = (ImageView) findViewById(R.id.imgContact);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
ContactHelper contactHelper = new ContactHelper();
ListViewActivity3 lv = new ListViewActivity3();
int position = bundle.getInt(ListViewActivity3.Key_Postion);
n.setText(lv.listAdapter.get(position).getName());
surn.setText(lv.listAdapter.get(position).getSurname());
ph.setText(lv.listAdapter.get(position).getPhone());
imgC.setImageResource(lv.listAdapter.get(position).getPhoto());
}
}
}
Here is the logcat.
com.example.achre.activityapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.achre.activityapp/com.example.achre.activityapp.ContactDetailItem}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.achre.activityapp.ContactDetailItem.onCreate(ContactDetailItem.java:50)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
In ContactDetailItem you are creating new ListViewActivity3. Instead it put to extra ContactHelper object.
Change your code like this:
Intent i3 = new Intent(ListViewActivity3.this, ContactDetailItem.class);
i3.putExtra(Key_Postion, listAdapter.get(position));
startActivity(i3);
and in ContactDetailItem:
ContactHelper contactHelper = (ContactHelper) bundle.getSerializableExtra(ListViewActivity3.Key_Postion);
n.setText(contactHelper.getName());
// ...
also your ContactHelper class must implement Serializable interface

Recyclerview java.lang.IndexOutOfBoundException

When I scroll down too fast and click on whatever item I land on I get this following error then the app crashes: java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{440a7260 position=15 id=-1, oldPos=14, pLpos:14 scrap tmpDetached no parent} I have read that it's a (known) bug in the recyclerview. Does someone have a way to bypass it? Maybe restrict scroll to let all the JSON data to load properly in recyclerview
I use the following method to send my JSON request
private void sendJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, urlUpcoming, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
gamesList.addAll(parseJsonResponse(response));
adapterUpcoming.notifyDataSetChanged();
adapterUpcoming.setData(gamesList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error getting data
}
});
//add the request
mRequestQueue.add(request);
}
The parseJsonResponse returns an array list, this is where the magic happens(fetching the data from the api)
private ArrayList<Game> parseJsonResponse(JSONObject response) {
final ArrayList<Game> games = new ArrayList<>();
//{fetching data with volley} code omitted
return games;
}
OnCreateView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_upcoming, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.upcomingGamesList);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
adapterUpcoming = new AdapterUpcoming(getActivity());
mRecyclerView.setAdapter(adapterUpcoming);
urlUpcoming = MyApplication.getUrl(); //the url from which I'm fetching my data
sendJsonRequest();
return view;
Error (The error is the same but values different):
E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{52ea27c0 position=5 id=-1, oldPos=4, pLpos:4 scrap tmpDetached no parent}
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:3229)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3359)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:523)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1942)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1594)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:502)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Thanks!!
Please always post the code that you need help with. Also make sure that this code is concise and well commented. However an IndexOutOfBounds exception means that somewhere you are trying to look at a string or an array. And looking at A negative number or a number too high. But it says position 15 so it is going past the end of the array. Trying adding a check statement if(oldPosition+1

listview row color dependent on value from DB

Ok, I have app that store data about Items in SQLite database.
Items are listed by name and presented on main activity. Every item has some details and there is detail about owner. I want set 2 colors of rows on list. 1 color when i'm owner (i get true from DB), and 2nd color for other case.
public class BHItemsAdapter extends ArrayAdapter<BHItem> {
private Activity context;
private List<BHItem> bhItems;
private MainActivity cbOwn ;
public BHItemsAdapter(Activity context, List<BHItem> bhItems) {
super(context, R.layout.bhitems_list_item, bhItems);
this.context = context;
this.bhItems = bhItems;
}
static class ViewHolder {
public TextView tvBHItemDescription;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
View rowView = convertView;
if(rowView == null) {
LayoutInflater layoutInflater = context.getLayoutInflater();
rowView = layoutInflater.inflate(R.layout.bhitems_list_item, null, true);
viewHolder = new ViewHolder();
viewHolder.tvBHItemDescription = (TextView) rowView.findViewById(R.id.tvBHItemDescription);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
BHItem task = bhItems.get(position);
/*line 49*/ if (cbOwn.onCheckboxClicked1())
{
rowView.setBackgroundColor(0x30ff2020);
}
else {
rowView.setBackgroundColor(0x30aaffff);
}
viewHolder.tvBHItemDescription.setText(task.getItem());
return rowView;
}
}
Even when I'm sending true or false i'm getting nullpointerexeption
//this is from main activity
public boolean onCheckboxClicked1() {
return true;
}
private void fillListViewData() {
bhDbAdapter = new DbAdapter(getApplicationContext());
bhDbAdapter.open();
getUncompletedTasks();
getCompletedTasks();
bhItemsAdapter = new BHItemsAdapter(this, bhItemList);
lvTodos.setAdapter(bhItemsAdapter);
}
private void initUiElements() {
etItem = (EditText) findViewById(R.id.etItem);
etDescription = (EditText) findViewById(R.id.etDescription);
etOwner = (EditText) findViewById(R.id.etOwner);
etBorrower = (EditText) findViewById(R.id.etBorrower);
tvItem = (TextView) findViewById(R.id.tvItem);
tvDescription = (TextView) findViewById(R.id.tvDescription);
tvOwner = (TextView) findViewById(R.id.tvOwner);
tvBorrower = (TextView) findViewById(R.id.tvBorrower);
tvCategory = (TextView) findViewById(R.id.tvCategory);
tvReturndate = (TextView) findViewById(R.id.tvReturndate);
lvTodos = (ListView) findViewById(R.id.lvTodos);
lvArchive = (ListView) findViewById(R.id.lvArchive);
llItemAdder = (LinearLayout) findViewById(R.id.llItemAdder);
llIAButtons = (LinearLayout) findViewById(R.id.llIAButtons);
llIAEditButtons = (LinearLayout) findViewById(R.id.llIAEditButtons);
llControlButtons = (LinearLayout) findViewById(R.id.llControlButtons);
llNewTaskButtons = (LinearLayout) findViewById(R.id.llNewTaskButtons);
llItemDetails = (LinearLayout) findViewById(R.id.llItemDetails);
dpReturndate = (DatePicker) findViewById(R.id.dpReturndate);
ivEditImage = (ImageView) findViewById(R.id.ivEditImage);
ivDetailImage = (ImageView) findViewById(R.id.ivDetailImage);
cbReturned = (CheckBox) findViewById(R.id.cbReturned);
spCategory = (Spinner) findViewById(R.id.spCategory);
cbOwn = (CheckBox) findViewById(R.id.cbOwn);}
// this is how i get my value (owner or not)
logcat
09-11 18:30:15.201 5825-5825/szub.borrowinghelper D/AndroidRuntime﹕ Shutting down VM
09-11 18:30:15.201 5825-5825/szub.borrowinghelper W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a99ba8)
09-11 18:30:15.211 5825-5825/szub.borrowinghelper E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: szub.borrowinghelper, PID: 5825
java.lang.NullPointerException
at soulflier.borrowinghelper.BHItemsAdapter.getView(BHItemsAdapter.java:49)
at android.widget.AbsListView.obtainView(AbsListView.java:2263)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
at android.widget.ListView.onMeasure(ListView.java:1175)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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)
I have no idea how send the value to that adapter.
I'm newbe in programing
thx for any help

Show GridView images from JSON Android

I have a problem when displaying images from JSON to GridView could help me .
GalleryActivity.java
public class GalleryActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_layout);
Intent i = getIntent();
String tempid = i.getStringExtra("tempid");
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this,tempid));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public String[] mThumbIds;
private static String KEY_SUCCESS = "success";
private static String KEY_IMAGES = "images";
private static String KEY_IMAGE = "url_img";
// Constructor
public ImageAdapter(Context c,String tempID){
mContext = c;
final DealerFunctions dealerFunction = new DealerFunctions();
JSONObject json = dealerFunction.getImages(tempID);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
JSONArray imagesFields = json
.getJSONArray(KEY_IMAGES);
for (int i = 0; i < imagesFields.length(); i++) {
JSONObject x = imagesFields.getJSONObject(i);
mThumbIds[i] = x.getString(KEY_IMAGE);
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView==null){
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
}else{
imageView = (ImageView) convertView;
}
imageView.setBackgroundDrawable(Drawable.createFromPath(mThumbIds[position]));
return imageView;
}
}
Don't Work...
when I run the application, closes immediately assume that the problem comes in imageView.setBackgroundDrawable (Drawable.createFromPath (mThumbIds [position]));
I need your help guys
Logcat Errors as follows.
03-27 10:50:12.658: D/AndroidRuntime(1782): Shutting down VM
03-27 10:50:12.658: W/dalvikvm(1782): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-27 10:50:12.678: E/AndroidRuntime(1782): FATAL EXCEPTION: main
03-27 10:50:12.678: E/AndroidRuntime(1782): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.montalvo.dealer/com.montalvo.dealer.GalleryActivity}: java.lang.NullPointerException
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.os.Handler.dispatchMessage(Handler.java:99)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.os.Looper.loop(Looper.java:123)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-27 10:50:12.678: E/AndroidRuntime(1782): at java.lang.reflect.Method.invokeNative(Native Method)
03-27 10:50:12.678: E/AndroidRuntime(1782): at java.lang.reflect.Method.invoke(Method.java:521)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-27 10:50:12.678: E/AndroidRuntime(1782): at dalvik.system.NativeStart.main(Native Method)
03-27 10:50:12.678: E/AndroidRuntime(1782): Caused by: java.lang.NullPointerException
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.montalvo.dealer.ImageAdapter.<init>(ImageAdapter.java:57)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.montalvo.dealer.GalleryActivity.onCreate(GalleryActivity.java:25)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-27 10:50:12.678: E/AndroidRuntime(1782): ... 11 more
03-27 10:50:15.501: I/Process(1782): Sending signal. PID: 1782 SIG: 9
You are mixing things up here, use this
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
imageView.setBackgroundDrawable(Drawable.createFromPath(mThumbIds[position]));
return imageView;
}
The pattern you have used is that of the ViewHolder but you are not creating any views. If you do want to use the ViewHolder model then,
first create an xml with an ImageView.
Create a ViewHolder class in your ImageAdapter with an ImageView.
In the getView() method, inflate the xml.
create the viewholder for the case of convertview == null
set the viewholder as the TAG of the convertview.
in the else condtion, assign the previously created viewholder to the convertview.

Categories

Resources