I have made a normal class and an AsyncTask and I want to make this code:
private void addNewQuake (Quake _quake) {
//Add the new quake to our list of earthquakes
earthquakes.add(_quake);
//Notify the array adapter of a change
aa.notifyDataSetChanged();
}
So I can add it to AsyncTask?
Or do I need to do in a other way?
#Override
protected void onCreate(Bundle savedInstanceState) {
// your other code
new DataLoadAsync().execute(); //start to get data
}
public class DataLoadAsync extends AsyncTask{
private Quake quake;
#Override
protected void doInBackground(){
// handle network data in here and put the result to quake in here.
refreshEarthquakes();
}
#Override
protected void onPostExecute(){
// use the result
addNewQuake(quake);
}
}
syntax is not complete, I just wanted to show you, you need to put your network data load method in doInBackground to get data, then you can use it in onPostExecute()
Here is my new code:
public class Earthquake extends Activity {
ListView earthquakeListView;
ArrayAdapter<Quake> aa;
ArrayList<Quake> earthquakes = new ArrayList<Quake>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
earthquakeListView = (ListView) this
.findViewById(R.id.earthquakeListView);
int layoutID = android.R.layout.simple_list_item_1;
aa = new ArrayAdapter<Quake>(this, layoutID, earthquakes);
earthquakeListView.setAdapter(aa);
new DataLoadAsync().execute();
}
public class DataLoadAsync extends AsyncTask<Object, Object, Object>{
private Quake quake;
protected void doInBackground(){
// handle network data in here and put the result to quake in here.
refreshEarthquakes();
}
protected void onPostExecute(){
// use the result
addNewQuake(quake);
}
#Override
protected Object doInBackground(Object... arg0) {
// TODO Auto-generated method stub
return null;
}
}
void refreshEarthquakes() {
//get the XML
URL url;
try {
String quakeFeed = getString(R.string.quake_feed);
url = new URL(quakeFeed);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//Parse the earthquake feed
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
//Clear the old earthquakes
earthquakes.clear();
//Get a list of each earthquake entry
NodeList nl = docEle.getElementsByTagName("entry");
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength(); i++) {
Element entry = (Element)nl.item(i);
Element title = (Element)entry.getElementsByTagName("title").item(0);
Element g = (Element)entry.getElementsByTagName("georss:point").item(0);
Element when = (Element)entry.getElementsByTagName("updated").item(0);
Element link = (Element)entry.getElementsByTagName("link").item(0);
String details = title.getFirstChild().getNodeValue();
String hostname = "http://earthquake.usgs.gov";
String linkString = hostname + link.getAttribute("href");
String point = g.getFirstChild().getNodeValue();
String dt = when.getFirstChild().getNodeValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
qdate = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
String[] location = point.split(" ");
Location l = new Location("dummyGPS");
l.setLatitude(Double.parseDouble(location[0]));
l.setLongitude(Double.parseDouble(location[1]));
String magnitudeString = details.split(" ")[1];
int end = magnitudeString.length()-1;
double magnitude = Double.parseDouble(magnitudeString.substring(0, end));
details = details.split(",")[1].trim();
Quake quake = new Quake(qdate, details, l, magnitude, linkString);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
finally {
}
}
private void addNewQuake (Quake _quake) {
//Add the new quake to our list of earthquakes
earthquakes.add(_quake);
//Notify the array adapter of a change
aa.notifyDataSetChanged();
}
}
Related
I am have sql DB and I am trying to display queried values in a listView. I created a custom adapter for the listView. problem is
I am not able to see any data displayed on my listView.
code of main
public class _songs_playlist extends AppCompatActivity {
ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
private static int SPLASH_TIME_OUT=2000;
AlertDialog alertDialog;
private boolean loggedIn = false;
String type;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__songs_playlist);
new JSONParse().execute();
MyCustomAdapterSongs itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(itemsAdapter);
itemsAdapter.notifyDataSetChanged();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
alertDialog.setTitle("Upadting Data");
pDialog = new ProgressDialog(_songs_playlist.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
HTTPHandler sh = new HTTPHandler();
String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
try {
//Fetching the boolean value form sharedpreferences
URL url = new URL(login_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.e("RESULT", result);
JSONObject jsonObject = new JSONObject(result);
JSONArray result1 = jsonObject.getJSONArray("result");
for (int i = 0; i < result1.length(); i++) {
JSONObject c = result1.getJSONObject(i);
String id = c.getString("songID");
String names = c.getString("songName");
String ss = c.getString("singerName");
listofsoongs.add(new songsarray(ss,id,names));
}
return jsonObject;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
if(true)
{
}
else
{
}
}
}
}
code of custom array adapter
public class MyCustomAdapterSongs extends ArrayAdapter<songsarray> {
Context context;
ArrayList<songsarray> items;
public MyCustomAdapterSongs(Activity context, ArrayList<songsarray> songsarrays) {
super(context, 0, songsarrays);
this.context=context;
this.items=songsarrays;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.itemlist, parent, false);
}
TextView nameTextView = (TextView) listItemView.findViewById(R.id.textView1);
nameTextView.setText(currentAndroidFlavor.getSingername());
Log.e("hhhh", nameTextView.getText().toString());
TextView numberTextView = (TextView) listItemView.findViewById(R.id.textView2);
numberTextView.setText(currentAndroidFlavor.getSongname());
Log.e("jjjj", numberTextView.getText().toString());
CheckBox ch=(CheckBox)listItemView.findViewById(R.id.checkBox1);
ch.setSelected(currentAndroidFlavor.isSelected());
return listItemView;
}
#Override
public int getCount() {
if(items == null)
return 0;
return items.size();
}
#Override
public songsarray getItem(int i) {
return items.get(i);
}
}
Call itemsAdapter.notifyDataSetChanged() within onPostExecute.
Your list is empty until the AsyncTask finishes there.
You'll have to make the adapter a member variable of the Activity class
As in your code I can see you are updating the list in doInBackground but you are not notifying the adapter for the changes.
In onPostExecute method you need to call itemsAdapter.notifyDataSetChanged() and make sure it you are not calling it inside doInBackground as in background thread you can't to UI related work.
Check the EDITS in this code snippet
`
public class _songs_playlist extends AppCompatActivity {
ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
private static int SPLASH_TIME_OUT=2000;
AlertDialog alertDialog;
private boolean loggedIn = false;
String type;
String result;
//EDIT 1: Make these member variables
MyCustomAdapterSongs itemsAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__songs_playlist);
//EDIT 2: get references your views before AsyncTask
listView = (ListView) findViewById(R.id.listView1);
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
alertDialog.setTitle("Upadting Data");
pDialog = new ProgressDialog(_songs_playlist.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
HTTPHandler sh = new HTTPHandler();
String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
try {
//Fetching the boolean value form sharedpreferences
URL url = new URL(login_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.e("RESULT", result);
JSONObject jsonObject = new JSONObject(result);
JSONArray result1 = jsonObject.getJSONArray("result");
for (int i = 0; i < result1.length(); i++) {
JSONObject c = result1.getJSONObject(i);
String id = c.getString("songID");
String names = c.getString("songName");
String ss = c.getString("singerName");
listofsoongs.add(new songsarray(ss,id,names));
}
return jsonObject;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
//EDIT 3: set your adapter here as this method will be called on the UI Thread
itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);
listView.setAdapter(itemsAdapter);
}
}
}
}
`
i have classes in my projects that only does the server operations such as getting and putting data. i have class which populating list and then method to get this list. the problem is that i'm calling the "getList" method and the background operation hasent finished then i get null from the "getList" method
this is my AsyncTask class, as you can see the "getList" suppose to give me the list completed
public class GetRoomatesListActivity extends AsyncTask<String, String, String> {
private ArrayList<RoomateModel> tmpList;
private ArrayList<RoomateModel> completeList;
DBHelper db;
Context context;
public GetRoomatesListActivity(Context context){
this.context = context;
}
#Override
protected String doInBackground(String... params) {
db = DBHelper.getInstance(context);
HttpURLConnection connection = null;
BufferedReader reader = null;
tmpList = new ArrayList<RoomateModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object
String Fname = finalObject.getString("firstName");
String Lname = finalObject.getString("lastName");
String phone = finalObject.getString("phone");
RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
tmpList.add(item);//adds the roomate to the list of roomates
//add the roomates to local data base
db.addRoomate(item,apartment);
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
completeList = tmpList;
}
public ArrayList<RoomateModel> getList(){
return completeList;
}
}
and this is the class which im trying to get the list to in order to use it but its retrieving null
public class roomatesScreen extends Activity {
ListView items;
ArrayList<RoomateModel> list; //list to compare with the list rerived from GetRoomatesListActivity
RoomatesAdapter adapter;
DBHelper db;
ApartmentModel apartment;
SharedPreferences preferences;
GetRoomatesListActivity r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roomates_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
items = (ListView) findViewById(R.id.roomatesList);
db = DBHelper.getInstance(this);
Bundle bundle = getIntent().getExtras();
int number = bundle.getInt("number");
apartment = new ApartmentModel(number);// creates apartment model with the user's apartment number
final String num = Integer.toString(number);
r = new GetRoomatesListActivity(this);
r.execute("this is the link to my query" + num);
list = r.getList(); //here list is null
adapter = new RoomatesAdapter(roomatesScreen.this, list);
items.setAdapter(adapter);//here application crushes because of nullPointerExpeption
The best way is to perform the update on UI is in PostExecute method of AsyncTask..
At the time you are accessing it, the control is in the doInBackground method. So your list is null at that time.
put this
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter = new RoomatesAdapter(roomatesScreen.this, tmpList);
items.setAdapter(adapter);/
}
into the onPostExecute().
2nd solution
Initialize the list when you are setting it to adapter. like:
list = new ArrayList();
and rest work (update the list and call notifyDataSetChanged() on adapter object) in onPostExecute().
Change doInBackground() method return type
public class GetRoomatesListActivity extends AsyncTask<String, String, ArrayList<Object>> {
private ArrayList<RoomateModel> tmpList;
private ArrayList<RoomateModel> completeList;
DBHelper db;
Context context;
public GetRoomatesListActivity(Context context){
this.context = context;
}
#Override
protected ArrayList<Object> doInBackground(String... params) {
db = DBHelper.getInstance(context);
HttpURLConnection connection = null;
BufferedReader reader = null;
tmpList = new ArrayList<RoomateModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object
String Fname = finalObject.getString("firstName");
String Lname = finalObject.getString("lastName");
String phone = finalObject.getString("phone");
RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
tmpList.add(item);//adds the roomate to the list of roomates
//add the roomates to local data base
db.addRoomate(item,apartment);
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
completeList = tmpList;
}
public ArrayList<RoomateModel> getList(){
return completeList;
}
}
my app needs to download a rss file in xml. i parse the data but i don't able to insert them into listview.
my code is.
public class MainActivity extends Activity {
ProgressDialog progress =null;
private final static String ADDRESS ="http://www.repubblica.it/rss/sport/rss2.0.xml";
private ListView lista =null ;
private List<ArticleInfo> list = null;
private ArrayAdapter<ArticleInfo> adapter = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lista= (ListView)findViewById(R.id.listView);
//adapter =new ArrayAdapter<ArticleInfo>(this,android.R.layout.simple_list_item_1,list);
//lista.setAdapter(adapter);
progress = new ProgressDialog(this);
progress.setMax(100);
progress.setMessage("Attendi qualche istante");
}
public void start(View v){
new BackgroundTask().execute();
}
private class BackgroundTask extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(ADDRESS);
} catch (MalformedURLException e) {
return null;
}
StringBuffer buffer=null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String tmp = null;
buffer = new StringBuffer();
while((tmp=reader.readLine())!= null){
buffer.append(tmp);
}
} catch (IOException e) {
return null;
}
list = RssParser.parseXML(buffer.toString());
return buffer.toString();
}
#Override
protected void onPreExecute(){
progress.setProgress(0);
progress.show();
}
#Override
protected void onProgressUpdate(Integer ... values){
super.onProgressUpdate(values);
progress.setProgress(values[0]);
}
#Override
protected void onPostExecute(String res){
super.onPostExecute(res);
progress.dismiss();
if (res!=null){
// TextView text = (TextView)findViewById(R.id.text);
//text.setText(res);
adapter =new ArrayAdapter<ArticleInfo>(this,android.R.layout.simple_list_item_1,res);
lista.setAdapter(adapter); **THIS IS MY ERROR**
}
}
}
}
this is my parser class
public class RssParser {
public static List<ArticleInfo> parseXML(String rss){
List<ArticleInfo> res =new ArrayList<>();
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder =null;
try {
builder=factory.newDocumentBuilder();
} catch (ParserConfigurationException e) { }
try {
Document doc = builder.parse(new InputSource(new StringReader(rss)));
doc.getDocumentElement().normalize();// aggiungo getDocumentElement()
NodeList list = doc.getElementsByTagName("item");
for(int i=0;i<list.getLength();i++){
Node n=list.item(i);
if(n.getNodeType()==Node.ELEMENT_NODE){
Element e= (Element) n;
String title = e.getElementsByTagName("title").item(0).getTextContent();
String url = e.getElementsByTagName("link").item(0).getTextContent();
res.add(new ArticleInfo(title,url));
}
}
} catch (SAXException e) {
} catch (IOException e) {
}
return res;
}
the framework gives me an error in the last row of main activity where i try to crate the adapter
Could you give me an hand ?
Thanks in advance
The issue is due of this line
adapter =new ArrayAdapter<ArticleInfo>(this,android.R.layout.simple_list_item_1,res);
your ArrayAdapter is expecting a Collection of ArticleInfo, but you are passing res which is one single String. Change your AsyncTask in order to make it return list instead of buffer.toString(), E.g.
private class BackgroundTask extends AsyncTask<String,Integer,List<ArticleInfo>>
and doInBackground returns list instead of buffer.toString()
ok i used the context and the error desappear . when i launch the emulator , when the asynctask works, the app goes in crash. the logcat is j
ava.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
at artetecapp.ilfattounofficial.MainActivity$BackgroundTask.onPostExecute(MainActivity.java:123)
at artetecapp.ilfattounofficial.MainActivity$BackgroundTask.onPostExecute(MainActivity.java:73)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
In the below code I got an error when running my android project for RssReader.
My main file:
public class Earthquake extends Activity {
ListView earthquakeListView;
ArrayAdapter < Quake > aa;
ArrayList < Quake > earthquakes = new ArrayList < Quake > ()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
earthquakeListView = (ListView) this.findViewById(R.id.earthquakeListView);
int layoutID = android.R.layout.simple_list_item_1;
aa = new ArrayAdapter < Quake > (this, layoutID, earthquakes);
earthquakeListView.setAdapter(aa);
refreshEarthquakes();
}
private void refreshEarthquakes() {
//get the XML
URL url;
try {
String quakeFeed = getString(R.string.quake_feed);
url = new URL(quakeFeed);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//Parse the earthquake feed
Document dom = db.parse( in );
Element docEle = dom.getDocumentElement();
//Clear the old earthquakes
earthquakes.clear();
//Get a list of each earthquake entry
NodeList nl = docEle.getElementsByTagName("entry");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element) nl.item(i);
Element title = (Element) entry.getElementsByTagName("title").item(0);
Element g = (Element) entry.getElementsByTagName("georss:point").item(0);
Element when = (Element) entry.getElementsByTagName("updated").item(0);
Element link = (Element) entry.getElementsByTagName("link").item(0);
String details = title.getFirstChild().getNodeValue();
String hostname = "http://earthquake.usgs.gov";
String linkString = hostname + link.getAttribute("href");
String point = g.getFirstChild().getNodeValue();
String dt = when.getFirstChild().getNodeValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Date qdate = new GregorianCalendar(0, 0, 0).getTime();
try {
qdate = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
String[] location = point.split(" ");
Location l = new Location("dummyGPS");
l.setLatitude(Double.parseDouble(location[0]));
l.setLongitude(Double.parseDouble(location[1]));
String magnitudeString = details.split(" ")[1];
int end = magnitudeString.length() - 1;
double magnitude = Double.parseDouble(magnitudeString.substring(0, end));
details = details.split(",")[1].trim();
Quake quake = new Quake(qdate, details, l, magnitude, linkString);
//Process a newly found earthquake
addNewQuake(quake);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} finally {}
}
private void addNewQuake(Quake _quake) {
//Add the new quake to our list of earthquakes
earthquakes.add(_quake);
//Notify the array adapter of a change
aa.notifyDataSetChanged();
}
}
Second file:
public class Quake {
private Date date;
private String details;
private Location location;
private double magnitude;
private String link;
public Date getDate() {
return date;
}
public String getDetails() {
return details;
}
public Location getLocation() {
return location;
}
public double getMagnitude() {
return magnitude;
}
public String getLink() {
return link;
}
public Quake(Date _d, String _det, Location _loc, double _mag, String _link) {
date = _d;
details = _det;
location = _loc;
magnitude = _mag;
link = _link;
}
#Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
String dateString = sdf.format(date);
return dateString + ": " + magnitude + " " + details;
}
}
I have read many articles with this and I have tried to add AsyncTask but it doesn't work. Also I have tried to add this:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But this error comes up:
android.os.NetworkOnMainThreadException
How can I fix this issue?
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask.
see : http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html
I am using AsyncTask to get data from RSS feed and DOM parser and ArrayAdapter.
I noticed that the RSS feed is taking too long to load and show data on screen, at first I thought because the number of articles is big but when I limited the for loop to read only 3 articles it remained taking too long to show the articles!!
below is the full code I am using to parse the data and the main activity
Main activity code:
public class NewsMainActivity extends Activity implements OnItemClickListener {
/** Called when the activity is first created. */
ListView listview;
List<NewsBean> arrayList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
initComponents();
if (Utils.isNetworkAvailable(this)) {
new MyRssReadTask()
.execute("feed_URL");
} else {
Toast.makeText(this, "Please check your internet connection", Toast.LENGTH_SHORT)
.show();
}
}
private void initComponents() {
listview = (ListView) findViewById(android.R.id.list);
listview.setOnItemClickListener(this);
}
class MyRssReadTask extends AsyncTask<String, Void, Void> {
ProgressDialog waitingDialog;
#Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(NewsMainActivity.this);
waitingDialog.setMessage("Loading articles, Please wait...");
waitingDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... urls) {
arrayList = new NewsParser().getData(urls[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
waitingDialog.dismiss();
setDataToListView();
super.onPostExecute(result);
}
}
protected void setDataToListView() {
if (null != arrayList && arrayList.size() != 0) {
NewsRowAdapter objNewsRowAdapter = new NewsRowAdapter(
NewsMainActivity.this, R.layout.row, arrayList);
listview.setAdapter(objNewsRowAdapter);
} else {
showToast("There was an error to get data, please try again later.");
}
}
void showToast(String msg) {
Toast.makeText(NewsMainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
final NewsBean objBean = (NewsBean) arrayList.get(position);
Intent intent = new Intent(NewsMainActivity.this,
NewsDetail.class);
intent.putExtra("title", objBean.getTitle());
intent.putExtra("description", objBean.getDescription());
//intent.putExtra("pubdate", objBean.getPubDate());
//intent.putExtra("creator", objBean.getCreator());
intent.putExtra("link", objBean.getLink());
startActivity(intent);
}
News Parser
public class NewsParser {
private List<NewsBean> arrayListPasre;
public List<NewsBean> getData(String _url) {
try {
arrayListPasre = new ArrayList<NewsBean>();
URL url = new URL(_url);
URLConnection con = url.openConnection();
System.out.println("Connection is : " + con);
System.out.println("Connection InputStream is : "
+ con.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
System.out.println("Reader us now : " + reader);
String inputLine;
String fullStr = "";
while ((inputLine = reader.readLine()) != null)
fullStr = fullStr.concat(inputLine + "\n");
InputStream istream = url.openStream();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
System.out.println("Builder : " + builder);
Document doc = builder.parse(istream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("item");
System.out.println("nlist " + nList);
for (int temp = 0; temp < 3; temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NewsBean objBean = new NewsBean();
objBean.setTitle(getTagValue("title", eElement));
objBean.setDescription(getTagValue("description", eElement));
objBean.setLink(getTagValue("link", eElement));
arrayListPasre.add(objBean);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayListPasre;
}
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
any suggestions i would be thankful!! :)
You do no need to parse whole rss at once time. You can do this partially. For example parse document and get rss items count and then call you async task for 3 or 5 or 10 items only. In onPostExecute() add results to your adapter and call notifydatasetchanged().