AsyncTask with progressbar - java

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.

Related

My android app crashes when a user logs in to facebook

I hope someone can help me.
I have an android app that has a standard login but also has twitter and facebook login buttons.
When the user try's to login using the facebook button the app crashes and I am unsure as to why? I believe that it is because the email field is returning as null.
I have rebuilt the app numerous times, the app is public on facebook, the app id is correct as is the package name.
logcat is below
09-03 15:15:45.971 16896-17259/com.projects.bmxtrackfinder W/chromium﹕ [WARNING:keycode_converter.cc(91)] empty code string
09-03 15:15:47.470 16896-17259/com.projects.bmxtrackfinder W/chromium﹕ [WARNING:keycode_converter.cc(91)] empty code string
09-03 15:15:48.128 16896-17259/com.projects.bmxtrackfinder W/chromium﹕ [WARNING:keycode_converter.cc(91)] empty code string
09-03 15:15:52.942 16896-16896/com.projects.bmxtrackfinder W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 16896
09-03 15:16:04.690 16896-16896/com.projects.bmxtrackfinder W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 16896
09-03 15:16:04.821 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:04.821 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:04.828 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:04.829 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:05.094 16896-16896/com.projects.bmxtrackfinder E/FACEBOOK USERNAME**﹕ John TrackFinder
09-03 15:16:05.095 16896-16896/com.projects.bmxtrackfinder E/FACEBOOK ID**﹕ 135514753461349
09-03 15:16:05.096 16896-16896/com.projects.bmxtrackfinder E/FACEBOOK EMAIL**﹕ null
09-03 15:16:05.124 16896-17668/com.projects.bmxtrackfinder E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #4
Process: com.projects.bmxtrackfinder, PID: 16896
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.fragments.activity.LoginActivity$2.onAsyncTaskDoInBackground(LoginActivity.java:263)
at com.asynctask.MGAsyncTask.doInBackground(MGAsyncTask.java:45)
at com.asynctask.MGAsyncTask.doInBackground(MGAsyncTask.java:10)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-03 15:16:05.667 16896-16896/com.projects.bmxtrackfinder E/WindowManager﹕ android.view.WindowLeaked: Activity com.fragments.activity.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2f585567 V.E..... R.....ID 0,0-729,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:99)
at com.asynctask.MGAsyncTask.onPreExecute(MGAsyncTask.java:60)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
at android.os.AsyncTask.execute(AsyncTask.java:539)
at com.fragments.activity.LoginActivity.syncFacebookUser(LoginActivity.java:274)
at com.fragments.activity.LoginActivity$4.onCompleted(LoginActivity.java:423)
at com.facebook.Request$1.onCompleted(Request.java:303)
at com.facebook.Request$4.run(Request.java:1726)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-03 15:16:12.839 16896-16908/com.projects.bmxtrackfinder W/art﹕ Suspending all threads took: 11.292ms
(LoginActivity.java:263) = String email = user.asMap().get("email").toString;
Asynch code below:
package com.asynctask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import com.projects.bmxtrackfinder.R;
import com.utilities.MGUtilities;
public class MGAsyncTask extends AsyncTask<Void, Void, String> {
public ProgressDialog dialog;
public Activity activity;
public Object object;
public int tag = 0;
public int listTag = 0;
OnMGAsyncTaskListener mCallback;
public interface OnMGAsyncTaskListener {
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask);
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask);
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask);
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask);
}
public void setMGAsyncTaskListener(OnMGAsyncTaskListener listener) {
try {
mCallback = (OnMGAsyncTaskListener) listener;
} catch (ClassCastException e) {
throw new ClassCastException(this.toString() + "Did not implement OnMGAsyncTaskListener");
}
}
public MGAsyncTask(Activity activity) {
this.activity = activity;
}
public void startAsyncTask() {
this.execute();
}
#Override
protected String doInBackground(Void... params) {
mCallback.onAsyncTaskDoInBackground(this);
return "";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation. parse json data
dialog.dismiss();
mCallback.onAsyncTaskPostExecute(this);
}
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For example showing ProgessDialog
String loading = MGUtilities.getStringFromResource(activity, R.string.loading);
dialog = ProgressDialog.show(activity, "", loading, true);
mCallback.onAsyncTaskPreExecute(this);
}
#Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
mCallback.onAsyncTaskProgressUpdate(this);
}
public void setMessage(String message) {
dialog.setMessage(message);
}
public void setTitle(String title) {
dialog.setTitle(title);
}
public void setIcon(int resId) {
dialog.setIcon(resId);
}
}

ASyncTask with progressdialog and button

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);
}

App force closes when I try to implement an EditText search in a Listview

I am new to android. I have created an app which was a pull parser in order to extract items from an Rss feed, into a ListView. Unfortunately my app seems to force close when I try and place code in order implement some sort of filtering mechanism in my ListView. This is the code I have so far, and I have no idea why it seems to crash. Any help would be appreciated.
public class RssFeed extends ListActivity {
// Listview Adapter
ArrayAdapter<string> adapter;
EditText SearchBox;
List titles;
public static List description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss);
// Initialising instance variables
titles = new ArrayList();
description = new ArrayList();
try {
URL url = new URL("http://my.url");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
/** While the rss feed has not displayed end_document, pull the title and description information */
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)
titles.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
description.add(xpp.nextText());
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
SearchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
RssFeed.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
And the LogCat:
04-12 20:43:00.792: D/dalvikvm(324): GC freed 7597 objects / 316440 bytes in 88ms
04-12 20:43:00.852: D/AndroidRuntime(324): Shutting down VM
04-12 20:43:00.852: W/dalvikvm(324): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-12 20:43:00.852: E/AndroidRuntime(324): Uncaught handler: thread main exiting due to uncaught exception
04-12 20:43:00.862: E/AndroidRuntime(324): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff.simpleRssReader/org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed}: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Looper.loop(Looper.java:123)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invoke(Method.java:521)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-12 20:43:00.862: E/AndroidRuntime(324): at dalvik.system.NativeStart.main(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): Caused by: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed.onCreate(RssFeed.java:142)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-12 20:43:00.862: E/AndroidRuntime(324): ... 11 more
04-12 20:43:00.892: I/dalvikvm(324): threadid=7: reacting to signal 3
04-12 20:43:00.892: E/dalvikvm(324): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
First of all: the class you posted doesn't have 142 lines, be sure to post the whole class.
Second: SearchBox is null here.
That is because you declared it with
EditText SearchBox;
but never assigned it which you would usually do from your layout like
SearchBox = (EditText) findViewById(R.id.searchBox);
(just an example)
SeachBox does not have an assigned value at this point so you can't use any methods on it.
Third: Use lower case names like searchBox, it'll make your code easier to read for others and yourself.

Create Dialog Box For Checking Internet Connection in Android

I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.

MediaController - Error when Show() called

I have this code for show the MediaController, but it give me a fatal error when I'm calling to Show() method.
The MediaPlayer itself working on Service and get Intent from the MediaPlayerControl interface.
My code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaController = new MediaController(this, false);
mediaController.setMediaPlayer(mediaPlayerControl);
mediaController.setAnchorView(findViewById(R.id.mediaController));
mediaController.setEnabled(true);
mediaController.show(0);
}
//implements MediaPlayerControl interface
private MediaPlayerControl mediaPlayerControl = new MediaPlayerControl()
{
//Override the methods to send Intent to the MediaPlayer Service
....
....
};
my logcat:
07-27 11:03:07.365: E/AndroidRuntime(328): FATAL EXCEPTION: main
07-27 11:03:07.365: E/AndroidRuntime(328): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.radius100fm/com.example.radius100fm.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.os.Looper.loop(Looper.java:123)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-27 11:03:07.365: E/AndroidRuntime(328): at java.lang.reflect.Method.invokeNative(Native Method)
07-27 11:03:07.365: E/AndroidRuntime(328): at java.lang.reflect.Method.invoke(Method.java:507)
07-27 11:03:07.365: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-27 11:03:07.365: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-27 11:03:07.365: E/AndroidRuntime(328): at dalvik.system.NativeStart.main(Native Method)
07-27 11:03:07.365: E/AndroidRuntime(328): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.ViewRoot.setView(ViewRoot.java:527)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.view.Window$LocalWindowManager.addView(Window.java:424)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.widget.MediaController.show(MediaController.java:304)
07-27 11:03:07.365: E/AndroidRuntime(328): at com.example.radius100fm.MainActivity.onCreate(MainActivity.java:100)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-27 11:03:07.365: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-27 11:03:07.365: E/AndroidRuntime(328): ... 11 more
What is the problem with my code?
Use this method.
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(mediaController != null)
mediaController.show(0);
}
I got the same problem and after several hours got the solution. I did the following:
Summary:
The Activity class implements the interfaces: MediaPlayer.OnPreparedListener and MediaController.MediaPlayerControl
OnCreate. setContentView.
onStart. Create MediaPlayer and MediaController, start the listener with setOnPreparedListener and call prepare() method of MediaPlayer.
Implement method onPrepared. Link the mediaController with the mediaPlayer, start mediaPlayer and here is where the method show() is called using a handler, only when we know that mediaPlayer is ready.
My code:
public class MainActivity extends Activity implements MediaPlayer.OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
Log.d(TAG, "Play - onStart");
super.onStart();
mediaPlayer = new MediaPlayer();
mediaController = new MediaController(this);
mediaPlayer.setOnPreparedListener(this);
try {
AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(R.raw.audio_example);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
afd.close();
} catch (IOException e) {
Log.e(TAG, "Error opening audio: " + e.getCause());
}
}
// override this method because of the OnPreparedListener interface
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "Play - onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.mediaController1));
mediaPlayer.start();
handler.post(new Runnable() {
#Override
public void run() {
mediaController.setEnabled(true);
mediaController.show(0);
}
});
}
// override these methods because of the MediaController.MediaPlayerControl interface
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public void start() {
mediaPlayer.start();
}
// release resources before kill the Activity
#Override
protected void onStop() {
Log.d(TAG, "Play - onStop");
super.onStop();
if (mediaPlayer != null) {
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
} }
Ok, so finely I found the answer.
The problem is in the line:
mediaController.show(0);
Because it called in onCreate() and the app still not activated.
Simple tried, add bottom that callingmediaController.show(0); when it clicked, and the app work perfect.
So now I have to call this line after the app get activate.
I'm tried onStart() and onResume() and it not working. The same error logCat.
How can I fix that??
I needed to show the MediaController to a already running MediaPlayer, so I couldn't set the OnPreparedListener like e_v_e said.
With the answer to this question: Can't fix MediaController.show() exception I discovered that the show method is been called before all the activity lifecycle methods were called. The solution proposed there(setting a delay to show) works, but to avoid the delay, you can place the show inside the onAttachedToWindow method, that is called after all the activity lifecycle methods.
Just put the mediaPlayer.prepare() and mediaPlayer.start() in a thread like handler or AsyncTask and done.
If you are using kotlin and anko lib, you can put it in doAsync {}.

Categories