I'm making an android app with a rss feed in android studio. I got a rss feed reader library(https://github.com/ShirwaM/Simplistic-RSS), put it in my project and created my MainActivity and now I get and and exception: V/Error Parsing Data﹕ java.io.IOException: Couldn't open http://feeds.bbci.co.uk/news/rss.xml
MainActivity:
public class MainActivity extends Activity {
private ListView mList;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, R.layout.basic_list_item);
new GetRssFeed().execute("http://feeds.bbci.co.uk/news/rss.xml");
}
private class GetRssFeed extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
RssReader rssReader = new RssReader(params[0]);
for (RssItem item : rssReader.getItems())
adapter.add(item.getTitle());
} catch (Exception e) {
Log.v("Error Parsing Data", e + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter.notifyDataSetChanged();
mList.setAdapter(adapter);
}
}
Add the proper permissions to use internet in your manifest will solve the problem.
Related
I am loading list in ListView using AsyncTask by showing ProgressBar. But in my code the ProgressBar is now showing. Cant understand the problem.
I used the same code as in slidenerd but in the video code works but my code doesn't seem to work.
Video Link
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] items = {"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
listView.setAdapter(adapter);
new JSONTask().execute();
}
public class JSONTask extends AsyncTask<Void, String, Void> {
private ArrayAdapter<String> adapter;
private int count = 0;
#Override
protected void onPreExecute() {
adapter = (ArrayAdapter<String>) listView.getAdapter();
setProgressBarIndeterminateVisibility(true);
setProgressBarVisibility(true);
}
#Override
protected Void doInBackground(Void... params) {
for (String i : items) {
publishProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
adapter.add(values[0]);
count++;
setProgress((int) (((double) count / items.length) * 10000));
}
#Override
protected void onPostExecute(Void aVoid) {
setProgressBarIndeterminateVisibility(false);
setProgressBarVisibility(false);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
}
}
From the documentation of setProgressBarVisibility() and setProgressBarIndeterminateVisibility():
This method was deprecated in API level 24.
No longer supported
starting in API 21.
You should use a ProgressDialog instead.
you should use simple ProgressDialog
for example :
ProgressDialog myPd = ProgressDialog.show(context, "Please wait", "Uploading Database to Cloud...", true);
myPd.setCancelable(false);
Trying to populate data to a RecyclerView from cloud, though I get output in Main Thread, it takes time, so decided to add an AsyncTask to load items with ease and also to insert a ProgressDialog, however now it seems like code has no effect, getting an empty screen.
But the AsyncTask is getting executed, as I am able to log items in the logcat, no idea why I don't get a RecyclerView. Here is the code I use and looking for help:
public class BigBoard extends ActionBarActivity {
private List<Person> persons;
private RecyclerView rv;
private RVAdapter adapter;
private String a,b;
private ProgressDialog pr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "app-id", "client-key");
setContentView(R.layout.activity_big_board);
Loader abc = new Loader();
abc.execute();
adapter = new RVAdapter(persons);
rv=(RecyclerView)findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
}
private class Loader extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pr = new ProgressDialog(BigBoard.this);
pr.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pr.setIndeterminate(true);
pr.setCancelable(false);
pr.setMessage("Loading Board");
pr.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... urls) {
initializeData();
initializeAdapter();
return null;
}
#Override
protected void onPostExecute(String result) {
pr.dismiss();
}
private void initializeData(){
persons = new ArrayList<>();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("BigBoard");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> credentialList, ParseException e) {
if (e == null) {
for(int i=0;i<credentialList.size();i++)
{
a=credentialList.get(i).getString("Location");
b=credentialList.get(i).getString("Feed");
persons.add(new Person(a,b));
Log.d("OUT", "So the Val::------> " +a +b);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
});
}
private void initializeAdapter(){
rv.setAdapter(adapter);
}
}
}
place the adapter.notifyDataSetChanged(); or rv.setAdapter(adapter);
to onPostExecute..
since onOPostExecute works on UI Thread.
Edit :
create a function inside the Adapter
public void updatePersons(List<Person> persons) {
this.persons = persons;
notifyDataSetChanged();
}
after filling the list in onPostExecute call this function the List.
I want to declare arrayList into this line:
public class tlcity extends Activity {
//ArrayList<String> idArray = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
and into the other method,for example this method:
protected void onPostExecute(String result) {
//fill the arraylist
...
and into the other method for example this method read arraylist data:
public void readlist(){
//read the arraylist data and show
}
How can i do this?
You can declare ArrayList like this
ArrayList<String> list;
list = new ArrayList<String>();
You can add, remove items in ArrayList Like this
list.add("A");
list.remove(0);
ArrayList<String> abc=new ArrayList<String>();
You can initialize or create an instance of your array list like this
idArray = new ArrayList();
You can perform any operations to it using idArray object.
For example you can add items like this
idArray.add("item1");//In you case its a list of strings.
In the same way you would do that in another Java app / class:
public class tlcity extends Activity {
List<String> idArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
idArray = new ArrayList<String>();
}
protected void onPostExecute(String result) {
idArray.add("One");
idArray.add("Two");
idArray.add("Three");
...
}
public void readlist(){
for (final String element : idArray) {
// Use the nth string
}
}
I want to declare arrayList into this line:
ArrayList<String> myList;
and into the other method,for example this method:
myList = new ArrayList<String>;
and into the other method for example this method read arraylist data:
for(int i=0; i<myList.size(); i++)
System.out.println(myList.get(i).toString());
If you want to use ArrayList locally then declare it locally. if you want to use it in all methods then declare it globally in class.
public class tlcity extends Activity {
ArrayList<String> idArray = new ArrayList<>(); // to Use this arraylist globally.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> localaraaylist = new ArrayList<>(); //to use arraylist in only in oncreate method.
....
According to your post, telling how to declae ArrayList will not enough as you have some methods like onPreExecute() which is a method ofAsyncTask Interface.
Look at this,
public class MainActivity extends ActionBarActivity {
ArrayList<String> arrayList; // declaring ArrayList here
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<String>(); // Initializing arrayList
arrayList.add("initial text"); // adding a data to arrayList
ListView listView = (ListView)findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList); // setting the arrayList in ArrayAdapter
listView.setAdapter(adapter);
new LongOperation().execute(); // async Task
}
private class LongOperation extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
// progress dialog starts here
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// for understanding purpose, i made a thread to sleep for 5 sec and later it will add A,B & C to ArrayList.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// adding few more items to arrayList
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss(); // dismissing the progress Dialog
adapter.notifyDataSetChanged(); // refreshing listview
readA(); // read the arrayList
}
}
public void readA()
{
for (int i = 0; i<arrayList.size(); i++)
{
Log.d("key",arrayList.get(i));
}
}
}
Output :
If you run the above code, Initially your list view will only contain only one item & after 5 sec loading it will add another 3 items. The below information will print in logcat that reads the ArrayList.
04-13 14:07:32.395 1123-1123/? D/key﹕ initial text
04-13 14:07:32.395 1123-1123/? D/key﹕ A
04-13 14:07:32.395 1123-1123/? D/key﹕ B
04-13 14:07:32.395 1123-1123/? D/key﹕ C
i have listview and the content of listview change depend on user interface
and i need to know how to create new instance of async task if i implement callback receiver
public interface CallbackReciever {
public void receiveData(String result);
}
and the async task class
public abstract class ConnectDB extends AsyncTask<String, String, String> implements CallbackReciever {
ProgressDialog pDialog;
Context context;
public String resString;
public ConnectDB(Context context)
{
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public abstract void receiveData(String object);
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args)
{
// getting JSON string from URL
resString =Connection.Get(path);
return resString;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all products
pDialog.dismiss();
if(resString!=null)
{
receiveData(resString);
}
}
}
and the MainActivity class
public class MainActivity extends Activity {
ListView list;
MovieAdapter adapter;
public ArrayList<Movie> data=new ArrayList<Movie>();
public ConnectDB conDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context t=this.getApplicationContext();
setContentView(R.layout.activity_main);
conDB= new ConnectDB(MainActivity.this) {
#Override
public void receiveData(String result) {
// TODO Auto-generated method stub
try {
Log.d("ds", result);
JSONObject json = null;
JSONArray jArray = new JSONArray(result);
int i=0;
while ( i< jArray.length())
{
final Movie tmp=new Movie();
json = jArray.getJSONObject(i);
tmp.setName(json.getString("name"));
tmp.setUrl(json.getString("image"));
tmp.setDescription(json.getString("desc"));
tmp.setTime(json.getString("time"));
tmp.setTime(Utils.ChangeTolocaclTime(tmp.getTime()));
tmp.setWatch(Utils.CanWatch(tmp.getTime()));
data.add(tmp);
i++;
}
}
catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
if(data.size()==0)
{
Toast.makeText(t, "Server Error", Toast.LENGTH_SHORT).show();
list.setVisibility(View.INVISIBLE);
}
// Create custom adapter for listview
adapter=new MovieAdapter(MainActivity.this, data,t);
//Set adapter to listview
list.setAdapter(adapter);
}
};
conDB.execute("MBC2");
}
The activity should implement the receiver and the async task should call it, something like this:
public class MyActivity extends Activity implements CallbackReceiver{
#Override
public void onCreate(Bundle savedInstanceState) {
//Set everything up
MyAsyncTask task = new MyAsyncTask();
task.setOnDataReceivedListener(this);
task.execute();
}
#Override
public void onReceiveData(String data){
//Do something with the data
}
}
Then, in the async task, you can call the receiver method in onPostExecute
public abstract class MyAsyncTask extends AsyncTask<String, String, String>{
private CallbackReciever receiver = null;
public void setOnDataReceivedListener(CallbackReciever receiver){
this.receiver = receiver
}
protected void onPostExecute(String file_url)
{
if(receiver != null){
receiver.onReceiveData(file_url);
}
}
}
The second way to do this is to simply make an anonymous inner class of your async task and override onPostExecute:
public class MyActivity extends Activity implements CallbackReceiver{
#Override
public void onCreate(Bundle savedInstanceState) {
//Set everything up
MyAsyncTask task = new MyAsyncTask(){
#Override
protected void onPostExecute(String file_url){
//Do what you want with your data here
}
};
task.execute();
}
}
this is my code to load listview items
#SuppressLint("DefaultLocale")
public class SearchList extends Activity {
private ArrayList<String> founded = new ArrayList<String>();
private OrderAdapter m_adapter;
ListView lv;
/** Called when the activity is first created. */
#SuppressLint("DefaultLocale")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchlist);
lv = (ListView) findViewById(R.id.listView1);
new Load().execute();
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}
private class Load extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(SearchList.this);
progress.setMessage("loading....");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
for (int i = 0; i <500000; i++) {
founded.add("String "+i);
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
}
}
when i run the code the progress dialog already appear but after its dismiss i found that the list is empty no items added to it i do not know what is the problem and why the list is empty after the dialog loading .Pls need help
thanks in advance.
Set listadapter in onPostExecute Because you Are using AsyncTask to get adapter data and setting ListAdapter before Completing AsyncTask So Try to Set ListAdapter after Completing AsyncTask
So add these
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
lines in onPostExecute method instead of onCreate Method
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
m_adapter = new OrderAdapter(YourActivity.this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}