I have activity where Im viewing data in listView. But I have to fill data from another thread. As you can see in following code. On every data change I'm calling handler message which triggers notifyDataSetChanged(). When I'm updating data less than 1 change per second it works ok, but when Im changing data faster It throws IllegalStateException. Is there any chance to catch this exception?
Is there any more clear solution how to update data from another thread?
full code link: https://www.dropbox.com/s/nxyac1xd88g2y71/TestListThreadFill.zip
Activity:
public class MainActivity extends Activity {
private ListView list;
private TestAdapter adapter;
public static MainActivity magic;
/**
* Called when the activity is first created.
*/
#Override public void onCreate( Bundle savedInstanceState) {
magic = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById( R.id.list);
adapter = new TestAdapter( getApplicationContext());
new FillThread().execute((Object) null);
Data.getInstance().addHandler(this, new Handler(){
#Override public void dispatchMessage(Message msg) {
update();
super.dispatchMessage(msg);
}
});
}
public void update(){
adapter.notifyDataSetChanged();
}
#Override protected void onResume() {
list.setAdapter( adapter);
super.onResume();
}
}
Data continer:
public class Data extends Vector<DataItem> {
private static Data instance = null;
private HashMap< Object, Handler> handlerList;
public Data() {
handlerList = new HashMap< Object, Handler>();
}
public static Data getInstance(){
if( instance == null)
instance = new Data();
return instance;
}
#Override public synchronized boolean add( DataItem object) {
boolean result = super.add(object);
for( Map.Entry< Object, Handler> handler : handlerList.entrySet())
{
handler.getValue().sendEmptyMessage( 0);
}
return result;
}
public synchronized void addHandler( Object object, Handler handler){
handlerList.put( object, handler);
}
public synchronized void addHandler( Handler handler){
addHandler( handler, handler);
}
public synchronized void removeHandler( Object object){
handlerList.remove( object);
}
}
Data filler thread:
public class FillThread extends AsyncTask{
#Override protected Object doInBackground(Object... params) {
while( true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Data.getInstance().add( new DataItem( "L", "TOP", "BOTTOM"));
}
}
}
Logcat:
05-23 13:20:23.900 25260-25260/com.example.TestListThreadFill E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131034115, class android.widget.ListView) with Adapter(class com.example.TestListThreadFill.TestAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1549)
at android.widget.AbsListView.onLayout(AbsListView.java:2170)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2149)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1907)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4606)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
at android.view.Choreographer.doCallbacks(Choreographer.java:567)
at android.view.Choreographer.doFrame(Choreographer.java:536)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:4987)
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:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
05-23 13:20:30.923 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:30.923 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x4000016E, flags=0x0, dataLen=0x8
05-23 13:20:31.421 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:31.421 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x17, id=0x4000016F, flags=0x0, dataLen=0xC
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000170, flags=0x0, dataLen=0x8
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000171, flags=0x0, dataLen=0x8
It's pretty clear the error message :
Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.
You could try something like this :
public class FillThread extends AsyncTask<Void, Void, DataItem> {
#Override
protected DataItem doInBackground(Void... params) {
return new DataItem();
}
#Override
protected void onPostExecute(DataItem dataItem) {
// call an update method that adds the dataItem and notifies the adapter
}
}
Related
The following code is a part of my app and it isn't working and I don't know why.
I don't know at which place I can put the "new MormaKaugummi().execute();". At any place the App crashed and gave me the error "Unfortunately, Criminal Life has stopped."
The "counter textview" is in an another activity in the same app.
(The name of the App is Criminal Life).
I need a unique solution because I'm new in Android programming.
public class Morma extends AppCompatActivity {
class MormaKaugummi extends AsyncTask<String, String, String> {
private int count = 0;
private void count() {
count++;
}
private void update() {
TextView counter = (TextView) findViewById(R.id.counter);
String Kcounter = Integer.toString(count);
counter.setText(Kcounter);
}
#Override
protected String doInBackground(String... params) {
count();
update();
return null;
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
That's the logcat
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:32)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:15)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:35.514 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:35.674 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:37.364 622-1376/? I/Process: Sending signal. PID: 622 SIG: 9
You are trying to do findviewbyId and update the text view in your doInBackground method via the update function, which you cannot do.
As for the crash its happening because of a null pointer exception as you can read for yourself in the logcat's caused by clause it tells you the exact line number where the null pointer exception is thrown
Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
as you can see here, its caused by null pointer at line 26 in Morma.java and I am guessing that your TextView counter is null since you are trying to initialize a variable to reference a UI element from a non-UI thread, the counter variable will be initialized as null obviously.
Now for the solution:
What you need to do is put the update function in the onPostExecute method for the async task class. Reason: onPostExceute runs on whatever thread the asyntcTask.execute method was called from so you are supposed to do your UI update in the onPostExecute method
#Override
protected String doInBackground(String... params) {
count();
return null;
}
#Override
protect void onPostExecute(String result) {
update();
}
Also since you are returning null from doInBackground anyway you should Extend AsyncTask<String,String,Void> ideally.
EDIT 1:
Added code
public class Morma extends AppCompatActivity {
// make the text view class variable if you want to update it outside of onCreate.
private TextView mCounterTextView;
class MormaKaugummi extends AsyncTask<Void, Void, Void> {
private int count = 0;
private void count() {
count++;
}
private void update() {
String Kcounter = Integer.toString(count);
mCounterTextView.setText(Kcounter);
}
#Override
protected void doInBackground(Void... aVoid) {
count();
}
#Override
protected void onPostExecute(Void aVoid) {
update();
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
// initiate all your view items in onCreate.
mCounterTextView = (TextView) findViewById(R.id.counter);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
You need to initialize all your view elements like the textview in onCreate itself and keep the reference as a class variable if you are going to use that view outside of onCreate.
I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
I need to set Listener for Activity Class from BroadcastReceiver Class But here in my below code I am getting null pointer exception in BroadcastReceiver class..
Here is my code
Activity Class
public class MainActivity extends ActionBarActivity implements TheListener
{
Message_Incomingsms jv_class_Message_Incomingsms;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jv_class_Message_Incomingsms = new Message_Incomingsms();
jv_class_Message_Incomingsms.setSmsReceivedistener(this);
}
#Override
public void onSmsReceived(String jv_string_address, String jv_string_MessageText)
{
Toast.makeText(getApplicationContext(),"This Message is from Lister number is "+jv_string_address +" Message is "+jv_string_MessageText,Toast.LENGTH_LONG).show();
//Doing some Activity.....
}
}
Interface
public void setSmsReceivedistener(Context context)
{
this.jv_TheListener = (TheListener)context;
}
BroadCastReceiver Class
public class Message_Incomingsms extends BroadcastReceiver
{
String jv_string_phone_received_Number;
String jv_string_phone_received_messageText;
public TheListener jv_TheListener;
#Override
public void onReceive(Context context, Intent intent)
{
Log.d("Received","OnReceive method is called");
jv_smsmanager_incoming_sms = SmsManager.getDefault();
jv_bundle_incoming_sms = intent.getExtras();
if(jv_bundle_incoming_sms!=null)
{
Object[] jv_pdusObj_incoming_sms = (Object[]) jv_bundle_incoming_sms.get("pdus");
for(int jv_i = 0; jv_i < jv_pdusObj_incoming_sms.length ;jv_i++)
{
SmsMessage jv_current_message = SmsMessage.createFromPdu((byte[]) jv_pdusObj_incoming_sms[jv_i]);
jv_string_phone_received_Number =jv_current_message.getDisplayOriginatingAddress();
jv_string_phone_received_messageText = jv_current_message.getDisplayMessageBody();
}
//Here Below line is problem for me Always am getting null value for (jv_TheListener)
//Why value is not getting assigned for this (jv_TheListener) always
jv_TheListener.onSmsReceived(jv_string_phone_received_Number,jv_string_phone_received_messageText);
}
}
public void setSmsReceivedistener(Context context)
{
this.jv_TheListener = (TheListener)context;
}
}
Please provide me solution for above BroadCastClass code where am always getting null exception for (jv_TheListener)
log Cat ( I removed some lines for in code for not to confuse.. so dont refer linenumber based on below error)
04-18 23:45:12.268 4064-4064/com.talkeasy.elavarasans.creativeactionbar E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start receiver com.talkeasy.elavarasans.creativeactionbar.Message_Incomingsms: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2153)
at android.app.ActivityThread.access$1500(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
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:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.talkeasy.elavarasans.creativeactionbar.Message_Incomingsms.onReceive(Message_Incomingsms.java:53)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2146)
at android.app.ActivityThread.access$1500(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
Thanks in Advance...
Hey guys can you look at my errors, my logcat says it is because i am getting null pointer exception. i don't understand why. I just added a String variable which is "Email" and make the value of my eadd which stands for email address equals to it, then i have these errors now. can you point to me the problem guys?
These are my codes:
**
public class LoginSub extends Activity {
public static String Email;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputEmail;
EditText inputPassword;
TextView TextView1;
// url to create new product
//private static String url_create_product = "http://student-thesis.netii.net/log_in.php";
private static String url_create_product = "http://10.0.2.2/TheCalling/log_in.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Edit Text
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputPassword = (EditText) findViewById(R.id.inputPassword);
// Create button
Button btnLogin = (Button) findViewById(R.id.btnLogin);
// button click event
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new phpconnect().execute();
}
});
Button btnReg = (Button) findViewById(R.id.btnReg);
// button click event
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Register.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class phpconnect extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginSub.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String eadd = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eadd", eadd));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Email.equals(eadd);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
**
and here's my logcat errors:
**
03-06 22:21:16.428: E/AndroidRuntime(1417): FATAL EXCEPTION: AsyncTask #1
03-06 22:21:16.428: E/AndroidRuntime(1417): java.lang.RuntimeException: An error occured while executing doInBackground()
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.lang.Thread.run(Thread.java:856)
03-06 22:21:16.428: E/AndroidRuntime(1417): Caused by: java.lang.NullPointerException
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:129)
03-06 22:21:16.428: E/AndroidRuntime(1417): at com.example.projectthesis.LoginSub$phpconnect.doInBackground(LoginSub.java:1)
03-06 22:21:16.428: E/AndroidRuntime(1417): at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-06 22:21:16.428: E/AndroidRuntime(1417): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
**
Thank you guys.
Remove this block from doInBackGround()
if (success == 1) {
// successfully created product
Intent i = new Intent(LoginSub.this, Mapping.class);
startActivity(i);
// closing this screen
finish();
} else {
}
And add it in onPostExecute() section
protected void onPostExecute(String file_url)
{
// dismiss the dialog once done
pDialog.dismiss();
if (success == 1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), Mapping.class);
startActivity(i);
// closing this screen
finish();
}
else
{
}
}
Some times getApplicationContext() wont provide the exact context values. So pass the
Context context; //declare
context=this;// assigning next line after setcontextview.
then pass the context instead of getApplicationContext() . and check it and also if you want to do any UI updates you are not supposed to do in doinBackground(). You have to do in post execute.
Hope this will help you.
I think because this line
new phpconnect().execute();
and
class phpconnect extends AsyncTask<String, String, String> {
You declare AsyncTask with <String, String, String> but you didn't pass any parameter in .exeute();
Moreover that, from your code you don't want any parameter for AsyncTask so you should declare your Asynctask like this
class phpconnect extends AsyncTask<Void, Void, Void> {
I am creating an RSS reader application for android 4.0+. I have put the reader code in AsyncTask because of the NetworkOnMainThreadException. The code almost works fine, however one line has an error. This is my code:
Java code:
private class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url=params[0];
headlines = new ArrayList();
links = new ArrayList();
//Download and parse xml feed
headlines = new ArrayList();
links = new ArrayList();
try {
URL url1 = new URL("http://feeds.pcworld.com/pcworld/latestnews");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url1), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
* As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
* so we should skip the "<title>" tag which is a child of "<channel>" tag,
* and take in consideration only "<title>" tag which is a child of "<item>"
*
* In order to achieve this, we will make use of a boolean variable.
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Feed parsed!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
}
in this code snippet i get an error:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
Error: The constructor ArrayAdapter(MainActivity.PostTask, int, List) is undefined.
Logcat:
01-26 20:55:53.811: E/AndroidRuntime(1830): FATAL EXCEPTION: AsyncTask #1
01-26 20:55:53.811: E/AndroidRuntime(1830): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.lang.Thread.run(Thread.java:856)
01-26 20:55:53.811: E/AndroidRuntime(1830): Caused by: java.lang.IllegalArgumentException
01-26 20:55:53.811: E/AndroidRuntime(1830): at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1615)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:343)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:1)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-26 20:55:53.811: E/AndroidRuntime(1830): ... 5 more
Could anyone please look into my problem and come up with a solution? Or tell me if i should do anything different? Thanks a lot!
Change it to:
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, headlines);
this refers to the AsyncTask, so you have to explicitly reference MainActivity's this.
use Activity Context instead of AsyncTask to Create ArrayAdapter inside onPostExecute method as :
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(Your_Current_Activity.this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
EDIT :
after log posted also change
xpp.setInput(getInputStream(url1), "UTF_8");
to
xpp.setInput(url1.openConnection().getInputStream(), "UTF_8");