I have a BroadcastReceiver that receives an SMS and then is supposed to immediately send a reply SMS if the text has certain characters. Now it receives and sends the SMSs but it soon forces close giving something like: Unable to start receiver... NullPointerException... ActivityThread.handleReciever (paraphrasing) in the LogCat...what might be the issue? Here's my code, you're looking for the ELSE IF statement(that's the part that I'm currently testing):
public class Service extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction()
.equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msgFrom;
if (bundle != null) {
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
String verificationCode = "717345221";
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgFrom = msgs[i].getOriginatingAddress();
String encodeHash = Uri.encode("#");
msgFrom = "0" + msgFrom.substring(4) + encodeHash;
String msgBody = msgs[i].getMessageBody();
if (msgBody.startsWith(verificationCode)) {
this.abortBroadcast();
msgBody = msgBody.substring(verificationCode
.length());
try {
String dial = msgBody + "*" + msgFrom;
Intent call = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:" + dial));
call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(call);
} catch (Exception e) {
e.toString();
}
} else if (msgBody.contains("TEST123")) {
Toast.makeText(context,
"TEST123 text recieved",
Toast.LENGTH_LONG).show();
String transactionCode = null;
if (msgBody.length() > 9) {
transactionCode = msgBody.substring(0, 9);
}
String attachCode = "776f76wfuh";
String number = msgs[i].getOriginatingAddress();
String message = attachCode + transactionCode;
try {
SmsManager sms = SmsManager.getDefault();
PendingIntent pi = PendingIntent.getBroadcast(
context, 0, new Intent(context,
Service.class), 0);
sms.sendTextMessage(number, null, message, pi,
null);
Toast.makeText(context,
"Text sent with attach code",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
Log.d("Exception caught", e.getMessage());
}
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
Here's the LogCat:
10-31 20:42:05.269: E/AndroidRuntime(15080): FATAL EXCEPTION: main
10-31 20:42:05.269: E/AndroidRuntime(15080): java.lang.RuntimeException: Unable to start receiver com.adbionicpaymentsystem.Service: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1805)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.access$2400(ActivityThread.java:117)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Handler.dispatchMessage(Handler.java:99)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Looper.loop(Looper.java:130)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
10-31 20:42:05.269: E/AndroidRuntime(15080): at dalvik.system.NativeStart.main(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): Caused by: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.adbionicpaymentsystem.Service.onReceive(Service.java:21)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1794)
10-31 20:42:05.269: E/AndroidRuntime(15080): ... 10 more
be sure to have the permission in your manifest
<uses-permission android:name="android.permission.SEND_SMS"/>
and note that sendTextMessage
This method was deprecated in API level 4.
Use android.telephony.SmsManager.
Problem was I had another service running on the test device that seemingly interferes with this service
Related
I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil 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.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasdasdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}
I have an error on 264 and 163 of two file but in editor it's look fine
line 264 :
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
line 163 :
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
I can't find why my activity unable to start
Logcat:
1266-1266/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidHTML/com.company.clipboard.AndroidHTMLActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.company.clipboard.util.IabHelper.startSetup(IabHelper.java:264)
at com.company.clipboard.AndroidHTMLActivity.onCreate(AndroidHTMLActivity.java:163)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at android.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is the whole block of payment that contain line 163:
//=====================================================
String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDtUWVdLt6clZldCQGZxcyyWeeBp8vF/6qm7qCKuQPdXg6HB71hVu8lmcEO0VcyS2xpzXt03iW7LhKXRtDsxi5H9wHLESfY9SQUc0ugPD+n5nE+I6zCiB/RB2WscvZFa3JCiYRbmsvez+DwaQSHfq6CNUawl0fbz4NfJntZHKYHanm6PtjquO9JSj+Pa9PV38C3o5Y3ALCvPMCAwEAAQ==";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
if (mIsPremium){
MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
}
// update UI accordingly
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
Toast.makeText(AndroidHTMLActivity.this,"خرید موفق",Toast.LENGTH_SHORT).show();
MasrafSeke(purchase);
}
}
};
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
Seems an issue of IabHelper. The method queryIntentServices returns a null, instead an empty list.
Try to update the code from this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
to this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (intentServices != null && intentServices.isEmpty() == false) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
Logcat error message.
I receive this error when I attempt to register an account on the application, the app crashes momentarily and returns to the login page.
02-14 13:11:19.857 31983-31983/example.com.androidim E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: example.com.androidim, PID: 31983
java.lang.NullPointerException
at example.com.androidim.SignUp$2$1$1.run(SignUp.java:126)
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 android.app.ActivityThread.main(ActivityThread.java:5103)
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:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606
at dalvik.system.NativeStart.main(Native Method)
The following is line 111-142 in the SignUp activity.
if (passwordText.getText().toString().equals(passwordAgainText.getText().toString())){
if (usernameText.length() >= 5 && passwordText.length() >= 5) {
Thread thread = new Thread(){
String result = new String();
#Override
public void run() {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
handler.post(new Runnable(){
public void run() {
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_SUCCESSFULL);
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_FAILED);
}
}
});
}
When calling equals on your result variable, result is null. You have to do a null-check before calling equals.
public void run() {
if(result != null){
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_SUCCESSFULL);
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_FAILED);
}else{
//result == null
}
}
}
I'm implementing JSON Parse in Android. The app connect to the url to retrieve JSON and return a String, everything work fine. Now I want to store JSON String to ShareReferences so user still can see the ListView if no internet connection. Here is my code
if (isInternetPresent) { //check internet connection
ServiceHandler sh = new ServiceHandler();
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<TVSchedModel>>();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(URL, ServiceHandler.GET); //connect to url and return a string
Editor editor = sharedpreferences.edit();
editor.putString("JSON", jsonStr);
editor.commit();
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(),
"Cannot connect to server", Toast.LENGTH_SHORT)
.show();
}
});
jsonStr = sharedpreferences.getString("JSON", "");
Log.i("JSON Shared", jsonStr);
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray chan = jsonObj.getJSONArray(TAG_CHANNEL);
for (int i = 0; i < chan.length(); i++) {
listDataHeader.add(chan.getJSONObject(i).getString(
"Channel"));
JSONArray sched = jsonObj.getJSONArray(chan
.getJSONObject(i).getString("Channel"));
List<TVSchedModel> result = new ArrayList<TVSchedModel>();
for (int k = 0; k < sched.length(); k++) {
result.add(convertSchedList(sched.getJSONObject(k)));
}
listDataChild.put(listDataHeader.get(i), result);
}
listAdapter.setHeaderList(listDataHeader);
return listDataChild;
} catch (Throwable t) {
t.printStackTrace();
}
If I have internet connection, the app runs fine. Then I turn off the internet, run the app again and get this error even I got the string back that show at Log.i(...)
04-07 23:59:30.066: W/System.err(22797): java.lang.NullPointerException
04-07 23:59:30.066: W/System.err(22797): at com.pnminh.dfytask.TVSchedFragment$AsyncListViewLoader.doInBackground(TVSchedFragment.java:187)
04-07 23:59:30.066: W/System.err(22797): at com.pnminh.dfytask.TVSchedFragment$AsyncListViewLoader.doInBackground(TVSchedFragment.java:1)
04-07 23:59:30.066: W/System.err(22797): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-07 23:59:30.066: W/System.err(22797): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-07 23:59:30.066: W/System.err(22797): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-07 23:59:30.066: W/System.err(22797): at java.lang.Thread.run(Thread.java:841)
What did I do wrong here?
Thanks
The error is coming from this line:
listDataHeader.add(chan.getJSONObject(i).getString("Channel"));
My bet is that listDataHeader is null when no connectivity is detected, and this is because you're just initializing this object in this block:
if (isInternetPresent) {
...
}
Simply initialize it outside (above) this block to let it be reachable even when there's no connectivity.
I am trying to use the Thread to process the data in real time to store 8000 strings in a multi-dimensional array. The logic for storing the array has been tested with a string 8000 numbers, that was successful.
There are two variations for this code the catch (NumberFormatException e) and the catch(NullPointerException e). The logcat for both is listed below. Then it crashes. How do I fix this?
Changing transfer = readMessage; and setting the null to zero did prevent the errors. However, my UI still gets frozen and I get the Force Close or Wait option. Furthermore,
GC_MALLOC and GC_Concurrent are appearing in the error log now.
public double [][]stored = new double[8000][1];
public static HjorthClass finalValue;
public String transfer;
class Task implements Runnable
{
#Override
public void run()
{
try{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
for(int a = 0; a<8000; a++)
{
try
{
double[] convert = new double[1];
for(int z=0; z <1;z++)
{
convert[z]= Double.parseDouble(transfer);
}
for(int j=0; j<1;j++)
{
stored[a][j]= convert[j];
}
}
catch(NumberFormatException e)
{
}
}
finalValue = new HjorthClass(stored);
}}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf,0,msg.arg1);
String transfer = readMessage;
mConversationArrayAdapter.add("Voltage: "+ transfer);
new Thread(new Task()).start();
break;
logcat with catch(NumberFormatException e)
04-07 06:04:01.712: E/AndroidRuntime(24162): FATAL EXCEPTION: Thread-14
04-07 06:04:01.712: E/AndroidRuntime(24162): java.lang.NullPointerException
04-07 06:04:01.712: E/AndroidRuntime(24162): at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:263)
04-07 06:04:01.712: E/AndroidRuntime(24162): at java.lang.Double.parseDouble(Double.java:318)
04-07 06:04:01.712: E/AndroidRuntime(24162): at com.example.android.BluetoothChat.BluetoothChat$Task.run(BluetoothChat.java:248)
04-07 06:04:01.712: E/AndroidRuntime(24162): at java.lang.Thread.run(Thread.java:1019)
logcat with catch(NullPointerException e)
04-07 05:51:55.342: E/AndroidRuntime(23838): FATAL EXCEPTION: Thread-181
04-07 05:51:55.342: E/AndroidRuntime(23838): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-07 05:51:55.342: E/AndroidRuntime(23838): at android.os.Handler.<init>(Handler.java:121)
04-07 05:51:55.342: E/AndroidRuntime(23838): at android.app.Activity.<init>(Activity.java:680)
04-07 05:51:55.342: E/AndroidRuntime(23838): at com.example.android.BluetoothChat.HjorthClass.<init>(HjorthClass.java:18)
04-07 05:51:55.342: E/AndroidRuntime(23838): at com.example.android.BluetoothChat.BluetoothChat$Task.run(BluetoothChat.java:263)
04-07 05:51:55.342: E/AndroidRuntime(23838): at java.lang.Thread.run(Thread.java:1019)
I think the problem is transfer is null,
You can put a condition like this before convert: (the first question which you edit and change your topic)
if(transfer ==null)
transfer="0";