how to fetch first image without click fetch image button
click to view image
this code work fine but on click fetch image button but i want fetch image with out click fetch images button i want to remove this button
Public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
You can trigger it in onCreate(),but you must not run it on UI thread,for it might be a time-consuming operation.Read Specifying the Code to Run on a Thread to help,
you might add the following block in your onCreate() method:
new Runnable() {
#Override
public void run() {
getAllImages();
}
}.run();
Related
I'm Having difficulty populating TextViews from my SQL Database. I have one column populating a spinner and then I want the Two Textviews to be populated by MySQL Columns from the same row of the spinner selection.
I cannot find the correct code to add to the OnSelectedItem portion.
MainActivity.java
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
Context c;
TextView colorDensity;
Spinner colorSpinner= findViewById(R.id.colorSpinner);
ArrayList<String> colors=new ArrayList<>();
final static String urlAddress = "http://www.burtkuntzhandjobs.org/dbcolors.php";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Downloader(MainActivity.this,urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(this,"Select Color", Toast.LENGTH_SHORT).show();
}
}
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setIu(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
Spinner colorSpinner;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, Spinner colorSpinner) {
this.c = c;
this.urlAddress = urlAddress;
this.colorSpinner = colorSpinner;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching");
pd.show();
}
#Override
protected String doInBackground(Void...params) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s == null) {
Toast.makeText(c,"Unable to Retrieve",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Success",Toast.LENGTH_SHORT).show();
DataParser parser=new DataParser(c,colorSpinner,s);
parser.execute();
}
}
private String downloadData() {
HttpURLConnection con= (HttpURLConnection) Connector.connect(urlAddress);
if(con == null) {
return null;
}
InputStream is = null;
try {
is = new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer response=new StringBuffer();
if(br != null){
while ((line=br.readLine()) !=null) {
response.append(line+"\n");
}
br.close();
} else {
return null;
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null){
try{
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Make following changes & add required code,
1. Remove Spinner colorSpinner= findViewById(R.id.colorSpinner); from class variable.
2. Add Spinner colorSpinner= findViewById(R.id.colorSpinner); in onCreate` method.
Look this spinet,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
Spinner colorSpinner= findViewById(R.id.colorSpinner);
new Downloader(this, urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
3. Access colors list from DataParser class,
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
private static ArrayList<Colors> colorsList=new ArrayList<>(); // add this line
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setUi(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
colorsList.add(s); // add this line
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
public static List<Colors> getColorsList() { // add this method
return colorsList;
}
}
4. Set density accordingly in onItemSelected() method of activity class.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<Colors> colorsList = DataParser.getColorsList();
colorDensity.setText(colorsList.get(position).getDensity());
}
I have declared a private field in the MainActivity Class with getter and setter method. Now I want to setText from another class in this field. But after running the device the app is crushing. I want to fetch some json data by using this code. I am not getting how to call this field from another class and how to set the value to run the app smoothly. My code looks like this.
public class MainActivity extends AppCompatActivity {
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit=(Button)findViewById(R.id.btnHit);
tvData=(TextView)findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONTask jsonTask=new JSONTask("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt"); //error showing this cannot be applied
jsonTask.execute();
}
});
}
The another class is
public class JSONTask extends AsyncTask<String,String,String>{
private TextView tvData;
public JSONTask(TextView tvData) {
this.tvData =tvData;
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
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);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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 result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
Make your AsyncTask like this:
class JSONTask extends AsyncTask<String ,String,String>{
private TextView textView;
public JSONTask(TextView textView) {
this.textView = textView;
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
}
now call this class from MainActivity
JSONTask jsonTask = new JSONTask(yourTextView);
jsonTask.execute();
Hope it will work for you .
#override
protected void onPostExecute(String result){
super.onPostExecute(result);
new MainActivity().setTvData().setText(result);
Use setTvData().setText() to set the value if you only one data in your json string .
I need to build an android app for my final year project, (i am new to android development). Is there any idea to minimize the code or maybe separate into different classes.
I want to make my main activity shorter and cleaner for maintenance, and preferably if it can be coded using MVC architecture. There will be more UI components added later.
Thank you for ur attention.
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button)findViewById(R.id.find_button);
json_output = (TextView)findViewById(R.id.json_output);
user_origin = (EditText)findViewById(R.id.user_origin);
user_destination = (EditText)findViewById(R.id.user_destination);
find_button.setOnClickListener(new View.OnClickListener(){
String origin;
String new_origin;
String destination;
String new_user_destination;
#Override
public void onClick(View v){
origin = user_origin.getText().toString();
new_origin = origin.replaceAll(" ", "+");
destination = user_destination.getText().toString();
new_user_destination = destination.replaceAll(" ", "+");
String link = "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
//json_output.setText(link);
new JSONTask().execute(link);
}
});
}
public class JSONTask extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... params){
HttpURLConnection connection = null;
BufferedReader reader = null;
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 final_json = buffer.toString();
return buffer.toString();
} catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException 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 result){
super.onPostExecute(result);
json_output.setText("result:" +result);
}
}
}
You can separate your JSONTask as a simple class,and execute its task,then define an interface in this class to pass some message or data should be handled by other class,and add a parameter type is this interface for constructor and save it as a field.like this:
public class JSONTask extends AsyncTask<String,String,String>{
private OnHandleResult mResult;
private String[] mParams;
public JSONTask(OnHandleResult onHandleResult,String... params){
this.mResult = onHandleResult;
this.mParams = params;
}
protected String doInBackground(String... params){
//params is empty,get params from this.mParams
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
//json_output.setText("result:" +result);
this.mResult.handleResult(result);
}
public static interface OnHandleResult{
void handleResult(final String result);
}
}
then let your activity implement interface onHandleResult,and hanlde result:set text to textview:
public class MainActivity extends AppCompatActivity implements JSONTask.OnHandleResult{
void handleResult(final String result){
json_output.setText("result:" +result);
}
}
and execute task like this:
new JSONTask(this,link).execute();
Usually it's good practise to have 1 class per file.
You can make your MainActivity a bit more readable
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button) findViewById(R.id.find_button);
json_output = (TextView) findViewById(R.id.json_output);
user_origin = (EditText) findViewById(R.id.user_origin);
user_destination = (EditText) findViewById(R.id.user_destination);
String link = build_link(user_origin, user_destination);
MyListener l = new MyListener(link);
find_button.setOnClickListener(l);
}
private String build_link(EditText user_origin, EditText user_destination) {
String origin = user_origin.getText().toString();
String new_origin = origin.replaceAll(" ", "+");
String destination = user_destination.getText().toString();
String new_user_destination = destination.replaceAll(" ", "+");
return "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
}
by isolating your listener's implementation:
public class MyListener implements View.OnClickListener {
String link;
public MyListener(String link) {
this.link = link;
}
#Override
public void onClick(View v) {
new JSONTask().execute(link);
}
Ok, I have a custom view which plays gifs from the internet. Therefor I need to add an url to my view to download the gif. But I can't seem to update my custom view inside my asynctask. I need to add an url string to my custom view gifView.setUrl(). It works in the onCreate Class but it gives me null in asynctask.
Oncreate class
GifView gifView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
id = extras.getInt("id");
String idStr = String.valueOf(id);
String extension = extras.getString("extension");
if(extension.equals(".gif")){
setContentView(R.layout.activity_post_gif);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gifView = (GifView)findViewById(R.id.gifview);
titleStr = (TextView)findViewById(R.id.titleTXT);
postInfo = (TextView)findViewById(R.id.infoTXT);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//the url
new getJsonInfoGif().execute("http://www.website.com/jsonApi");
}else{
Asynctask
public class getJsonInfoGif extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("loading post...");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
return GET(strings[0]);
}
#Override
protected void onPostExecute(String res) {
try {
JSONObject jsonObject = new JSONObject("{'postinfo':[" + res + "]}");
JSONArray jsonArray = jsonObject.getJSONArray("postinfo");
JSONObject obj = jsonArray.getJSONObject(0);
//post title
titleStr.setText(obj.getString("name"));
//category and maker full name
//large image
JSONObject imgObj = obj.getJSONObject("thumbnails");
gifView.setUrl("http://www.website.com/my.gif");
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
GifView.java
public void setUrl(String urlStr){
this.urlStr = urlStr;
invalidate();
requestLayout();
}
public String getUrl(){
return this.urlStr;
}
public void init(final Context context)throws IOException{
setFocusable(true);
movie = null;
movieWidth = 0;
movieHeight = 0;
movieDuration = 0;
final Thread thread = new Thread(new Runnable() {
#Override
public void run(){
try{
Log.d("DEBUG", "URL" + urlStr);
URL url = new URL(urlStr);
try {
HttpURLConnection http = (HttpURLConnection) url.openConnection();
inputStream = http.getInputStream();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
movie = Movie.decodeStream(inputStream);
movieWidth = movie.width();
movieHeight = movie.height();
movieDuration = movie.duration();
((PostActivity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
invalidate();
requestLayout();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
thread.start();
}
Here is the Log from the url, it gives me null if I add the url inside my asynctask in Activity.
11-07 14:41:58.821 5674-6076/svenmobile.tools.showcase D/DEBUGļ¹ URLnull
What I want to know is what the problem is and how to solve it if possible.
Thanks in advance, Sven
Maybe you called init() before setUrl().
You can pass it the url in the contructor, or public void init(final Context context, String urlStr)throws IOException{
I also suggest you to move all that network code to doInBackground
Cannot display images.. unless putting the adding code in the callback function. But because i ve to cycle draw operation, ive just used the assignment
imageHandler = image; it seems to not work
activity class:
public class Home extends ActionBarActivity implements OnTaskComplete{
public Bitmap imageHandler;
#Override
public void callBackFunction(Bitmap image) {
imageHandler = image;
}
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);
Context context = this;
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(context);
result = reader.execute(address).get();
}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(context,this);
reader.execute(address);
}catch(MalformedURLException e){
e.printStackTrace();
}
ImageView asset = new ImageView(getApplicationContext());
asset.setImageBitmap(imageHandler);
//Toast.makeText(getApplicationContext(),asset.toString(),Toast.LENGTH_LONG).show();
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);
}
}
}
URLImageReader Asynctask
public class URLImageReader extends AsyncTask<URL, Void, Bitmap> {
Context context = null;
private OnTaskComplete mlistener;
public URLImageReader(Context context, OnTaskComplete mlistener){
this.context = context;
this.mlistener = mlistener;
}
#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;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mlistener.callBackFunction(bitmap);
}
interface:
public interface OnTaskComplete{
void callBackFunction(Bitmap image);
}
You on task complete interface seems extraneous, just pass the imageview to it instead:
public class URLImageReader extends AsyncTask<URL, Void, Bitmap> {
private final Context context;
private final ImageView mImageView;
public URLImageReader(ImageView imageView){
this.context = imageView.getContext();
this.mImageView = imageView;
}
#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;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (mImageView != null){
mImageView.setImageBitmap(bitmap);
}
}
}
Then to call it,
// see final notes below about using this (the activity), lets create the imageview before we call URLImageReader constructor
ImageView asset = new ImageView(this);
try {
address = new URL("http://www.youth-stories.com/public/admin/CH_FocusOn/images/"+focusOn.get(i).getId()+"_thumb2.jpg");
URLImageReader reader = new URLImageReader(asset);
reader.execute(address);
}catch(MalformedURLException e){
e.printStackTrace();
}
Also, don't use the application context to create views, use the Activity context instead.