java.lang.NullPointerExeption before onCreate called for android app [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having a tremendous amount of trouble figuring out how and why I am getting a java.lang.NullPointerException. I have no idea what is going on because it seems to happen before my program loads. I've set a breakpoint at the first line of my onCreate function and my android log still shows that I have a this exception thrown but the program continues to start and I reach my breakpoint. But stepping through I get very weird behavior. I will post the code in question as well as the log. if any other info needed to help me with this please ask. Also please excuse the indention. I'm fairly new to stack overflow
package com.example.facta.myapplication;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by facta on 11/21/2014.
*/
public class SiteConfig {
private XmlResourceParser configParser;
ArrayList<RSSProviderInfo> RSSProviderInfos;
ArrayList<String> RSSProviderNames;
public SiteConfig()
{
RSSProviderInfos = new ArrayList<RSSProviderInfo>();
RSSProviderNames = new ArrayList<String>();
}
public ArrayList<RSSProviderInfo> getProvierInfos()
{
return RSSProviderInfos;
}
public ArrayList<String> getProvierNames()
{
return RSSProviderNames;
}
public void loadConfig(Context context, int resourceId)
{
configParser = context.getResources().getXml(resourceId);
RSSProviderInfos.clear();
RSSProviderInfo providerInfo = new RSSProviderInfo();
ArrayList<String> providerNames = loadProviders(configParser);
for(int i=0; i < providerNames.size(); i++)
{
providerInfo = LoadProviderInfo(configParser, providerNames.get(i));
if(providerInfo != null && providerInfo.isComplete()) {
RSSProviderInfos.add(providerInfo);
}
}
}
private RSSProviderInfo LoadProviderInfo(XmlResourceParser parser, String provider) {
RSSProviderInfo info = new RSSProviderInfo();
String attrName = new String();
try {
parser.next();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& parser.getName().equalsIgnoreCase("site" )) {
attrName = parser.getAttributeValue(null, "name");
if(attrName.equalsIgnoreCase(provider + ".enabled"))
{
/*
String value = parser.getAttributeValue(null, "value");
if(value.equalsIgnoreCase("no")) {
Log.d("LoadProviderInfo", "value does equal no");
return null; //If it's not enabled don't include it in the config
}
*/
}
else if(attrName.equalsIgnoreCase(provider + ".elementTag"))
{
info.setElementTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".titleTag"))
{
info.setTitleTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".linkTag"))
{
info.setLinkTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".descriptionTag"))
{
info.setDescriptionTag(parser.getAttributeValue(null,"value"));
}
else if(attrName.equalsIgnoreCase(provider + ".url"))
{
info.addUrl(parser.getAttributeValue(null, "value"));
}
break;
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
e.printStackTrace();
StackTraceElement st[] = e.getStackTrace();
for(int i=0; i < st.length; i++)
{
Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());
}
}
return null;
}
private ArrayList<String> loadProviders(XmlResourceParser parser) {
ArrayList<String> names = new ArrayList<String>();
try {
parser.next();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& parser.getName().equalsIgnoreCase("siteproviders")) {
String[] parsedNames = parser.getAttributeValue(null, "value").split(",");
for (int i=0; i < parsedNames.length; i++)
{
names.add(i, parsedNames[i]);
}
break;
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
e.printStackTrace();
StackTraceElement st[] = e.getStackTrace();
for(int i=0; i < st.length; i++)
{
Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());
}
}
return names;
}
}
Log Below
11-23 18:20:40.830 537-537/com.example.facta.myapplication D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
11-23 18:20:41.569 537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:41.580 537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.040 537-537/com.example.facta.myapplication D/loadProviders﹕ Caught an exeption: java.lang.NullPointerException
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ java.lang.NullPointerException
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadProviders(SiteConfig.java:119)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadConfig(SiteConfig.java:42)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.fetch(ResultsActivity.java:94)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.onCreate(ResultsActivity.java:62)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Activity.performCreate(Activity.java:4465)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
11-23 18:20:42.070 537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:42.080 537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.270 537-537/com.example.facta.myapplication D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
11-23 18:37:36.440 669-669/com.example.facta.myapplication W/ActivityThread﹕ Application com.example.facta.myapplication is waiting for the debugger on port 8100...
11-23 18:37:36.490 669-669/com.example.facta.myapplication I/System.out﹕ Sending WAIT chunk
11-23 18:37:36.701 669-675/com.example.facta.myapplication I/dalvikvm﹕ Debugger is active
11-23 18:37:36.740 669-669/com.example.facta.myapplication I/System.out﹕ Debugger has connected
11-23 18:37:36.740 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:36.900 669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:36.910 669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:37:36.940 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.140 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.680 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.880 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.079 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.279 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.369 669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:38.379 669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
Calling Activity Below
package com.example.facta.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.ArrayList;
/* TODO
Need to make a config file that has the following format.
site.names = CNN,FOX,NBC,AP
site.CNN.enabled = yes
site.CNN.searchtag = item
site.CNN.titletag = title
site.CNN.linktag = link
site.CNN.descriptiontag = description
site.CNN.numurls = 10
site.CNN.url.1 = "https://www.cnn.com/top_stories.rss
site.CNN.url.2 = "https://www.cnn.com/world_politics.rss
site.FOX.enabled = no
site.FOX.searchtag = story
*/
public class ResultsActivity extends Activity {
private ArrayList<String> finalUrls = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
finalUrls.add("http://rss.cnn.com/rss/cnn_topstories.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_world.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_us.rss");
finalUrls.add("http://rss.cnn.com/rss/money_latest.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_allpolitics.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_crime.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_tech.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_health.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_showbiz.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_travel.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_living.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_freevideo.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_studentnews.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_mostpopular.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_latest.rss");
finalUrls.add("http://rss.ireport.com/feeds/oncnn.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_behindthescenes.rss");
this.fetch();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_results, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fetch() {
/**TODO possibly load config then for each provider pass in RSSProviderInfo into HandleXML
That way HandleXML can set all the tags it needs and then parse the urls from the param
*/
SiteConfig siteConfig = new SiteConfig();
siteConfig.loadConfig(this, R.xml.sites);
ArrayList<RSSProviderInfo> siteConfigProvierInfos = siteConfig.getProvierInfos();
for (int k = 0; k < siteConfigProvierInfos.size(); k++) {
HandleXML obj = new HandleXML(siteConfigProvierInfos.get(k));
obj.fetchXML();
while (!obj.parsingComplete) {
try {
Thread.sleep(500, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
final ArrayList<RSSInfo> rssInfos = obj.getRssInfos();
final TableLayout tableLayout = (TableLayout) findViewById(R.id.results_table);
Log.d("fetch", "Size of rssinfos " + rssInfos.size());
for (int i = 0; i < rssInfos.size(); i++) {
final int index = i;
final TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
//Get information from infos
final TextView textView = new TextView(this);
textView.setText(rssInfos.get(index).getTitle());
textView.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tableRow.setClickable(true);
tableRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(rssInfos.get(index).getLink()));
startActivity(intent);
}
});
tableRow.addView(textView);
tableLayout.addView(tableRow);
}
Log.d("fetch", "tableLayout = " + tableLayout.toString());
}
}
}
}

Sorry for the confusion. I think I need to review Android Studio. That is an error from a previous version of my code (notice the date of yesterday 11-23). I thought "clear all" in logcat literally cleared all and delete it. I just found out I am wrong. There are no NPEs at this time that I am aware of. Sorry for the waste of time....lesson learned for me using android studio. After noticing this I was able to find the logical error that caused the program to exit shortly after. Thanks all for the help

Related

The api isApiSupported return true but SipManager newInstance still return null in Android native Sip

I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
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:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282) 
at android.app.ActivityThread.access$600(ActivityThread.java:147) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5265) 
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:760) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 
at dalvik.system.NativeStart.main(Native Method) 

Android Weather app crashing-network error

I have been developing a weather app through Treehouse and unfortunately no one has been able to help me fix this perticular error.
For some reason no weather data is retrieved on the app. I signed up through forecast IO to get the weather data to the app but nothing appears and the app crashes.
I use my phone as an emulator but I receive no errors in the log. Only when I use the Android Studio emulator do I receive an error in the logcat. Any suggestions ?
Stormy app on gitHub
Github
MainActivity.java file
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
#InjectView(R.id.humidityValue) TextView mHumidityValue;
#InjectView(R.id.precipValue) TextView mPrecipValue;
#InjectView(R.id.summaryLabel) TextView mSummaryLabel;
#InjectView(R.id.iconImageView) ImageView mIconImageView;
#InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
final double latitude = 38.627;
final double longitude = -90.199;
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "8ec5f1674002ab5081cad28e9be10ced";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if(isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
toggleRefresh();
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
updateDisplay();
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught:", e);
}
}
});
}
else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mRefreshImageView.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON:" + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getLong("time"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return new CurrentWeather();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
"PropertyFetcher: AdbCommandRejectedException getting properties for
device 0043d8b5c84ed1f5: device unauthorized.
Please check the confirmation dialog on your device."
Error log
02-10 14:17:31.130 52-52/? I/qemu-props﹕ received: qemu.hw.mainkeys=0
02-10 14:17:33.180 56-56/? I/SurfaceFlinger﹕ SurfaceFlinger's main thread ready to run. Initializing graphics H/W...
02-10 14:18:51.060 624-624/? D/AndroidRuntime﹕ Calling main entry com.android.commands.pm.Pm
02-10 14:19:01.630 548-548/com.android.launcher I/Choreographer﹕ Skipped 346 frames! The application may be doing too much work on its main thread.
02-10 14:19:02.750 437-437/? I/Choreographer﹕ Skipped 1210 frames! The application may be doing too much work on its main thread.
02-10 14:19:04.920 386-386/system_process W/BroadcastQueue﹕ Failure sending broadcast Intent { act=android.intent.action.TIME_TICK flg=0x50000014
(has extras) } android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1059)
at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:421)
at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:507)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:714)
at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:13807)
at android.content.BroadcastReceiver$PendingResult.sendFinished(BroadcastReceiver.java:419)
at android.content.BroadcastReceiver$PendingResult.finish(BroadcastReceiver.java:395)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:785)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at com.android.server.ServerThread.initAndLoop(SystemServer.java:1093)
at com.android.server.SystemServer.main(SystemServer.java:1179)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
02-10 14:19:08.800 386-386/system_process I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
02-10 14:19:19.860 548-548/com.android.launcher I/Choreographer﹕ Skipped 1089 frames! The application may be doing too much work on its main thread.
02-10 14:19:23.320 718-718/com.android.systemui I/Choreographer﹕ Skipped 679 frames! The application may be doing too much work on its main thread.
02-10 14:19:25.100 718-718/com.android.systemui I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-10 14:19:27.700 718-718/com.android.systemui I/Choreographer﹕ Skipped 154 frames! The application may be doing too much work on its main thread.
02-10 14:19:30.720 548-548/com.android.launcher I/Choreographer﹕ Skipped 61 frames! The application may be doing too much work on its main thread.
02-10 14:19:57.300 893-893/? D/AndroidRuntime﹕ Calling main entry com.android.commands.am.Am
02-10 14:19:57.400 386-398/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=aurielvilaire.com.stormy/.MainActivity} from pid 893
02-10 14:19:57.890 386-714/system_process I/ActivityManager﹕ Start proc aurielvilaire.com.stormy for activity aurielvilaire.com.stormy/.MainActivity: pid=928 uid=10054 gids={50054, 3003}
02-10 14:20:00.640 928-928/aurielvilaire.com.stormy D/MainActivity﹕ Main UI code is running!
02-10 14:20:02.170 386-400/system_process I/ActivityManager﹕ Displayed aurielvilaire.com.stormy/.MainActivity: +4s339ms
02-10 14:20:05.540 928-943/aurielvilaire.com.stormy D/MainActivity﹕ 1:20 PM
02-10 14:20:05.600 928-943/aurielvilaire.com.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: aurielvilaire.com.stormy, PID: 928 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at aurielvilaire.com.stormy.MainActivity.updateDisplay(MainActivity.java:154)
at aurielvilaire.com.stormy.MainActivity.access$500(MainActivity.java:31)
at aurielvilaire.com.stormy.MainActivity$2.onResponse(MainActivity.java:122)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
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:841)
02-10 14:20:05.650 386-397/system_process W/ActivityManager﹕ Force finishing activity aurielvilaire.com.stormy/.MainActivity
02-10 14:20:05.710 386-414/system_process W/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-10 14:20:05.710 386-414/system_process E/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
02-10 14:20:05.720 386-606/system_process W/InputDispatcher﹕ Attempted to unregister already unregistered input channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)'
02-10 14:20:05.720 386-606/system_process I/WindowState﹕ WIN DEATH: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:05.960 386-397/system_process I/WindowManager﹕ Screenshot max retries 4 of Token{b2051338 ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity t2 f}} appWin=Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity EXITING} drawState=4
02-10 14:20:07.260 548-548/com.android.launcher I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ This window was lost: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ mDisplayId=0 mSession=Session{b210e748 928:u0a10054}
mClient=android.os.BinderProxy#b2116298 mOwnerUid=10054
mShowToOwnerOnly=true package=aurielvilaire.com.stormy appop=NONE
mAttrs=WM.LayoutParams{(0,0)(fillxfill) sim=#120 ty=1 fl=#1810100
pfl=0x8 wanim=0x10302a1} Requested w=1080 h=1776 mLayoutSeq=71
mBaseLayer=21000 mSubLayer=0 mAnimLayer=21000+0=21000 mLastLayer=0
mToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mRootToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mAppToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mViewVisibility=0x0 mHaveFrame=true mObscured=true mSeq=0
mSystemUiVisibility=0x0 mPolicyVisibility=false
mPolicyVisibilityAfterAnim=false mAppOpVisibility=true
mAttachedHidden=false mGivenContentInsets=[0,0][0,0]
mGivenVisibleInsets=[0,0][0,0] mConfiguration={1.0 310mcc260mnc en_US
ldltr sw360dp w360dp h567dp 480dpi nrml port finger qwerty/v/v -nav/h
s.5} mHasSurface=true mShownFrame=[0.0,0.0][1080.0,1776.0]
isReadyForDisplay()=false mFrame=[0,0][1080,1776]
last=[0,0][1080,1776] mSystemDecorRect=[0,0][1080,1776]
last=[0,0][1080,1776] Frames: containing=[0,0][1080,1776]
parent=[0,0][1080,1776] display=[0,0][1080,1776]
overscan=[0,0][1080,1920] content=[0,75][1080,1776]
visible=[0,75][1080,1776] decor=[0,0][1080,1920] Cur insets:
overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0] Lst
insets: overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0]
WindowStateAnimator{b20db3d0
aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}:
mSurface=Surface(name=aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity)
mDrawState=HAS_DRAWN mLastHidden=true Surface: shown=false layer=21005
alpha=0.0 rect=(0.0,0.0) 1080.0 x 1776.0 mShownAlpha=1.0 mAlpha=1.0
mLastAlpha=-1.0 mGlobalScale=1.0 mDsDx=1.0 mDtDx=0.0 mDsDy=0.0
mDtDy=1.0 mExiting=false mRemoveOnExit=false mDestroying=true
mRemoved=false
02-10 14:20:52.610 386-606/system_process I/ActivityManager﹕ Start proc com.android.email for broadcast com.android.email/.service.EmailBroadcastReceiver: pid=1049 uid=10024 gids={50024, 3003, 1028, 1015}
02-10 14:20:53.400 1049-1063/com.android.email D/ActivityThread﹕ Loading provider com.android.email.provider;com.android.email.notifier: com.android.email.provider.EmailProvider
02-10 14:20:58.452 386-583/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.522 1049-1103/com.android.email I/Email﹕Observing account changes for notifications
02-10 14:20:58.622 386-432/system_process I/ActivityManager﹕ Start proc com.android.exchange for service com.android.exchange/.service.EmailSyncAdapterService: pid=1104 uid=10025 gids={50025, 3003, 1028, 1015}
02-10 14:20:58.622 386-607/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.882 1049-1065/com.android.email D/dalvikvm﹕ GC_FOR_ALLOC freed 313K, 16% free 3359K/3960K, paused 231ms, total 254ms
02-10 14:21:49.352 718-718/com.android.systemui I/Choreographer﹕ Skipped 32 frames! The application may be doing too much work on its main thread.
After reading through that and looking at your code, I believe the main culprit here is that you are doing to much on the main thread. You should use the android AsyncTask to run especially network connections on a separate thread. For example you might use:
private class DownloadForecast extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
getForecast(); //run all your network intensive methods
return response;
}
#Override
protected void onPostExecute(String result) {
//update all your UI stuff.
}
Can't seem to correctly intent the code. But thats what you should use. Good luck.

Debugging AsyncTask - strange behaviour, debug jumping into the code

I'm debugging an Asynctask that simply downloads a file: here the code:
public class AsyncDownloadFilesTask extends AsyncTask<String, Integer, Boolean> {
public AsyncResponse<Boolean> delegate=null;
protected Boolean doInBackground(String... params) {
android.os.Debug.waitForDebugger();
try {
URL url = new URL(params[0]);
int count;
String fileName = new String(params[1]);
URLConnection connessione = url.openConnection();
connessione.connect();
int lenghtOfFile = connessione.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileName);
long total = 0;
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return Boolean.valueOf(true);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Boolean result) {
delegate.processFinish(result);
}
}
I obtain a strange behaviour: when execution arrive to return
Boolean.valueOf(true);
it skips to
return null;
into the catch block, but Exception e is null, and then debugger goto line 1 of AsyncTask, that is simply
package com.example.compa.asynctasks;
Then execution goes on (executing onPostExecute method) and, of course, returned result is null
What happens? Why debug jump in this way?
Task download correctly the file.
Here code of the Activity that instantiates and calls Async Task
package com.example.compa.activities;
import android.app.Activity;
import ...
public class CoverActivity extends Activity implements AsyncResponse<Boolean>{
ImageView coverImg;
Drawable d;
CompassesFileManager cfm;
int coverId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cover);
coverId = getIntent().getExtras().getInt("coverId");
cfm = new CompassesFileManager(this);
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
d = cfm.getCover(coverId);
if (d!=null){
coverImg.setImageDrawable(d);
} else {
AsyncDownloadFilesTask task = new AsyncDownloadFilesTask();
task.delegate = this;
task.execute(cfm.getCoverURL(coverId), cfm.getCoverFileName(coverId));
}
}
#Override
public void processFinish(Boolean output) {
if (output){
Drawable d = cfm.getCover(coverId);
coverImg.setImageDrawable(d);
} else {
finish();
}
}
}
Stacktrace of error:
02-21 19:37:29.520: E/AndroidRuntime(407): FATAL EXCEPTION: main
02-21 19:37:29.520: E/AndroidRuntime(407): java.lang.NullPointerException
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:1)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Looper.loop(Looper.java:176)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-21 19:37:29.520: E/AndroidRuntime(407): at dalvik.system.NativeStart.main(Native Method)
line:
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
is the last one of AsyncDownloadFilesTask class, and is a closing bracket, }
Thank you
I don't have enough points to comment, but it looks like delegate is null in your onPostExecute
delegate.processFinish(result); // delegate is null
if that's not the case, you're code stub above doesn't define it though.
I solved on my own.
1st, I move call to the Async Task in the onStart() method, instead of onCreate()
2nd, I made a mistake, in change line
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
in
coverImg = (ImageView)findViewById(R.id.cover_image);
to avoid a stupid null pointer (I already declared coverImg)!
Anyway, I still don't understand debug's behaviour, but I solved my problem.
Thank you everybody

Cursor is Null in Service Class - But Returns Value in Standalone Activity Class

My classmates and I are stuck on an issue with android application we are building.
We've successfully built an Android app which contains an activity which searches our browser histories / bookmarks for specific urls and launches another activity (successfully) if a match is found as an example of an adult content warning implementation.
This is functioning fine.
Now we are implementing a service class to continually execute every few seconds - in order to execute the search of our recent history using our new service class - but we're experiencing a few issues.
Our problem is when we attempt to add the "Nanny" source code from Nanny.java to the service class so the "Nanny" script will search the history continuously, instead of just once - the "Nanny" application continually force closes - due to a null pointer exception at the initialization of our cursor: if (cursor.moveToFirst()) {
Which is a bit strange because the NullPointerException does not occur when the exact same script is executed outside the service class in a test file we have (Main.java)
Our working Main.java and our working service class [which successfully displays a toast every few seconds] as well as our [failed] combination of the two - are shown below:
Empty Service Class:
public class Service_class extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
Working Nanny.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
public class Nanny extends Activity {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nanny);
TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
//if (url.toLowerCase().contains(Filthy)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent intent = new Intent(Nanny.this, Warning.class);
Nanny.this.startActivity(intent);
}
} while (cursor.moveToNext());
tv.setText(urls);
}}}
Unsuccessful method we've attempted to implement (adding the functioning nanny script to the service class) which causes the NullPointerException: if (cursor.moveToFirst()) {
public class Service_class extends Service {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//setContentView(R.layout.main3);
// TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent warning_intent = new Intent(Service_class.this, Warning.class);
Service_class.this.startActivity(intent);
}
} while (cursor.moveToNext());
// tv.setText(urls);
return START_STICKY;
}
return startId;}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
private void setContentView(int main3) {
// TODO Auto-generated method stub
}
private TextView findViewById(int hello) {
// TODO Auto-generated method stub
return null;
}
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
LOGCAT (When using combined implementation shown above)
Fails on Line 53: if (cursor.moveToFirst()) {
04-15 18:26:24.761: D/dalvikvm(7466): Late-enabling CheckJNI
04-15 18:26:25.651: D/dalvikvm(7466): GC_FOR_ALLOC freed 82K, 4% free 7379K/7608K, paused 13ms, total 13ms
04-15 18:26:25.651: I/dalvikvm-heap(7466): Grow heap (frag case) to 10.861MB for 3686416-byte allocation
04-15 18:26:25.661: D/dalvikvm(7466): GC_FOR_ALLOC freed 1K, 3% free 10977K/11212K, paused 13ms, total 13ms
04-15 18:26:25.681: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 3% free 10977K/11212K, paused 3ms+2ms, total 17ms
04-15 18:26:25.901: D/dalvikvm(7466): GC_FOR_ALLOC freed <1K, 3% free 10977K/11212K, paused 11ms, total 11ms
04-15 18:26:25.911: I/dalvikvm-heap(7466): Grow heap (frag case) to 17.086MB for 6529744-byte allocation
04-15 18:26:25.931: D/dalvikvm(7466): GC_FOR_ALLOC freed 0K, 2% free 17354K/17592K, paused 13ms, total 13ms
04-15 18:26:25.941: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 2% free 17354K/17592K, paused 3ms+2ms, total 16ms
04-15 18:26:26.051: D/libEGL(7466): loaded /system/lib/egl/libEGL_tegra.so
04-15 18:26:26.061: D/libEGL(7466): loaded /system/lib/egl/libGLESv1_CM_tegra.so
04-15 18:26:26.071: D/libEGL(7466): loaded /system/lib/egl/libGLESv2_tegra.so
04-15 18:26:26.091: D/OpenGLRenderer(7466): Enabling debug mode 0
04-15 18:26:31.181: D/AndroidRuntime(7466): Shutting down VM
04-15 18:26:31.181: W/dalvikvm(7466): threadid=1: thread exiting with uncaught exception (group=0x40f4f930)
04-15 18:26:31.181: E/AndroidRuntime(7466): FATAL EXCEPTION: main
04-15 18:26:31.181: E/AndroidRuntime(7466): java.lang.RuntimeException: Unable to start service com.ut.appdemo.Service_class#41698e90 with Intent { cmp=com.ut.appdemo/.Service_class }: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2673)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.access$1900(ActivityThread.java:141)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Looper.loop(Looper.java:137)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invoke(Method.java:511)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 18:26:31.181: E/AndroidRuntime(7466): at dalvik.system.NativeStart.main(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): Caused by: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.ut.appdemo.Service_class.onStartCommand(Service_class.java:53)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2656)
04-15 18:26:31.181: E/AndroidRuntime(7466): ... 10 more
You are setting the cursor to null...
you use this method to instantiate the cursor:
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,projection, null, null, null);
and then you define managedQuery() method like this:
private Cursor managedQuery(Uri bookmarksUri, String[] projection, Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
essentially what your code says is:
Cursor cursor = null;
curser.doSomething();
this will always result in a nullPointer. I strongly suggest you go back and study java fundamentals before diving in to android, you are just asking for headaches if you are trying to accomplish something in android with such a lack of understanding of java.

Android music player prepare method failed

I have been trying to play an MP3 file. It just won't work.
I did manage to play it and add all sorts of functionalities to it with the very same/similar code a few days ago. Just tried to make it all over again and now these errors...
Can someone point out the error also why does this happen.
Just to clarify I used different formats of URI, none of them work. Thought maybe its the prepare method.
package com.player.phoneagent.gui;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class AndroidClientActivity extends Activity {
/** Called when the activity is first created. */
private MediaPlayer mp;
String path = "android.resource://com.player.phoneagent/raw/test";
ImageButton btn_prev;
ImageButton btn_play;
ImageButton btn_pause;
ImageButton btn_next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_prev = (ImageButton) findViewById(R.id.ImageButton01);
btn_pause = (ImageButton) findViewById(R.id.ImageButton02);
btn_play = (ImageButton) findViewById(R.id.ImageButton03);
btn_next = (ImageButton) findViewById(R.id.ImageButton04);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mp.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
});
}
}
08-01 07:06:00.142: W/KeyCharacterMap(407): No keyboard for id 0
08-01 07:06:00.142: W/KeyCharacterMap(407): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
08-01 07:06:05.821: D/dalvikvm(407): GC_EXPLICIT freed 21K, 53% free 2568K/5379K, external 3207K/3962K, paused 55ms
08-01 07:06:20.311: D/dalvikvm(444): GC_EXTERNAL_ALLOC freed 52K, 53% free 2552K/5379K, external 1969K/2137K, paused 58ms
08-01 07:06:43.171: E/MediaPlayer(444): error (1, -2147483648)
08-01 07:06:43.171: W/System.err(444): java.io.IOException: Prepare failed.: status=0x1
08-01 07:06:43.171: W/System.err(444): at android.media.MediaPlayer.prepare(Native Method)
08-01 07:06:43.171: W/System.err(444): at com.player.phoneagent.gui.AndroidClientActivity$1.onClick(AndroidClientActivity.java:60)
08-01 07:06:43.171: W/System.err(444): at android.view.View.performClick(View.java:2485)
08-01 07:06:43.171: W/System.err(444): at android.view.View$PerformClick.run(View.java:9080)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.handleCallback(Handler.java:587)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 07:06:43.181: W/System.err(444): at android.os.Looper.loop(Looper.java:123)
08-01 07:06:43.181: W/System.err(444): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invoke(Method.java:507)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 07:06:43.181: W/System.err(444): at dalvik.system.NativeStart.main(Native Method)
08-01 07:06:43.181: E/MediaPlayer(444): start called in state 0
08-01 07:06:43.181: E/MediaPlayer(444): error (-38, 0)
08-01 07:06:43.181: E/MediaPlayer(444): Error (-38,0)
I always had problems trying to use "raw" folder... I suggest putting the sound file in "assets" and using the methods here to set / prepare / and play:
http://droidapp.co.uk/2011/06/08/android-dev-playing-a-mp3-from-assets/
Just do something like:
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
mp.start();
//Other stuff below.
See if that works.

Categories