Setting OnClickListener throws an exception? - java

I want to know why my application is throwing a runtime exception when I run it? I used to the code in the following link for my application,
dynamically add and remove view to viewpager.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ab=getActionBar();
pagerAdapter = new MainPagerAdapter();
pager = (ViewPager) findViewById (R.id.pager);
pager.setAdapter (pagerAdapter);
inflater = (LayoutInflater)getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
v0 = (FrameLayout) inflater.inflate (R.layout.listlayout, null);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(this);
pagerAdapter.addView (v0, 0);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button1)
{
pagerAdapter.addView (v0);
pagerAdapter.notifyDataSetChanged();
}
}
LogCat:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.todolistworkable/com.example.todolistworkable.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
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:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)Caused by: java.lang.NullPointerException
at com.example.todolistworkable.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)

the object on line 43 of your code within your onCreate method is null. Most likely the target of one of your findViewById calls is not returning what you expect it to.
See this for more info.
How to interpret Logcat

Related

Application not working on Android Kitkat

I'm creating my own application. I tested it on Android Lollipop and Marshmallow - everything works great. But whenever I try Android Kitkat, an error occurs. Here's error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newproject/com.example.newproject.Progi}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at com.example.newproject.Progi.onCreate(Progi.java:62)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
It looks like problem is on line 62 in "progi" class, but - as for me - everything is OK especially that on newer Android versions it works great.
public class Progi extends AppCompatActivity {
Intent intent;
Bundle liczby;
Bundle doble;
BigDecimal tablica [][];
BigDecimal punkty = new BigDecimal(-1);
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
android.content.SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
boolean warunek = shared.getBoolean("serial", false);
android.view.MenuItem menuitem = menu.getItem(0);
if(warunek)
{
menuitem.setTitle("Oceny pojedynczo");
}
else menuitem.setTitle("Oceny seryjnie");
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.firstmenu, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutprogi);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("Progi punktowe");
intent = getIntent();
liczby = intent.getBundleExtra("liczby");
doble = intent.getBundleExtra("doble");
tablica = (BigDecimal[][]) doble.getSerializable("doble"); //here is line 62
if(intent.hasExtra("max")) {
Bundle a = intent.getBundleExtra("max");
punkty = (BigDecimal) a.getSerializable("max");
}
przejscie(true);
if(punkty.compareTo(new BigDecimal(-3))==0)
{
procenty(findViewById(android.R.id.content));
}
else if(punkty.compareTo(new BigDecimal(-1))!=0)
{
liczymy(findViewById(android.R.id.content));
}}
And in case someone asking "what 'tablica' gets from intent?":
BigDecimal[][] tablica = new BigDecimal[16][3];
//here i get data from file and put in inside "tablica"
Bundle doble = new Bundle();
doble.putSerializable("doble", tablica);
Intent intent = new Intent(Starter.this, MyActivity.class);
intent.putExtra("doble", doble);
startActivity(intent);
Any idea what's wrong?
Try switching your array implementation (BigDecimal[] []) to ArrayList.
If you want to pass an Array through an intent on Android versions
prior to Android 5.0.1 (maybe some older versions work aswell, but up
to Android 4.3 it is NOT working) You'll have to work around it. You
could do this by converting your Array to an ArrayList.
Then you would be casting it something like this:
(ArrayList<ArrayList<BigDecimal>>) doble.getSerializable("doble");
Related SO answer

Android CursorAdapter giving java.lang.NullPointerException error

I am having a few issues running my custom CursorAdapter in my application. According to my logcat, the error I get:
11-08 06:41:03.228 6109-6109/? W/System.err? java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
11-08 06:41:03.229 6109-6109/? W/System.err? at com.app.name.MyActivity.onCreate(MyActivity.java:71)
11-08 06:41:03.231 6109-6109/? E/AndroidRuntime? FATAL EXCEPTION: main
occurs at line 71 which sets the adapter (obj.setAdapter(myAdapter)). Initially I thought my database data retrieve function (Cursor chatCursor = mydb.selectConversation(msgId);) did not return any data but after testing it with the chatCursor.getCount() function, I realized that was not the case. Kindly assist me in solving this issue. Below are the codes for my activity, adapter and logcat. Thanks in advance.
MyAdapter.java
public class MyAdapter extends CursorAdapter {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public MyAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.chat_left, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView user = (TextView) view.findViewById(R.id.reply_user);
TextView msg = (TextView) view.findViewById(R.id.reply_msg);
String theTime = cursor.getString(cursor.getColumnIndexOrThrow("message_id"));
String theMessage = cursor.getString(cursor.getColumnIndexOrThrow("message"));
user.setText(theTime);
msg.setText(String.valueOf(theMessage));
}
}
MyActivity.java
public class MyActivity extends ListActivity {
//Utils Class
Utils util;
final Context context = this;
private ProgressBar dialog;
ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
util = new Utils(this);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
final Integer msgId = extras.getInt("id");
obj = (ListView) findViewById(R.id.list);
Cursor chatCursor = mydb.selectConversation(msgId);
MyAdapter myAdapter = new MyAdapter(this, chatCursor);
obj.setAdapter(myAdapter);
}
}
logcat
11-08 06:41:03.228 6109-6109/? W/System.err? java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
11-08 06:41:03.229 6109-6109/? W/System.err? at com.app.name.MyActivity.onCreate(MyActivity.java:71)
11-08 06:41:03.231 6109-6109/? E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2351)
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.MyActivity.onCreate(MyActivity.java:71)
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)
11-08 06:41:03.238 559-832/? W/ActivityManager? Force finishing activity com.app.name/.MyActivity
11-08 06:41:03.742 559-574/? W/ActivityManager? Activity pause timeout for ActivityRecord{42e71938 u0 com.app.name/.MyActivity}
Take a look to your activity_view.xml. Probably the listview ID isn't "list" as you state when you try to find it with findViewById(R.layout.list).

TabHost NullPointerException using ActionBarSherlock

I’m using Sherlock library and I want to create a tab in my app but I’m getting a NullPointerException; what am I doing wrong?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bonsitesherlock/com.example.bonsitesherlock.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2077)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
at android.app.ActivityThread.access$600(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
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:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.widget.TabHost.addTab(TabHost.java:229)
at com.example.bonsitesherlock.MainActivity.addTab(MainActivity.java:49)
at com.example.bonsitesherlock.MainActivity.setTabs(MainActivity.java:32)
at com.example.bonsitesherlock.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:4479)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
... 11 more
This is my MainActivity:
public class MainActivity extends SherlockActivity {
private TabHost mTabHost;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
setTabs();
}
private void setTabs()
{
addTab("", R.drawable.tab_news, News.class);
addTab("", R.drawable.tab_servises, News.class);
addTab("", R.drawable.tab_profile, News.class);
}
private void addTab(String labelId, int drawableId, Class<?> c)
{
Intent intent = new Intent(getApplicationContext(), c);
TabHost.TabSpec spec = mTabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, mTabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
mTabHost.addTab(spec);
}
}

Refreshing ListView from Custom Adapter Class - Android

I want to refresh data in ListFragment from my custom adapter class, but got the error NullPointerException.
This is Adaper class method:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BasketFragment basketFragment = new BasketFragment();
basketFragment.getBsketList();
}
});
And when I call it in my Fragment class I get java.lang.NullPointerException at mDataBase = dbHelper.getWritableDatabase();
getBasketList():
public void refreshList() {
dbAdaper.setArrayMyData(selectAll());
dbAdaper.notifyDataSetChanged();
}
And here is the part where I got the error:
public ArrayList<BasketData> selectAll() {
Cursor mCursor = null;
dbHelper = new DBHelper(getActivity());
mDataBase = dbHelper.getWritableDatabase();//NullPointerException
mCursor = mDataBase.query("orderTable", null, null, null, null, null, null);
LogCat:
java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.epon.fragments.BasketFragment.selectAll(BasketFragment.java:100)
at com.epon.fragments.BasketFragment.getBsketList(BasketFragment.java:142)
at com.epon.adapters.DBBasketAdapter$2.onClick(DBBasketAdapter.java:177)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
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)
Have you set the context right?
Android: NullPointerException on getWritableDatabase()
NullPointerException on getWritableDatabase()
I think that his is your problem a problem.
Maybe if this is not helping posting the content of getActivity() might be helpful?
edit
Your logcat makes me keep thinking that its a context error!

Force Close After Implementation of Splash Screen w AsyncTask

I'm getting a force close issue after attempting to implement a splash screen into my app.
The issue occurs on line 76 lv.setAdapter(adapter); however I'm unsure as to why.
Any input is greatly appreciated.
09-19 15:20:53.687: E/AndroidRuntime(25177): FATAL EXCEPTION: main
09-19 15:20:53.687: E/AndroidRuntime(25177): java.lang.NullPointerException
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:76)
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:1)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.AsyncTask.finish(AsyncTask.java:631)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.os.Looper.loop(Looper.java:137)
09-19 15:20:53.687: E/AndroidRuntime(25177): at android.app.ActivityThread.main(ActivityThread.java:4931)
09-19 15:20:53.687: E/AndroidRuntime(25177): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 15:20:53.687: E/AndroidRuntime(25177): at java.lang.reflect.Method.invoke(Method.java:511)
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-19 15:20:53.687: E/AndroidRuntime(25177): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
09-19 15:20:53.687: E/AndroidRuntime(25177): at dalvik.system.NativeStart.main(Native Method)
SOURCE:
public class MainActivity extends Activity {
Context context;
ArrayList<String> aa = new ArrayList<String>();
ListView lv;
final String URL = "http://news.google.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(R.layout.splash);
lv= (ListView) findViewById(R.id.listView1);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
aa.add(element.text().toString());
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aa);
lv.setAdapter(adapter);
}
}
}
Not to beat a dead horse but lv is null since you changed the layout with setContentView(). Maybe I can explain a little better why this is because I'm not sure you quite understand how Views work in the Activity.
When you call setContentView() it inflates the xml layout file that you set in this function. Initializing any View that is not in that layout file will return null which will give a NPE when you try to set a method on it such as setAdapter().
It appears that you are under the assumption that you can still initialize the ListView which is in another layout file...you cannot. You can only use Views inflated with setContentView() or by inflating the layout file which holds that View and adding it to the currently inflated `layout.
One way around this is to call setContentView() again in onPostExecute() then initialize your ListView and set the Adapter. I wouldn't normally recommend calling setContentView() more than once in a single Activity but in your case it may be the easiest for what you currently have.
So it might look like this
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aa);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
Is there a View named R.id.listView1 in splash.xml? It looks like you changed your setContentView() call to the splash screen, but your listview is on a more "main" page.
lv is likely null here. Have you verified in the debugger that it is getting set correctly when you set it to (ListView) findViewById(R.id.listView1);?
Null Pointer Exception suggest that there might be problem with lv.
You have changed the name of xml.so verify whether R.id.listview1 is present in splash.xml

Categories

Resources