Force Close After Implementation of Splash Screen w AsyncTask - java

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

Related

NPE while using simple list item 2 in android

I am trying to put the values of two columns created in the database to two text views of simple list item 2 using simple cursor adapter but I am getting NPE.
Please help.
Regards
My code is:
class NotesList extends ListActivity{
private DataSource datasource;
ArrayAdapter<Message> adapter;
Cursor cursors = null;
private SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
datasource = new DataSource(this);
datasource.open();
// List<Message> values = datasource.getAllMessages();
// adapter = new ArrayAdapter<Message>(this, android.R.layout.simple_list_item_1, values);
// setListAdapter(adapter);
String queryz = "SELECT " + MySQLiteHelper.COLUMN_ID + "," + MySQLiteHelper.COLUMN_MESSAGE+ " FROM " + MySQLiteHelper.TABLE_NAME ;
cursors = database.rawQuery(queryz, null);
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
cursors, // Pass in the cursor to bind to.
new String[] {MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_MESSAGE}, // Array of cursor columns to bind to.
new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
setListAdapter(adapter);
}
#Override
public void onResume() {
datasource.open();
super.onResume();
}
#Override
public void onPause() {
datasource.close();
super.onPause();
}
Datasource and Mysqlitehelper are the names of my classes.MySqliteHelper class creates the two columns of id and notes.
Logcat is:
03-19 01:15:32.557: E/AndroidRuntime(10579): FATAL EXCEPTION: main
03-19 01:15:32.557: E/AndroidRuntime(10579): java.lang.RuntimeException: Unable to start activity ComponentInfo{soft.b.notes/soft.b.notes.NotesList}: java.lang.NullPointerException
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.access$600(ActivityThread.java:122)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.os.Looper.loop(Looper.java:137)
03-19 01:15:32.557: E/AndroidRuntime(10579): at android.app.ActivityThread.main(ActivityThread.java:4340)
Your database is not initialized.
Also, it's useful to examine the full stack trace. There's a "caused by" exception nested in the RuntimeException. Double-clicking a stacktrace row in your IDE would show exactly the line of code where the problem occurs.
You're running a rawQuery on a database that's null. I don't see anywhere that you actually get a SQLiteDatabase for your database variable.

Setting OnClickListener throws an exception?

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

IllegalStateException while using Tables in android

When I execute the following code I get an IllegalStateException..
public class DatabaseView extends Activity{
TextView tv;
MySQLiteHelper h;
TableLayout main;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newview);
h=new MySQLiteHelper(this);
main=(TableLayout) findViewById(R.id.tb1);
table();
}
private void table() {
// TODO Auto-generated method stub
TableRow header_row=new TableRow(this);
header_row.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
TextView item=new TextView(this);
item.setText("Item");
header_row.addView(item);
TextView amt=new TextView(this);
amt.setText("Amount");
header_row.addView(amt);
main.addView(header_row, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
Cursor c=h.getAllEntry();
c.moveToFirst();
do
{
TableRow tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
TextView tv=new TextView(this);
Log.d(" ", c.getString(2));
tv.setText(c.getString(2));
tr.addView(item);
TextView amnt=new TextView(this);
Log.d(" ", c.getString(1));
amnt.setText(c.getString(1));
tr.addView(amt);
tr.addView(tv);
tr.addView(amnt);
main.addView(tr,new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
c.moveToNext();
}while(!c.isAfterLast());
}
The error log is--
AndroidRuntime(1692):FATAL EXCEPTION: main
AndroidRuntime(1692): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.expensesdatabase/com.example.expensesdatabase.DatabaseView}: >java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
AndroidRuntime(1692):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
AndroidRuntime(1692):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
AndroidRuntime(1692):at android.app.ActivityThread.access$600(ActivityThread.java:141)
AndroidRuntime(1692):at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
AndroidRuntime(1692):at android.os.Handler.dispatchMessage(Handler.java:99)
AndroidRuntime(1692):at android.os.Looper.loop(Looper.java:137)
AndroidRuntime(1692):at android.app.ActivityThread.main(ActivityThread.java:5103)
AndroidRuntime(1692):at java.lang.reflect.Method.invokeNative(Native Method)
AndroidRuntime(1692):at java.lang.reflect.Method.invoke(Method.java:525)
Please tell why this error is occurring and solution to the same.Thanks in advance.
In the do-while loop, you're re-adding item and amt views that you've already added to a parent.
Errors like this are easy to diagnose when you look at the logcat, below the part you've posted. There's a "caused by" exception below it that points you to the exact line of code.

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!

nullPointerException at getWritableDatabase()

New to Android here. I've made a new Fragments app, and I'm having trouble accessing the database from the Fragment.
Here's the class:
public class ShopListActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoplist);
db = new DatabaseHelper(this); // tried getApplicationContext(), and getBaseContext() as well
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public void onClickAddProduct(View view) {
TextView productName = (TextView) findViewById(R.id.add_product_text);
SQLiteDatabase dbWritable = db.getWritableDatabase(); // <-- crashes here
ContentValues values = new ContentValues();
values.put("Name", (String) productName.getText());
dbWritable.insert("Lists", "Name", values);
}
All the other solutions I found on SO didn't help.
DatabaseHelper is a very basic DB Helper class:
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_TABLES);
db.execSQL("INSERT INTO Lists (Name) VALUES('Test')");
}
Here's the Logcat:
07-07 21:03:24.351 9641-9641/com.chas.shopforme E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3606)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17362)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3601)
... 11 more
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.chas.shopforme.ShopListActivity.onClickAddProduct(ShopListActivity.java:69)
... 14 more
Note: I know there are more questions like this, but their solutions didn't work for me.
try this
db = new DatabaseHelper(this.getApplicationContext());
I tried adding this as a comment to your question, but nasty things happen to code in comments.
Assuming you've tried a) in the comment above, and it didn't work, an example of b) follows:
protected void onCreate(Bundle savedInstanceState) {
...
Handler hand = new Handler();
hand.post(new Runnable() {
public void run() {
dbInit();
}
});
}
public void dbInit() {
db = new DatabaseHelper(this);
}
This allows the fragment manager to finish setting up the fragment before you try to use it. What it is doing is sending a message to itself which is processed when the fragment's message handler loop is running.

Categories

Resources