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");
Related
I got this error whenever I change my URL to my online hosting, but if I change to 10.0.2.2 everything seems fine and running.
LogCat
02-01 23:02:18.302 17643-18052/com.example.jithea.testlogin E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0x40d8d9a8)
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: uncaught exception occurred
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ java.lang.RuntimeException: An error occured while executing doInBackground()
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ Caused by: java.lang.NullPointerException
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ ... 4 more
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: calling UncaughtExceptionHandler
02-01 23:02:18.315 17643-18052/com.example.jithea.testlogin 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:838)
Caused by: java.lang.NullPointerException
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
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:838)
02-01 23:02:18.371 17643-17659/com.example.jithea.testlogin I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x528dc150) fps:43.08, dur:1044.57, max:73.51, min:6.02
And here's my NewsActivity.java
public class NewsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParserNews jParser = new JSONParserNews();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://agustiniancampusevents.site40.net/newsDB/get_all_news.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_PID = "pid";
private static final String TAG_NEWSTITLE = "newstitle";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_NEWS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String newstitle = c.getString(TAG_NEWSTITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NEWSTITLE, newstitle);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NewsActivity.this, productsList,
R.layout.news_list_item, new String[]{TAG_PID,
TAG_NEWSTITLE},
new int[]{R.id.pid, R.id.newstitle});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
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.
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'm trying to develop an autocomplete location for goofle map. But, I have encountered some errors while developing. I do not know what is the cause of the error.
Below is my code.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ArrayAdapter<String> adapter;
AutoCompleteTextView textView;
Object[] arg0 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, R.layout.item_list);
textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (count % 3 == 1) {
adapter.clear();
// GetPlaces task = new GetPlaces();
// now pass the argument in the textview to the task
new GetPlaces().execute(textView.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args) {
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try {
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ URLEncoder.encode(arg0[0].toString(), "UTF-8")
+ "&types=geocode&language=en&sensor=true&key=<API-key here>");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
// take Google's legible JSON and turn it into one big
// string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
// turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
// now get the JSON array that's inside that object
JSONArray ja = new JSONArray(
predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
// add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
// then our post
#Override
protected void onPostExecute(ArrayList<String> result) {
Log.d("YourApp", "onPostExecute : " + result.size());
// update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.item_list);
adapter.setNotifyOnChange(true);
// attach the adapter to textview
textView.setAdapter(adapter);
for (String string : result) {
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp",
"onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
Here is the logcat error:
10-24 15:10:54.609: E/AndroidRuntime(14346): FATAL EXCEPTION: AsyncTask #1
10-24 15:10:54.609: E/AndroidRuntime(14346): java.lang.RuntimeException: An error occured while executing doInBackground()
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$3.done(AsyncTask.java:278)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.lang.Thread.run(Thread.java:856)
10-24 15:10:54.609: E/AndroidRuntime(14346): Caused by: java.lang.NullPointerException
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:76)
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:1)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$2.call(AsyncTask.java:264)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
The source of the error is obviously in MainActivity line 76, where you are accessing a null object
in 76th line..
use "URLEncoder.encode(args[0].toString()" instead of "URLEncoder.encode(arg0[0].toString()"
I'm trying to download strings from a HttpPost and I'm using the Async class to do this. But, when I run the App, it crashes. This is my first time using the Async class and I'm afraid I did some really silly, could you help me to find the error?
Just to note, I also want to update my listview when I get the strings. I tried to do this, buy putting them in a separate method.
Code:
public static final String PREFS_NAME = "MyPrefsFile";
BufferedReader in = null;
String data = null;
String username;
List headlines;
List links;
String password;
ArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// listview method
ContactsandIm();
new loadcontactsandIm().execute(PREFS_NAME);
}
public class loadcontactsandIm extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l ="";
String nl ="";
while ((l =in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
setListAdapter(adapter);
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
}
public void ContactsandIm() {
headlines = new ArrayList();
//get prefs
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String username = settings.getString("key1", null);
String password = settings.getString("key2", null);
if(username.equals("irock97")) {
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.setGravity(Gravity.TOP, -30, 50);
toast.show();
} else {
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.setGravity(Gravity.TOP, -30, 150);
toast.show();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
}
}
LogCat:
03-25 13:47:37.356: E/AndroidRuntime(2484): FATAL EXCEPTION: AsyncTask #1
03-25 13:47:37.356: E/AndroidRuntime(2484): java.lang.RuntimeException: An error occured while executing doInBackground()
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.os.AsyncTask$3.done(AsyncTask.java:200)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.lang.Thread.run(Thread.java:1096)
03-25 13:47:37.356: E/AndroidRuntime(2484): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.ViewRoot.requestLayout(ViewRoot.java:594)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.View.requestLayout(View.java:8125)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.View.requestLayout(View.java:8125)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.View.requestLayout(View.java:8125)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.view.ViewGroup.removeAllViews(ViewGroup.java:2255)
03-25 13:47:37.356: E/AndroidRuntime(2484): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:196)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.app.Activity.setContentView(Activity.java:1647)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.app.ListActivity.ensureList(ListActivity.java:314)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.app.ListActivity.getListView(ListActivity.java:299)
03-25 13:47:37.356: E/AndroidRuntime(2484): at com.gta5news.bananaphone.ChatService$loadcontactsandIm.doInBackground(ChatService.java:87)
03-25 13:47:37.356: E/AndroidRuntime(2484): at com.gta5news.bananaphone.ChatService$loadcontactsandIm.doInBackground(ChatService.java:1)
03-25 13:47:37.356: E/AndroidRuntime(2484): at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-25 13:47:37.356: E/AndroidRuntime(2484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
do you job in doInBackground, and use your jobs result on onPostExecute.
example:
public class TestActivity extends Activity
{
private GetTask getTask;
public ListView fList;
#Override
public void onCreate(Bundle savedInstanceState)
{
getTask = new GetTask();
getTask.execute();
fList = (ListView) findViewById(R.id.lstview);
}
public class GetTask extends AsyncTask<Void, Void, List>
{
#Override
protected List doInBackground(Void... params) {
return load();
}
#Override
protected void onPostExecute(List result) {
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
fList.setAdapter(adapter);
}
}
private List load() {
// get your data from http
// add to your list, probably you can use model.
List headlines;
headlines.add(data);
return headlines;
}
}
You set your ListView adapter in doInBackground. Never manipulate the UI outside of UI thread
You can't interact with UI elements from any other thread than the main thread. You'll need to do all of the interaction of the ListView in the onPostExecute method.
Basically you will want to compile all the data from the web request in the doInBackground method, stored on your task instance, then on the onPostExecute get the list view and set the adapter and populate with the data.
Firstly you must not handle any UI related task in doInBackground() to UI related task we have a method call onPostExecute() where we can handle all ui related tasks..
If you still dont want to use these method and handle it in doInBackground() then you do it in the below code::::
runOnUiThread(new Runnable() {
public void run() {
//your UI related code stuff
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
setListAdapter(adapter); //do what you like here
}
});