I am having some problems with implementation of Collection in android. The code is given below. I compare the position chosen in an alert dialog and accordingly call collection and its related function. But there seems to be problem and java.lang NullPointerException occurs all the time. i Call these Collection functions at the OnCreate method of the Applciation Start-Up Activity.
private void onStartPref() {
// TODO Auto-generated method stub
// try {
SharedPreferences pref2 = getApplication().getSharedPreferences(
"MyPref", MODE_PRIVATE);
int loadPosition = pref2.getInt("MyKey", isChecked);
Toast.makeText(getApplicationContext(), "Position : " + loadPosition,
Toast.LENGTH_LONG).show();
if (pref2.contains("MyKey")) {
Toast.makeText(getApplicationContext(), "IF" + loadPosition,
Toast.LENGTH_LONG).show();
if (loadPosition == 0) {
Collections.reverse(applist);
Toast.makeText(getApplicationContext(),
"Reverses the present order list", Toast.LENGTH_SHORT)
.show();
} else if (loadPosition == 1) {
Collections.sort(applist,
new ApplicationInfo.DisplayNameComparator(
packageManager));
Toast.makeText(getApplicationContext(), "Sorts Alphabetically",
Toast.LENGTH_SHORT).show();
} else if (loadPosition == 2) {
Collections.shuffle(applist);
Toast.makeText(getApplicationContext(),
"Shuffles the present order selected",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "NO PREF" + loadPosition,
Toast.LENGTH_LONG).show();
}
// } catch (Exception e) {
// // TODO: handle exception
// Toast.makeText(getApplicationContext(), "ERROR : " + e,
// Toast.LENGTH_LONG).show();
// Log.i("ERROR", "" + e);
// e.printStackTrace();
// }
}
I am reversing , shuffling , sorting the order of my list but the application force closes. Can anybody help me with this Exception ? Can anybody also tell me how to load a list dynamically after these changes without reloading the activity or scrolling the list ?
Thanks
LOG -----------------
01-26 01:29:15.872: I/ERROR(26192): java.lang.NullPointerException
01-26 01:29:15.872: W/System.err(26192): java.lang.NullPointerException
01-26 01:29:15.882: W/System.err(26192): at java.util.Collections.reverse(Collections.java:1719)
01-26 01:29:15.882: W/System.err(26192): at com.example.allapps.AllAppsActivity.onStartPref(AllAppsActivity.java:462)
01-26 01:29:15.882: W/System.err(26192): at com.example.allpps.AllAppsActivity.onCreate(AllAppsActivity.java:252)
01-26 01:29:15.882: W/System.err(26192): at android.app.Activity.performCreate(Activity.java:5283)
01-26 01:29:15.882: W/System.err(26192): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-26 01:29:15.882: W/System.err(26192): at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 01:29:15.882: W/System.err(26192): at android.os.Looper.loop(Looper.java:136)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.main(ActivityThread.java:5001)
01-26 01:29:15.882: W/System.err(26192): at java.lang.reflect.Method.invokeNative(Native Method)
01-26 01:29:15.882: W/System.err(26192): at java.lang.reflect.Method.invoke(Method.java:515)
01-26 01:29:15.882: W/System.err(26192): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
01-26 01:29:15.882: W/System.err(26192): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
01-26 01:29:15.882: W/System.err(26192): at dalvik.system.NativeStart.main(Native Method)
I use the methods in OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
new LoadApplications().execute();
onStartPref();
}
LoadApplication is the main method regarding the applist. I use it in OnCreate Method and the method function is below.
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(AllAppsActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(AllAppsActivity.this, null,
"Loading Please Wait...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
You seem to initialize applist in the doInBackground method of an AsyncTask. I.e. there is no guarantee that when you call onStartPref, it will be initialized.
I would suggest to call onStartPref in onPostExecute.
Related
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."));
}
}
I know this has been posted multiple times now, but nothing seemed to fix my problem. I create a Loading Dialog on the UI thread, then start another thread which is doing some networking stuff and via interface, the class gets a callback, when networking is done. The problem is, after its done, i cant remove the loading dialog, even with "runOnUIThread". Here is the code:
public void onClickLoginButton (View view) {
if (!((EditText)findViewById(R.id.textNickname)).getText().toString().isEmpty() &&
!((EditText)findViewById(R.id.textPassword)).getText().toString().isEmpty()) {
loggingIn = new ProgressDialog(this);
loggingIn.setTitle("Login");
loggingIn.setMessage("Wait while logging in...");
loggingIn.show();
final LoginInterface callbackInterface = this;
new Thread(new Runnable() {
public void run() {
Networking net = new Networking();
net.Login(((EditText) findViewById(R.id.textNickname)).getText().toString(), ((EditText) findViewById(R.id.textPassword)).getText().toString(), callbackInterface);
}
}).start();
}
}
And this is the function that gets called by the networking stuff, after its done:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
loggingIn.hide();
loggingIn = null;
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}
And this is the stack trace:
04-17 17:06:11.313 13018-13121/com.assigame.nidhoegger.assigame E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-1422
Process: com.assigame.nidhoegger.assigame, PID: 13018
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6122)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:850)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.setFlags(View.java:8908)
at android.view.View.setVisibility(View.java:6036)
at android.app.Dialog.hide(Dialog.java:299)
at com.assigame.nidhoegger.assigame.Login.LoginCallback(Login.java:72)
at com.assigame.nidhoegger.assigame.Networking.Login(Networking.java:134)
at com.assigame.nidhoegger.assigame.Login$1.run(Login.java:64)
at java.lang.Thread.run(Thread.java:841)
04-17 17:06:11.719 13018-13018/com.assigame.nidhoegger.assigame E/WindowManager﹕ android.view.WindowLeaked: Activity com.assigame.nidhoegger.assigame.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42284588 G.E..... R......D 0,0-684,324} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:366)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.assigame.nidhoegger.assigame.Login.onClickLoginButton(Login.java:56)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
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:5017)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
You are calling the loggingIn.hide() method twice, and the first time not on the UI thread. Change your code to this:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}
I'm trying to implement a system service on Android with inter-process communication based on binding a messenger. For this I'm following this tutorial:
http://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html
But no matter what I'm trying, i can't get it to work.
I found different tutorials online but in the end they are all based on the same procedure.
The app will crash right away when I'm trying to communicate with the service.
Error message
10-09 15:40:33.490 3468-3468/com.example.stenosis.testservice E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.stenosis.testservice, PID: 3468
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stenosis.testservice/com.example.stenosis.testservice.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.stenosis.testservice.MyActivity.sendMsg(MyActivity.java:87)
at com.example.stenosis.testservice.MyActivity.onCreate(MyActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
MyActivity.java:
public class MyActivity extends Activity {
private ServiceConnection sConn;
private Messenger messenger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Service Connection to handle system callbacks
sConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
messenger = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We are conntected to the service
messenger = new Messenger(service);
}
};
// We bind to the service
bindService(new Intent(this, MyService.class), sConn, Context.BIND_AUTO_CREATE);
// Try to send a message to the service
sendMsg();
}
// This class handles the Service response
class ResponseHandler extends Handler {
#Override
public void handleMessage(Message msg) {
int respCode = msg.what;
String result = "";
switch (respCode) {
case MyService.TO_UPPER_CASE_RESPONSE: {
result = msg.getData().getString("respData");
System.out.println("result");
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
}
}
public void sendMsg() {
String val = "This is a test";
Message msg = Message
.obtain(null, MyService.TO_UPPER_CASE);
msg.replyTo = new Messenger(new ResponseHandler());
// We pass the value
Bundle b = new Bundle();
b.putString("data", val);
msg.setData(b);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
MyService.java
public class MyService extends Service {
public static final int TO_UPPER_CASE = 0;
public static final int TO_UPPER_CASE_RESPONSE = 1;
private Messenger msg = new Messenger(new ConvertHanlder());;
#Override
public IBinder onBind(Intent intent) {
return msg.getBinder();
}
class ConvertHanlder extends Handler {
#Override
public void handleMessage(Message msg) {
// This is the action
int msgType = msg.what;
switch (msgType) {
case TO_UPPER_CASE: {
try {
// Incoming data
String data = msg.getData().getString("data");
Message resp = Message.obtain(null, TO_UPPER_CASE_RESPONSE);
Bundle bResp = new Bundle();
bResp.putString("respData", data.toUpperCase());
resp.setData(bResp);
msg.replyTo.send(resp);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
}
default:
super.handleMessage(msg);
}
}
}
}
AndroidManifest.xml
<service android:name=".MyService" android:process=":convertprc"/>
Your problem is that the messanger property is null. You are experiencing concurrency problem. The bindService method is asynchronous - it returns immediately and performs the binding in a background thread. When the binding is done, the onServiceConnected method is invoked. When you try to send the message, the messanger is still not initialized because the onServiceConnected method is hasn't been executed yet.
me again, in my previous post, i was told to use AsyncTask in codes, to avoid mainexceptionthread, and now i'm encountering this errors:
**
01-26 09:39:06.220: E/AndroidRuntime(17218): FATAL EXCEPTION: AsyncTask #1
01-26 09:39:06.220: E/AndroidRuntime(17218): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.lang.Thread.run(Thread.java:856)
01-26 09:39:06.220: E/AndroidRuntime(17218): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4609)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.view.View.invalidate(View.java:10193)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.invalidateRegion(TextView.java:4375)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.invalidateCursor(TextView.java:4318)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.spanChange(TextView.java:7172)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:8759)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.Selection.setSelection(Selection.java:76)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.Selection.setSelection(Selection.java:87)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.setText(TextView.java:3535)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.setText(TextView.java:3405)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.EditText.setText(EditText.java:80)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.widget.TextView.setText(TextView.java:3380)
01-26 09:39:06.220: E/AndroidRuntime(17218): at com.example.projectthesis.Main$phpconnect.doInBackground(Main.java:98)
01-26 09:39:06.220: E/AndroidRuntime(17218): at com.example.projectthesis.Main$phpconnect.doInBackground(Main.java:1)
01-26 09:39:06.220: E/AndroidRuntime(17218): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-26 09:39:06.220: E/AndroidRuntime(17218): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-26 09:39:06.220: E/AndroidRuntime(17218): ... 5 more
**
i think it is because of the Exception e part, which has inputEmail.setText(e.toString());
but when i am changing it to just e.printstacktrace, it results nothing. Can you help me here guys these are my codes:
android:
**
public class Main extends Activity {
EditText inputEmail;
EditText inputPassword;
Button btnLogin;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputPassword = (EditText) findViewById(R.id.inputPassword);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
// button click event
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
validation();
}
});
}
public void validation()
{
if(inputEmail.getText().toString().equals("") || inputPassword.getText().toString().equals(""))
{
Toast.makeText( getApplicationContext(),"Fill Empty Fields",Toast.LENGTH_SHORT ).show();
}
else
{
new phpconnect().execute();
}
}
class phpconnect extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Main.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("eadd", inputEmail.getText().toString()));
postParameters.add(new BasicNameValuePair("password", inputPassword.getText().toString()));
//Passing Parameter to the php web service for authentication
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/TheCalling/log_in.php", postParameters); //Enter Your remote PHP,ASP, Servlet file link
String res=response.toString();
//res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
{
Toast.makeText( getApplicationContext(),"Correct Username or Password",Toast.LENGTH_SHORT ).show();
Intent i = new Intent(Main.this,MainMenu.class);
startActivity(i);
}
else
if(res.equals("0"))
{
Toast.makeText( getApplicationContext(),"Sorry!! Incorrect Username or Password",Toast.LENGTH_SHORT ).show();
}
} catch (Exception e) {
inputEmail.setText(e.toString());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
**
This again my PHP codes:
**
<?php
include("db_config.php");
$eadd=addslashes($_POST['eadd']);
$password=addslashes($_POST['password']);
$sql="SELECT * FROM users WHERE eadd='$eadd' and password='$password'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$count=mysql_num_rows($result);
if($count==1)
{
echo "1";
//(If result found send 1 to android)
}
else
{
echo "0";
//(If result not found send o to android)
}
?>
**
You get an error because of:
catch (Exception e) {
inputEmail.setText(e.toString());
}
Over here you try to alter the app's UI by altering the contents of an EditText from the background thread of the AsyncTask. Since I doubt you actually want to show an error to the user in the email input field and are doing this just for debugging purposes, try using e.printStackTrace() instead of inputEmail.setText(e.toString());
Additionally, you'll want to wrap your Toast.show() calls in a runOnUiThread() runnable.
You can't show the toast messages in doInBackground just move it to onPostExecute. and yes also this
catch (Exception e) {
inputEmail.setText(e.toString());
}
I am creating an RSS reader application for android 4.0+. I have put the reader code in AsyncTask because of the NetworkOnMainThreadException. The code almost works fine, however one line has an error. This is my code:
Java code:
private class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url=params[0];
headlines = new ArrayList();
links = new ArrayList();
//Download and parse xml feed
headlines = new ArrayList();
links = new ArrayList();
try {
URL url1 = new URL("http://feeds.pcworld.com/pcworld/latestnews");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url1), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
* As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
* so we should skip the "<title>" tag which is a child of "<channel>" tag,
* and take in consideration only "<title>" tag which is a child of "<item>"
*
* In order to achieve this, we will make use of a boolean variable.
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Feed parsed!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
}
in this code snippet i get an error:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
Error: The constructor ArrayAdapter(MainActivity.PostTask, int, List) is undefined.
Logcat:
01-26 20:55:53.811: E/AndroidRuntime(1830): FATAL EXCEPTION: AsyncTask #1
01-26 20:55:53.811: E/AndroidRuntime(1830): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.lang.Thread.run(Thread.java:856)
01-26 20:55:53.811: E/AndroidRuntime(1830): Caused by: java.lang.IllegalArgumentException
01-26 20:55:53.811: E/AndroidRuntime(1830): at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1615)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:343)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:1)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-26 20:55:53.811: E/AndroidRuntime(1830): ... 5 more
Could anyone please look into my problem and come up with a solution? Or tell me if i should do anything different? Thanks a lot!
Change it to:
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, headlines);
this refers to the AsyncTask, so you have to explicitly reference MainActivity's this.
use Activity Context instead of AsyncTask to Create ArrayAdapter inside onPostExecute method as :
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(Your_Current_Activity.this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
EDIT :
after log posted also change
xpp.setInput(getInputStream(url1), "UTF_8");
to
xpp.setInput(url1.openConnection().getInputStream(), "UTF_8");