In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#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 + "\n");
Log.d("Response: ", "> " + 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);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.
Before trying to get a row of data from a MySQL server, I used a column and managed to get that into a listView through tutorials. But for getting data in a row from a table, I couldn't manage to put it into a listView.
So what I'm trying to do is put "shift" from background worker into a listview.
PHP SQL query:
$sql = "SELECT id, employee, hours FROM selected_shifts WHERE day = '$day';";
Navigation drawer from Main Activity:
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
if (items[0].equals(mExpandableListTitle.get(childPosition))) {
String day = "Monday";
OnChoice(day);
} else if (items[1].equals(mExpandableListTitle.get(childPosition))) {
String day= "Tuesday";
OnChoice(day);
} else if (items[2].equals(mExpandableListTitle.get(childPosition))) {
String day = "Wednesday";
OnChoice(day);
} else if (items[3].equals(mExpandableListTitle.get(childPosition))) {
String day = "Thursday";
OnChoice(day);
} else if (items[4].equals(mExpandableListTitle.get(childPosition))) {
String day = "Friday";
OnChoice(day);
}
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
public void OnChoice(String day) {
String type = "choice";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, day);
}
Background worker(getting data from MySQL server):
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String shifts_url = "***PHP LINK***";
if(type.equals("choice")) {
try {
String day = params[1];
URL url = new URL(shifts_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("day","UTF-8")+"="+URLEncoder.encode(day,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String shift="";
String line="";
while((line = bufferedReader.readLine())!= null) {
shift += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return shift;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
#Override
protected void onPostExecute(String shift) {
//Toast the data as json
Toast.makeText(context, shift, Toast.LENGTH_LONG).show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
EDIT
Putting it into ListView:
public void onTaskCompleted(String shift) {
try {
loadIntoListView(shift);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void loadIntoListView(String shift) throws JSONException {
JSONArray jsonArray = new JSONArray(shift);
String[] list = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
list[i] = obj.getString(shift);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
So what you want to do to pass the shift back is use a custom "Listener".
Create this
public interface TaskListener {
void onTaskCompleted(String shift);
}
And on your BackgroundWorker change the constructor as follow:
TaskListener taskListener;
BackgroundWorker(Context context, TaskListener taskListener){
this.context = context;
this.taskListener = taskListener;
}
Then on the onPostExecute method, do a taskListener.onTaskCompleted(shift).
When you call the BackgroundWorker constructor pass this as the second parameter:
BackgroundWorker backgroundWorker = new BackgroundWorker(this, this)
Then implement TaskListener on your Main and implement the method.
Something like this:
... MainActivity implements TaskListener
...
#override
onTaskCompleted(String shift) {
// You have your `shift` here to do with as you please
}
At your onPostExecute() you should add the "shift" to a dataSet in your adapter.
The main part of this question is, when I run this code, the TextViews latitudeTextView and longitudeTextView get updated correctly, therefore the global variable are being change to the correct values. But when i try to access them again after going an asynctask, they are set to 0.0, 0.0? Shouldn't they stay as the same values after onPostExecute ends?
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Weather>{
private static final String GOOGLE_CONVERTER = "https://maps.googleapis.com/maps/api/geocode/json";
private static final String GOOGLE_KEY = "AIzaSyBtt8yaXoRvLTkJHUXrhl5pQaLxomReHIA";
public static final int LOADER_ID = 0;
String jsonResponse = "";
private String address;
private TextView latitudeTextView;
private TextView longitudeTextView;
private TextView summaryTextView;
private TextView tempuratureTextView;
private TextView timezoneTextView;
private TextView textTextView;
private double latitude = 0.0;
private double longitude = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView = (TextView) findViewById(R.id.latitude);
longitudeTextView = (TextView) findViewById(R.id.longitude);
summaryTextView = (TextView) findViewById(R.id.summaryTextView);
tempuratureTextView = (TextView) findViewById(R.id.temperatureTextView);
timezoneTextView = (TextView) findViewById(R.id.timezoneTextView);
textTextView = (TextView) findViewById(R.id.test);
final EditText addressEditText = (EditText) findViewById(R.id.edittext_address);
Button submitButton = (Button) findViewById(R.id.submit_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
address = addressEditText.getText().toString().trim();
address = "5121+Paddock+Court+Antioch+Ca+94531";
String fullUrl = GOOGLE_CONVERTER + "?address=" + address + "&key=" + GOOGLE_KEY;
new getlongAndLat().execute(fullUrl);
textTextView.setText(latitude + "");
//Log.e("TAG", latitude + " " + longitude);
// getLoaderManager().initLoader(LOADER_ID, null, MainActivity.this);
}
});
}
#Override
public android.content.Loader<Weather> onCreateLoader(int id, Bundle args) {
return new WeatherAsyncTaskLoader(this, latitude, longitude);
}
#Override
public void onLoadFinished(android.content.Loader<Weather> loader, Weather data) {
}
#Override
public void onLoaderReset(android.content.Loader<Weather> loader) {
}
public class getlongAndLat extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
Log.e("TAG", connection.getResponseCode() + "");
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
//trouble closing input stream
e.printStackTrace();
}
}
}
extractJsonResponse(jsonResponse);
return null;
}
#Override
protected void onPostExecute(String s) {
latitudeTextView.setText(latitude + "");
longitudeTextView.setText(longitude + "");
super.onPostExecute(s);
}
}
private void extractJsonResponse(String jsonResponse) {
try {
JSONObject rootJsonObject = new JSONObject(jsonResponse);
JSONArray nodeResultsArray = rootJsonObject.getJSONArray("results");
JSONObject nodeFirstObject = nodeResultsArray.getJSONObject(0);
JSONObject nodeGeometryObject = nodeFirstObject.getJSONObject("geometry");
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
In your code doInBackground(), you are calling extractJsonResponse() method before return statement. In extractJsonResponse(), you are getting lat and long and setting those to Global variables as mentioned in your code
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
I am sure that you are getting those zero values from Json object. You need to verify this thing at your end
When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.
public class DetailsActivity extends Activity {
private ArrayAdapter<Imageclass> adapter;
ArrayList<String> imageselect = new ArrayList<String>();
private ArrayList<Imageclass> array1;
private ArrayList<Imageclass> list = new ArrayList<Imageclass>();
//private ArrayList<Imageclass> array;
ArrayList<String> imagetest = new ArrayList<String>();
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
int id;
int pid;
int val;
int val_new;
double lati;
double longi;
String imagename;
//private ImageView image;
//public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
ImageView image;
static Bitmap bm;
ProgressDialog pd;
BitmapFactory.Options bmOptions;
public class test extends AsyncTask<Void, Void, InputStream>{
ArrayList<Imageclass> str;
private DetailsActivity activity;
public test(DetailsActivity activity){
this.activity = activity;
}
#Override
protected InputStream doInBackground(Void... params) {
//String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id);
Log.e("Checking id",""+id);
String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id);
URL url;
try {
stringURL=stringURL.replaceAll(" ", "%20");
url = new URL(stringURL);
Log.e("URL",""+ url);
URLConnection conn= url.openConnection();
Log.e("URLConnection",""+conn );
InputStream stream= conn.getInputStream();
Log.e("URLStream",""+stream );
return stream;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("Excepiton", ""+e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
Log.e("Result", ""+result);
StringBuilder builder = new StringBuilder();
Log.e("Builder", ""+ builder);
BufferedReader reader = new BufferedReader(new InputStreamReader(result));
Log.e("Reader", ""+ reader);
String line = null;
try {
while((line = reader.readLine()) != null) {
Log.e("Result11", ""+ builder.append(line));
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String jsonString = builder.toString();
Log.e("image", jsonString);
try {
JSONObject rootObject = new JSONObject(jsonString);
Log.e("JSOnObject",""+ rootObject);
JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images");
//array1.clear();
ArrayList<String> imagearray = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
Imageclass imageinstance = new Imageclass();
JSONObject object = (JSONObject) jsonArray.get(index);
Log.e("Image test", "" + object);
imageinstance.image = object.getString("file_name");
//### this contain the image name
Log.e("Imageinstance.image",""+imageinstance.image);
imagename = imageinstance.image;
imagearray.add(imageinstance.image);
array1.add(imageinstance);
//array1.add(imagearray);
Log.e("array1","test"+array1);
}
Log.e("IMAGES",""+array1);
activity.setlist(array1);
}
catch (JSONException e) {
Log.e("this Exception",""+ e);
e.printStackTrace();
}
catch (Exception e) {
Log.e("NULL","NULL"+e);
}
// adapter.notifyDataSetChanged();
}
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... param) {
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
Log.e("inside img",""+Finalname);
Log.e("inside img_val",""+val);
Log.e("Check","check"+imageUrl);
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
Log.e("Test","Test"+ imageUrl.equals(""));
image.setImageBitmap(bm);
} else {
Toast.makeText(DetailsActivity.this,
"test", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
String Finalname;
//String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname;
public void setlist(ArrayList<Imageclass> list)
{
this.list= list;
Log.e("LIST",""+ this.list);
String imagename1 = list.toString();
Log.e("image new value",""+imagename1);
this.list= list;
Log.e("testing",""+ this.list);
for (int i=0; i < list.size(); i++)
{
Log.e("new check",""+list.get(i));
//String test2= list.get(i).toString();
imagetest.add(list.get(i).toString());
Finalname = list.get(i).toString();
getimage_name(Finalname);
Log.e("Come",""+list.get(i).toString());
Log.e("Finalname",""+Finalname);
}
}
//String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
private void getimage_name(String finalname2) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
image = (ImageView)findViewById(R.id.imageView2);
// getMenuInflater().inflate(R.menu.details);
//R.id.textDetailPlace
textView1 = (TextView)findViewById(R.id.textDetailPlace);
textView2 = (TextView)findViewById(R.id.textDetailAddress );
textView3 = (TextView)findViewById(R.id.textCapacity);
// textView4 = (TextView)findViewById(R.id.textDetailContactNo);
textView5 = (TextView) findViewById(R.id.textViewDescription);
textView1.setText(getIntent().getExtras().getString("test"));
textView2.setText(getIntent().getExtras().getString("test2"));
textView3.setText(getIntent().getExtras().getString("test3"));
//textView4.setText(getIntent().getExtras().getString("test4"));
textView5.setText(getIntent().getExtras().getString("test5"));
id = getIntent().getExtras().getInt("test6");
Log.e("ID value",""+id);
pid = getIntent().getExtras().getInt("test7");
Log.e("PID value",""+pid);
lati = getIntent().getExtras().getDouble("testlat");
Log.e("long",""+lati);
longi = getIntent().getExtras().getDouble("testlong");
Log.e("long",""+longi);
val=pid;
Log.e("val",""+val);
ActionBar actionBar = getActionBar();
actionBar.hide();
pd = ProgressDialog.show(DetailsActivity.this, null, null,true);
pd.setContentView(R.layout.progress);
array1 = new ArrayList<Imageclass>();
//new test(this).execute();
new test(this).execute();
here test asynctask is called
Log.e("JUST","CHECK");
Log.e("JUST","CHECK");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here imageDownload asynctask is getting called::
new ImageDownload().execute();
Log.e("imagename",""+imagename);
}
}
here before ImageDownload is start executing before test async task is complete
and i am not able to get the status of the task can u tell how it is done
whatever i understood from this you want to execute your ImageDownload thread after the task thread,so start the ImageDownload Thread from the onPostExecute() of your task thread
When executing an async task a new thread is started, but your current thread keeps running. It immediately runs into your thread.sleep(1000) just after starting test.async.
It looks like your doing some internet downloading in test.async, and as you might have guessed, it takes longer than 1000 milliseconds (1 second). This means 1 second later, your other async is starting, before the first completed.
I assume you want to stagger them. In the postExecute of the first async, you can spawn the second async. A more stylistically correct method would be to implement an interface on your activity that takes a callback on Async completion, then upon receiving the call back, launch your second async.
An example of how to structure this is below.
interface AsyncCallback{
void onAsyncComplete();
}
public class ExampleActivity extends Activity implements AsyncCallback {
....
public void launchFirstAsync(){
new Task(this).execute();
}
#Override
public void onAsyncComplete() {
//todo launch second asyncTask;
}
}
class Task extends AsyncTask<Void, Void, Void>{
AsyncCallback cb;
Task(AsyncCallback cb){
this.cb = cb;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
cb.onAsyncComplete();
}
}
Have a look here, This Help me for same..Pass your url to GetTemplateImageController and get the result in Bitmap array
GetTemplateImageController Class:
public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]>
{
Context mcontext;
private ProgressDialog pDialog;
public static String[] imageurls;
public static Bitmap bm[]=new Bitmap[15];
// URL to get JSON
private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?";
private static final String TEMPLATE = "Template_images";
private static final String IMAGEURLS = "tempimagename";
// JSONArray
JSONArray loginjsonarray=null;
//result from url
public GetTemplateImageController(Context c) {
this.mcontext=c;
}
protected void onPreExecute() {
// Showing progress dialog
super.onPreExecute();
pDialog=new ProgressDialog(mcontext);
pDialog.setMessage("Loading");
pDialog.setCancelable(true);
pDialog.setIndeterminate(true);
pDialog.show();
}
protected Bitmap[] doInBackground(String... arg) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("templateMasterId",arg[0].toString()));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params);
Log.d("Response: ", ">"+jsonstr);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(TEMPLATE);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(IMAGEURLS);
}
for(int i=0;i<imageurls.length;i++){
bm[i]=DownloadImage(imageurls[i]);
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return bm;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Integer result) {
// Dismiss the progress dialog
pDialog.dismiss();
if(result != null)
Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show();
//}
}
}
ServiceHandler Class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity=null;
HttpResponse httpResponse=null;
// Checking http request method type
if(method==POST){
HttpPost httpPost=new HttpPost(url);
if(params!=null)
{
//adding post params
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse=httpClient.execute(httpPost);
}
else if(method==GET)
{
// appending params to url
if(params!=null)
{
String paramString=URLEncodedUtils.format(params, "utf-8");
url +="?"+paramString;
}
HttpGet httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
}
Over time there have been several changes to the way Android deals with AsyncTasks that run concurrently. In very old Android versions (pre-1.6 afaik) multiple AsyncTasks were executed in sequence. That behavior has been changed to run the AsyncTasks in parallel up until Android 2.3. Beginning with Android 3.0 the the Android team decided that people were not careful enough with synchronizing the tasks that run in parallel and switched the default behavior back to sequential execution. Internally the AsyncTask uses an ExecutionService that can be configured to run in sequence (default) or in parallel as required:
ImageLoader imageLoader = new ImageLoader( imageView );
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );