'How to change a variable of an AsyncTask in an activity from another activity by a button click in android studio?
I am using an AsyncTask in my MainActivity in Android Studio, where in doInBackground method, I have an URL, that I want to be changed from a list view item, which is loaded to a listView in HomeActivity.
Is it possible to change the value of the URL to the value of the list item? So I will get a Unique URL every time I click on a list item.
My MainActivity:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MainActivity extends AppCompatActivity {
ListView lvRss;
ArrayList<String> titles;
ArrayList<String> links;
ArrayList<NewsInformation> news =new ArrayList<>();
private DatabaseHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvRss = (ListView) findViewById(R.id.lvRss);
titles = new ArrayList<String>();
links = new ArrayList<String>();
db = new DatabaseHandler(this);
if(isNetworkAvailable(this)){
new ProcessInBackground().execute();
}else {
try {
db.open();
ArrayList<NewsInformation> news = db.getAllNews();
CustomAdapter adapter = new CustomAdapter(this,news);
lvRss.setAdapter(adapter);
db.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public class ProcessInBackground extends AsyncTask<Integer, Void, Exception> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
Exception exception = null;
@Override
protected void onPreExecute() {
progressDialog.setMessage("Fetching Latest News!");
progressDialog.show();
}
@Override
protected Exception doInBackground(Integer... integers) {
try {
// rss feed site here
URL url = new URL("https://moxie.foxnews.com/feedburner/sports.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getInputStream(url));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
//// fetch every node item in RSS and create news_item list
for (int i = 0; i < nodeList.getLength(); i++) {
NewsInformation news_item = new NewsInformation();
Node node = nodeList.item(i);
Element parentItem = (Element) node;
NodeList links = parentItem.getElementsByTagName("link");
Element element_link = (Element) links.item(0);
NodeList element_link_childNodes = element_link.getChildNodes();
news_item.link = element_link_childNodes.item(0).getNodeValue();
NodeList titles = parentItem.getElementsByTagName("title");
Element element_title = (Element) titles.item(0);
NodeList element_title_childNodes = element_title.getChildNodes();
news_item.title = element_title_childNodes.item(0).getNodeValue();
NodeList pubDates = parentItem.getElementsByTagName("pubDate");
Element element_pubDate = (Element) pubDates.item(0);
NodeList element_pubDate_childNodes = element_pubDate.getChildNodes();
news_item.pubDate = element_pubDate_childNodes.item(0).getNodeValue();
NodeList description = parentItem.getElementsByTagName("description");
Element element_description = (Element) description.item(0);
if(element_description !=null){
NodeList element_description_childNodes = element_description.getChildNodes();
news_item.description = element_description_childNodes.item(0).getNodeValue();
}else{
news_item.description =" ";
}
NodeList image = parentItem.getElementsByTagName("media:group");
Element element_image = (Element) image.item(0);
NodeList image_content = element_image.getElementsByTagName("media:content");
Element image_content_element = (Element) image_content.item(0);
news_item.image = image_content_element.getAttribute("url");
// Log.e("IMAGE:",news_item.image);
news.add(news_item);
//////////////////////////////////////////////////////////////////////////////////////////////
}
} catch (MalformedURLException e) {
exception = e;
Log.e("IMAGE:","1");
} catch (IOException e) {
exception = e;
Log.e("IMAGE:","2");
} catch (ParserConfigurationException e) {
e.printStackTrace();
Log.e("IMAGE:","3");
} catch (SAXException e) {
e.printStackTrace();
Log.e("IMAGE:","4");
}
return null;
}
@Override
protected void onPostExecute(Exception s) {
super.onPostExecute(s);
CustomAdapter adapter = new CustomAdapter(getBaseContext(),news);
lvRss.setAdapter(adapter);
//////////// after fetching data insert to db///////////////////////////////////////////
try {
db.open();
for (int i = 0; i < news.size(); ++i) {
db.insertNewsInfo(news.get(i));
}
db.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
/////////////////////////////////////////////////////////////////////////////
progressDialog.dismiss();
}
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
In this class I want the value of URL url = new URL("https://moxie.foxnews.com/feedburner/sports.xml"); to be changed.
My HomeActivity
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class Home extends AppCompatActivity {
ListView lst1;
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().getAttributes().windowAnimations = R.style.Fade;
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
setContentView(R.layout.activity_home);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AddWebsiteActivity.class);
view.getContext().startActivity(intent);}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
this.getRecords();
}
private void getRecords() {
SQLiteDatabase db = openOrCreateDatabase("WebsiteDB", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lvRssHome);
final Cursor c = db.rawQuery("select * from records", null);
int id = c.getColumnIndex("id");
int name = c.getColumnIndex("name");
int address = c.getColumnIndex("address");
titles.clear();
arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, titles);
lst1.setAdapter(arrayAdapter);
final ArrayList<WebsitesInformation> stud = new ArrayList<WebsitesInformation>();
if (c.moveToFirst()) {
do {
WebsitesInformation stu = new WebsitesInformation();
stu.id = c.getInt(id);
stu.name = c.getString(name);
stu.address = c.getString(address);
stud.add(stu);
titles.add(c.getString(id) + " \t" + c.getString(name));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.invalidateViews();
}
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
});
}
}
Here I want the address value in the listView to be transferred to the URL value in MainActivity
Solution 1:[1]
First of all why AsyncTask? Its already deprecated and comes with many issues. https://developer.android.com/reference/android/os/AsyncTask
You can simply use coroutines. its super easy and less complicated. or you can even use rxjava.
Secondly, your AsyncTask is designed in a wrong way. Do the following.
- Define your async task to take strings
public class ProcessInBackground extends AsyncTask<String, Void, Exception> {
- then your
doInBackgroundwill look something like this:
@Override
protected Exception doInBackground(String... strings) {
URL url = new URL(strings[0]);
}
- execute the asyncTask by calling it this way.
new ProcessInBackground().execute("pass_your_url_from_list");
Just dont use AsyncTask.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
