NullPointException in ListView - java

Please have a look at the following code
activity_form.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Form" >
<ImageView
android:id="#+id/logo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/logo" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/logo"
android:layout_marginTop="10dp"
android:text="#string/title" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/listImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/star" />
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="10dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Form.java
package com.example.callmanager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Form extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
ListView lv = (ListView)findViewById(android.R.id.list);
String arr[] = getResources().getStringArray(R.array.branch_list);
lv.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_1,R.id.listText,arr));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_form, menu);
return true;
}
private class MyAdapter extends ArrayAdapter
{
public MyAdapter(Context context, int resource, int textViewResourceId,
Object[] objects) {
super(context, resource, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View contentView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_layout, parent,false);
TextView tv = (TextView)findViewById(R.id.listText);
ImageView iv = (ImageView)findViewById(R.id.listImage);
String arr[] = getResources().getStringArray(R.array.branch_list);
tv.setText(arr[position]);
if(arr[position].equals("Anuradhapura"))
iv.setImageResource(R.drawable.star);
return view;
}
}
}
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Esoft Call Manager</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title"><b>Select a Branch To Call</b></string>
<string-array name="branch_list">
<item>Anuradhapura</item>
<item>Avissawella</item>
</string-array>
</resources>
When I run this code, I get the 'NullPointException'. I am adding the complete log file here
02-08 21:04:01.463: D/dalvikvm(490): GC_EXTERNAL_ALLOC freed 43K, 53% free 2551K/5379K, external 1949K/2137K, paused 82ms
02-08 21:04:01.713: D/AndroidRuntime(490): Shutting down VM
02-08 21:04:01.713: W/dalvikvm(490): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-08 21:04:01.733: E/AndroidRuntime(490): FATAL EXCEPTION: main
02-08 21:04:01.733: E/AndroidRuntime(490): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.callmanager/com.example.callmanager.Form}: java.lang.NullPointerException
02-08 21:04:01.733: E/AndroidRuntime(490): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.os.Looper.loop(Looper.java:123)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-08 21:04:01.733: E/AndroidRuntime(490): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 21:04:01.733: E/AndroidRuntime(490): at java.lang.reflect.Method.invoke(Method.java:507)
02-08 21:04:01.733: E/AndroidRuntime(490): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-08 21:04:01.733: E/AndroidRuntime(490): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-08 21:04:01.733: E/AndroidRuntime(490): at dalvik.system.NativeStart.main(Native Method)
02-08 21:04:01.733: E/AndroidRuntime(490): Caused by: java.lang.NullPointerException
02-08 21:04:01.733: E/AndroidRuntime(490): at com.example.esoftcallmanager.Form.onCreate(Form.java:24)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-08 21:04:01.733: E/AndroidRuntime(490): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-08 21:04:01.733: E/AndroidRuntime(490): ... 11 more
I am adding the folder structure below if it helps
Why I am getting this error? How to solve this? Please help!

try this:
change this
ListView lv = (ListView)findViewById(android.R.id.list);
for:
ListView lv = (ListView)findViewById(R.id.list);
Normally they use android.R.id.list when class extends a ListActivity

Change:
ListView lv = (ListView)findViewById(android.R.id.list);
to
ListView lv = (ListView)findViewById(R.id.list);
Unless you have an id in your XML in the format of android:id="#android:id/myID", you don't need to use android.R. Whenever you use one of your own IDs, you can simply use R.id.Whatever

The issue is right here. ListView lv = (ListView)findViewById(android.R.id.list); you reference the Id android.R.id.list
however in your layout you reference android:id="#+id/list" which creates an Id in the Resources class called list. so you should be referencing R.id.list if you debug you will find that the lv variable is null because it wasn't found because you referenced the wrong id.

If your are using your own layout you don't need any more to write android.R just remove android and reorganize your class

Try this.
I hope it will solve your NPE.
Change it
ListView lv = (ListView)findViewById(android.R.id.list);
to
ListView lv = (ListView)findViewById(R.id.list);
Actually You have defined the list view in the layout activity_form.xml have name list so you need to write the R.id.list.

I managed to solve this by my self. Following edits were required.
activity_form.xml
The "id" of the ListView should be
android:id="#android:id/list"
Form.java
It should call the ListView in this way
ListView lv = (ListView) findViewById(android.R.id.list);
Inside getView(), the initialization of the TextView and ImageView should be like this
TextView tv = (TextView) view.findViewById(R.id.listText);
ImageView iv = (ImageView) view.findViewById(R.id.listImage);
Note the view.findViewById() part.

Related

android.view.InflateException: Binary XML file line #16: Error inflating class <unknown> (ListView Maybe?) [duplicate]

This question already exists:
android.view.InflateException: Binary XML file line #16: Error inflating class fragment
Closed 6 years ago.
I made an app, it works well in virtual device and real device, but today my app is throwing exceptions, maybe it is the same with some old errors in here, but I can not find my own answer for this. So, please tell me how to solve it, thanks so much
here is my logcat
FATAL EXCEPTION: main
Process: com.gvc.tvschedule, PID: 1918
android.view.InflateException: Binary XML file line #16: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:620)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:121)
at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
at android.widget.AbsListView.obtainView(AbsListView.java:2255)
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.widget.RelativeLayout.measureChild(RelativeLayout.java:689)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
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 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 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:1912)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
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:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
... 48 more
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x12/d=0x0 a=2 r=0x7f0b0068}
at android.content.res.Resources.loadDrawable(Resources.java:2073)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.TextView.<init>(TextView.java:806)
at android.widget.TextView.<init>(TextView.java:618)
... 51
here under is Layout XML: getprogram_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/relativeLayoutProgram"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="#+id/relativeLayoutProgram"
android:orientation="vertical"
android:layout_marginTop="40dp">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true">
</ListView>
<!-- #android:id/list or #id/android:list -->
</RelativeLayout>
</RelativeLayout>
and: view_program_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/programtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:paddingTop="15sp"
android:paddingLeft="6sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/programtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:drawableLeft="#+id/programtime" />
<!-- android:background="#color/blue2" -->
</LinearLayout>
and Java : ProgramPickerActivity.java
package com.gvc.tvschedule;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.gvc.service.DBController;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ProgramPickerActivity extends Activity {
// DB Class to perform DB related operations
DBController controller = new DBController(this);
// Progress Dialog Object
ProgressDialog prgDialog;
HashMap<String, String> queryValues;
private static String titleTextFromView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.getprogram_main);
ArrayList<HashMap<String, String>> programList = controller.generalProgram(MainActivity.getNameOfChannel(), DatePickerActivity.getDate());
if (programList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(getApplicationContext(), programList, R.layout.view_program_entry, new String[] {
"ptime", "ptitle" }, new int[] { R.id.programtime, R.id.programtitle });
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView titleVIew = (TextView) view.findViewById(R.id.programtitle);
titleTextFromView = titleVIew.getText().toString();
createPopupWindownForDescription(titleTextFromView);
}
});
}
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("loading...");
prgDialog.setCancelable(false);
}
private void createPopupWindownForDescription(String pTitle){
String content = controller.getDescription(pTitle);
AlertDialog.Builder builder = new AlertDialog.Builder(ProgramPickerActivity.this);
builder.setTitle("Content");
builder.setMessage(content);
builder.show();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if(prgDialog!=null)
prgDialog.dismiss();
}
public static String getTitleTextFromView(){
return titleTextFromView;
}
}
I think the trouble is related with the listview, because, when no data put on listview, it is fine, but with data, it threw the errors.
I believe your current problem is
<TextView
android:id="#+id/programtitle"
...
android:drawableLeft="#+id/programtime" /> // HERE
You are referencing the other TextView but you should be referencing a Drawable. My guess is that you want to put it to the left of the other TextView?
If this is the case, the LinearLayout will lay them out from left to right by default so you just need to put them in the order that you want them to appear. Also, not a problem but since they are left to right by default, there's no need for
android:orientation="horizontal"
It's not showing when you don't have any items in your ListView because the layout is never inflated so the error is never caught.
Docs
android:id="#+id/list"
use that, you're welcome
PS: Change
ListView myList = (ListView) findViewById(android.R.id.list);
for:
ListView myList = (ListView) findViewById(R.id.list);

Unable to start activity: NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Hi I am encountering a null pointer error when I click on the activity Links. The purpose of my feature is to call a list of links in the form of list view. Below is the logcat and as far as I understand it is coming from my onItemClickListener, but I can't seem to point out the null error.:
sitesList.setOnItemClickListener(new OnItemClickListener()
Links.java
package com.example.sgrecipe;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Links extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getLink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://dl.dropboxusercontent.com/u/5724095/XmlParseExample/stacksites.xml", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(Links.this, -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
}
activity_links.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Links" >
<ListView
android:id="#+id/sitesList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
row_site.xml (for the listview)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/iconImg"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="8dp" />
<TextView
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/aboutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="12sp"
android:layout_below="#id/nameTxt"
/>
</RelativeLayout>
Here is the logcat:
02-23 15:13:10.856: E/AndroidRuntime(8201): FATAL EXCEPTION: main
02-23 15:13:10.856: E/AndroidRuntime(8201): Process: com.example.sgrecipe, PID: 8201
02-23 15:13:10.856: E/AndroidRuntime(8201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sgrecipe/com.example.sgrecipe.Links}: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.access$800(ActivityThread.java:163)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Handler.dispatchMessage(Handler.java:102)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Looper.loop(Looper.java:157)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.main(ActivityThread.java:5335)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invokeNative(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invoke(Method.java:515)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-23 15:13:10.856: E/AndroidRuntime(8201): at dalvik.system.NativeStart.main(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): Caused by: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.example.sgrecipe.Links.onCreate(Links.java:36)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Activity.performCreate(Activity.java:5389)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
Any help is really appreciate, thank you!
Change following line
setContentView(R.layout.activity_main);
to
setContentView(R.layout.activity_links);
Seems like your using different layouts:
setContentView(R.layout.activity_main);
vs
activity_links.xml

Going from Activity to ListActivity on Android

I am new to android development and I need help with going from an Acticity to a Listactivity.
I have a button in my mainActivity, here is the code:
package com.mz47.kazeroon;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DescriptionListActivity.class);
//intent.putExtra("thetext", edt.getText().toString());
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
If I click that button, my intention it will go to:
package com.mz47.kazeroon;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.EventLogTags.Description;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class DescriptionListActivity extends ListActivity {
//Database Helper
MyDatabaseHelper db = new MyDatabaseHelper(getApplicationContext());;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.desc_list_layout);
setListAdapter(new DescriptionAdapter(this,
android.R.layout.simple_list_item_1,
R.id.textView1, db.getAllDescriptionNames()));
db.close();
}
private class DescriptionAdapter extends ArrayAdapter<String>{
public DescriptionAdapter(Context context, int resource,
int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, parent, false);
MyDescription[] descriptions = (MyDescription[])db.getAllDescriptions().toArray();
ImageView imgv = (ImageView) row.findViewById(R.id.imageView1);
TextView txtv = (TextView) row.findViewById(R.id.textView1);
txtv.setText(descriptions[position].getDescriptionName());
imgv.setImageBitmap(db.getImage(descriptions[position].getDescriptionID()).getImageData());
return row;
}
}
}
My question is why my application has stopped unexpectedly?
In manifest I register the DescriptionListActivity class as an Activity
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mz47.kazeroon"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mz47.kazeroon.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.mz47.kazeroon.DescriptionListActivity"></activity>
</application>
</manifest>
Logcat:
03-11 16:10:26.887: D/dalvikvm(3186): GC_EXPLICIT freed 5K, 58% free 2569K/6023K, external 716K/1228K, paused 61ms
03-11 16:10:53.627: D/dalvikvm(3186): Debugger has detached; object registry had 1 entries
03-11 16:18:32.777: D/AndroidRuntime(16464): Shutting down VM
03-11 16:18:32.777: W/dalvikvm(16464): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-11 16:18:32.797: E/AndroidRuntime(16464): FATAL EXCEPTION: main
03-11 16:18:32.797: E/AndroidRuntime(16464): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mz47.kazeroon/com.mz47.kazeroon.DescriptionListActivity}: java.lang.NullPointerException
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.os.Looper.loop(Looper.java:123)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-11 16:18:32.797: E/AndroidRuntime(16464): at java.lang.reflect.Method.invokeNative(Native Method)
03-11 16:18:32.797: E/AndroidRuntime(16464): at java.lang.reflect.Method.invoke(Method.java:507)
03-11 16:18:32.797: E/AndroidRuntime(16464): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-11 16:18:32.797: E/AndroidRuntime(16464): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-11 16:18:32.797: E/AndroidRuntime(16464): at dalvik.system.NativeStart.main(Native Method)
03-11 16:18:32.797: E/AndroidRuntime(16464): Caused by: java.lang.NullPointerException
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-11 16:18:32.797: E/AndroidRuntime(16464): at com.mz47.kazeroon.DescriptionListActivity.<init>(DescriptionListActivity.java:18)
03-11 16:18:32.797: E/AndroidRuntime(16464): at java.lang.Class.newInstanceImpl(Native Method)
03-11 16:18:32.797: E/AndroidRuntime(16464): at java.lang.Class.newInstance(Class.java:1409)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-11 16:18:32.797: E/AndroidRuntime(16464): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
03-11 16:18:32.797: E/AndroidRuntime(16464): ... 11 more
Other xml files:
desc_list_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp" >
</ListView>
</LinearLayout>
list_items.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxHeight="48dp"
android:maxWidth="48dp"
android:minHeight="48dp"
android:minWidth="48dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
You have initialized your MyDatabaseHelper db to a context that is not yet existing
MyDatabaseHelper db = new MyDatabaseHelper(getApplicationContext());;
It should be done like this:
MyDatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.db = new MyDatabaseHelper(getApplicationContext());
setContentView(R.layout.desc_list_layout);
setListAdapter(new DescriptionAdapter(this,
android.R.layout.simple_list_item_1,
R.id.textView1, db.getAllDescriptionNames()));
db.close();
}
The problem is here:
MyDatabaseHelper db = new MyDatabaseHelper(getApplicationContext());
Method getApplicationContext() returns context after calling super.onCreate only. So try to change your activity like this:
MyDatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new MyDatabaseHelper(getApplicationContext());
//rest of your code
}

NullpointerException in Listview on android

Hello everyone I'm working with a ListView and when i open the activity my app crashes due to a NullPointerException. Everything is declared, so I really have no idea of why this is happening.
So I have this layouts:
delete.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/background"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView android:id="#android:id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
<Button
android:id="#+id/btn_deleteAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/deleteAll"/>
</LinearLayout>
</ScrollView>
And item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
And my ListActivity class is:
package com.example.calendar;
import com.example.calendar.DBHandler;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class DeleteAppointment extends ListActivity implements OnClickListener{
DBHandler db;
Appointment app;
ListView list;
Cursor cursor;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.delete);
Button deleteAll = (Button)findViewById(R.id.btn_deleteAll);
list = (ListView) findViewById(R.id.list);
deleteAll.setOnClickListener(this);
db = new DBHandler(this);
cursor = getContentResolver().query(db.CONTENT_URI, new String[]{app._date, app._title, app._time, app._details}, null, null, "asc");
startManagingCursor(cursor);
String[] columns = new String[]{app._date, app._title, app._time, app._details};
int[] to = new int[]{R.id.date, R.id.name, R.id.time, R.id.details};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, columns, to);
this.setListAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_deleteAll:
finish();
break;
}
}
}
The line where it crashes is line 28, which is
cursor = getContentResolver().query(db.CONTENT_URI, new String[]{app._date, app._title, app._time, app._details}, null, null, "asc");
Logcat stacktrace:
03-23 18:54:51.705: E/AndroidRuntime(1070): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calendar/com.example.calendar.DeleteAppointment}: java.lang.NullPointerException
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.ActivityThread.access$600(ActivityThread.java:122)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.os.Looper.loop(Looper.java:137)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-23 18:54:51.705: E/AndroidRuntime(1070): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 18:54:51.705: E/AndroidRuntime(1070): at java.lang.reflect.Method.invoke(Method.java:511)
03-23 18:54:51.705: E/AndroidRuntime(1070): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-23 18:54:51.705: E/AndroidRuntime(1070): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-23 18:54:51.705: E/AndroidRuntime(1070): at dalvik.system.NativeStart.main(Native Method)
03-23 18:54:51.705: E/AndroidRuntime(1070): Caused by: java.lang.NullPointerException
03-23 18:54:51.705: E/AndroidRuntime(1070): at com.example.calendar.DeleteAppointment.onCreate(DeleteAppointment.java:28)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.Activity.performCreate(Activity.java:4465)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-23 18:54:51.705: E/AndroidRuntime(1070): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
Please help me.
app is not initialized in your code. you need initialize that before using
you need something like:
app = new Appointment();
and if you are using a ListActivity, you need to have a ListView who's id is android.R.list in your layout file.
Use android.R.id.list or getListView() instead of R.id.list to initialize ListView :
list = (ListView) findViewById(android.R.id.list);
OR
list = getListView();

PullToRefreshGridView Inflate Exception

I am using this library https://github.com/chrisbanes/Android-PullToRefresh for implementing a refreshable grid view and i am getting this error:
android.view.InflateException: Binary XML file line #8: Error inflating class com.handmark.pulltorefresh.library.PullToRefreshGridView
at android.view.LayoutInflater.createView(LayoutInflater.java:518)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at com.example.retrievetweets.FragmentPhotos.onCreateView(FragmentPhotos.java:55)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:238)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 24 more
Caused by: java.lang.NullPointerException
at com.handmark.pulltorefresh.library.internal.IndicatorLayout.<init>(IndicatorLayout.java:66)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.addIndicatorViews(PullToRefreshAdapterViewBase.java:355)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.updateUIForMode(PullToRefreshAdapterViewBase.java:328)
at com.handmark.pulltorefresh.library.PullToRefreshBase.init(PullToRefreshBase.java:1142)
at com.handmark.pulltorefresh.library.PullToRefreshBase.<init>(PullToRefreshBase.java:113)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.<init>(PullToRefreshAdapterViewBase.java:74)
at com.handmark.pulltorefresh.library.PullToRefreshGridView.<init>(PullToRefreshGridView.java:35)
... 27 more
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- The PullToRefreshGridView replaces a standard GridView widget. -->
<com.handmark.pulltorefresh.library.PullToRefreshGridView
xmlns:ptr="http://schemas.android.com/apk/res-auto"
android:id="#+id/pull_refresh_grid"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="0dp"
android:horizontalSpacing="1dp"
android:columnWidth="80dp"
android:stretchMode="columnWidth"
android:gravity="fill"
ptr:ptrMode="both"
ptr:ptrDrawable="#drawable/default_ptr_rotate"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:indeterminateOnly="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
And here is the java code for the method onCreateView in FragmentPhotos (the line 55 is this one "ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,"):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ref = "";
fa = getActivity();
ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,
container, false);
bar = (ProgressBar) ll.findViewById(R.id.progressBar);
mPullRefreshGridView = (PullToRefreshGridView) ll
.findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener<GridView>() {
#Override
public void onRefresh(
PullToRefreshBase<GridView> refreshView) {
// TODO Auto-generated method stub
if (NetworkReceiver.mobileConnected) {
new GetDataTaskWhitoutLoading().execute();
} else {
Toast.makeText(
getActivity(),
"Ahora mismo no se pueden cargar nuevos datos."
+ " Comprueba la conexi—n a Internet.",
Toast.LENGTH_LONG).show();
mPullRefreshGridView.onRefreshComplete();
}
}
});
mGridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
// Do something in response to the click
Intent intent = new Intent(fa, ImageSelected.class);
intent.putExtra("URL_image", mListItems.get(position)
.subSequence(0, mListItems.get(position).length() - 6));
startActivity(intent);
}
});
mListItems = new ArrayList<String>();
mAdapter = new FotosItemAdapter(fa, R.layout.image_group, mListItems);
mGridView.setAdapter(mAdapter);
if (NetworkReceiver.mobileConnected) {
GetDataTask.newInstance(bar).execute();
}
return ll;
}
Thank you!!
Are you importing in your classhpath on eclipse?
Pull to refhresh is a lib for android,then import like this:
project properties> android> add lib.
In my case it solved by adding this to my project.properties :
target=android-19
android.library.reference.1=../library
that library is the name of the handmark library.
hope be useful.

Categories