Reputation: 103
I have a main activity class from which I call two async tasks to load external (from url) data. I want to display a progress bar or a simple Toast message, but I cant retrieve the application context.
This is the async class code:
public class URLDataReader extends AsyncTask<URL, Void, String> {
@Override
protected void onPreExecute() {
// here where I need the context
}
String result = null;
@Override
protected String doInBackground(URL... params) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
params[0].openStream()
)
);
result = reader.readLine();
}catch(IOException e){
e.printStackTrace();
}
return result;
}
}
This is the home activity class code:
public class Home extends ActionBarActivity{
Context context = getApplicationContext();
public class Post{
String id;
String title;
String description;
String release;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getRelease() {
return release;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setRelease(String release) {
this.release = release;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String result = null;
ArrayList<Post> focusOn = new ArrayList<Post>();
try {
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLDataReader reader = new URLDataReader();
result = reader.execute(address).get();
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}catch (IOException e){
e.printStackTrace();
} catch(InterruptedException e){
e.printStackTrace();
} catch (ExecutionException e){
e.printStackTrace();
}
try {
JSONObject obj = new JSONObject(result);
String success = (String) obj.getString("success");
JSONArray records = obj.getJSONArray("records");
for(int i = 0; i < records.length(); i++) {
Post tmp = new Post();
tmp.setId(records.getJSONObject(i).getString("id"));
tmp.setTitle(records.getJSONObject(i).getString("title"));
tmp.setDescription(records.getJSONObject(i).getString("contents"));
tmp.setRelease(records.getJSONObject(i).getString("data_post"));
focusOn.add(tmp);
}
}catch (JSONException e){
e.printStackTrace();
}
//wrapper
LinearLayout container = (LinearLayout)findViewById(R.id.wrapper);
for(int i = 0; i < focusOn.size(); i++){
//item
LinearLayout item = new LinearLayout(getApplicationContext());
container.addView(item);
item.setOrientation(LinearLayout.HORIZONTAL);
//image
Bitmap imageHandler = null;
URL address = null;
try {
address = new URL("http://www.youth-stories.com/public/admin/CH_FocusOn/images/"+focusOn.get(i).getId()+"_thumb2.jpg");
URLImageReader reader = new URLImageReader();
imageHandler = reader.execute(address).get();
}catch(MalformedURLException e){
e.printStackTrace();
}catch (ExecutionException e){
e.printStackTrace();
}catch(InterruptedException e){
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(),address.toString(),Toast.LENGTH_LONG).show();
ImageView asset = new ImageView(getApplicationContext());
//asset.setImageResource(R.drawable.ic_launcher);
asset.setImageBitmap(imageHandler);
item.addView(asset);
LinearLayout.LayoutParams imgSettings = new LinearLayout.LayoutParams(300,300);
asset.setLayoutParams(imgSettings);
//inside
LinearLayout contents = new LinearLayout(getApplicationContext());
contents.setOrientation(LinearLayout.VERTICAL);
item.addView(contents);
//title
TextView title = new TextView(getApplicationContext());
title.setText(focusOn.get(i).getTitle());
title.setTextAppearance(this, R.style.title);
contents.addView(title);
//description
TextView description = new TextView(getApplicationContext());
description.setText(focusOn.get(i).getDescription());
description.setTextAppearance(this, R.style.description);
contents.addView(description);
//date
TextView date = new TextView(getApplicationContext());
date.setText(focusOn.get(i).getRelease());
date.setTextAppearance(this, R.style.description);
contents.addView(date);
}
}
}
The context is now passed correctly and I can write a simple Toast but when I try to display progress dialog app crashes. This is the code modified:
public class URLImageReader extends AsyncTask<URL, Void, Bitmap> {
Context context = null;
ProgressDialog dialog = null;
public URLImageReader(Context context){
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading, please wait.");
dialog.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected Bitmap doInBackground(URL... params) {
Bitmap image = null;
try {
URL url= params[0];
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e){
e.printStackTrace();
}
return image;
}
}
Upvotes: 0
Views: 74
Reputation: 8134
First, Assign context
inside onCreate()
like:
`context = this;`
And, define constructor
with context
for your asynctask
class
then pass it from where you call it
`URLDataReader reader = new URLDataReader(context);`
and in your URLDataReader.java
Context contextAsynctask;
public URLDataReader(Context context)
{
this.contextAsynctask = context;
}
forgot to write the part where you declare context
in your Asynctask
class
Upvotes: 0
Reputation: 132992
I want to display a progress bar or a simple Toast message, but i cant retrieve the application context
Use URLDataReader
class constructor for getting Context to show Toast and ProgressBar:
1. Create a constructor in URLDataReader
class which take Context as parameter :
private Context mContext;
public URLDataReader(Context mContext){
this.mContext=mContext;
}
2. From Home
Activity create object of URLDataReader
class :
URLDataReader reader = new URLDataReader(Home.this);
Now use mContext
in on onPreExecute
to show progress bar.
NOTE:
Here
imageHandler = reader.execute(address).get();
Calling get()
method which stop execution of current Thread until doInBackground
method execution not complete.
imageHandler = reader.execute(address);
No need to call get()
method if want to show progress bar just call execute method and use onPostExecute
for processing doInBackground
method response
Upvotes: 1
Reputation: 3111
Send the context in the Constructor of URLDataReader such that in your onCreate method in Home class
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLDataReader reader = new URLDataReader(context);
result = reader.execute(address).get();
Then in URLDataReader class
void URLDataReader (Context _context) {
this.context = _context; // declare a global variable called context in your URLDataReader class
}
Upvotes: 0