how to set javafx Togglebutton in javafx Tableview to correct image based on boolean from sqlite database(JDBC) - image

I am working on a program that is going to allow users to select/add sounds as favorites
via a toggle button with an image in a javafx tableview tablecell and set the status of the sound in the database(the updating of the favorite status in the database works) however the updating of the image only partially works.
when pressing the toggle button the image updates correctly as does the database
initial loading
first 10 records before any favorite selection
after button is pressed
database
but the problem comes when I stop and restart the program because I wind up with none of the buttons selected (sound id 5 should be)
here is the code for the database data loading
public void getSounds() {
soundFilelist.removeAll(soundFilelist);
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");
// add where userId = VerifiedUserId or something simular//
String sql = "SELECT * FROM Sounds Where userId = ? ";
PreparedStatement ps;
ResultSet rs;
ps = conn.prepareStatement(sql);
ps.setInt(1 , User.getUserId());
rs = ps.executeQuery();
while (rs.next()) {
int favoriteStatus;
soundFilelist.add(new Sound(
rs.getInt("SoundId") ,
rs.getString("SoundName") ,
rs.getString("soundPath") ,
rs.getLong("soundDurration") ,
favoriteStatus = rs.getInt("Favorite")));
System.out.println(favoriteStatus);
if(favoriteStatus == 0){
setFavoritesTableButton(0);
}else if(favoriteStatus == 1){
setFavoritesTableButton(1);
}
}
soundBrowser.setItems(soundFilelist);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
the addButtoncell code
(favorite column 2) modified from https://riptutorial.com/javafx/example/27946/add-button-to-tableview
private void addButtonToTable() {
Callback<TableColumn<Sound, Void>, TableCell<Sound, Void>> cellFactory = new Callback<TableColumn<Sound, Void>, TableCell<Sound, Void>>() {
#Override
public TableCell<Sound, Void> call(final TableColumn<Sound, Void> param) {
favoritecell = new TableCell<>() {
private final ToggleButton btn = new ToggleButton();
private Image favoritesImage = new Image("SoundSphere/RegularSizeFavoritesImage.png");
private Image favoriteslPressedImage = new Image("SoundSphere/RegularSizeFavoriteslPressedImage.png");
private ImageView tableViewFavorites = new ImageView();
{
tableViewFavorites.setFitWidth(20);
tableViewFavorites.setFitHeight(20);
btn.setAlignment(Pos.CENTER);
// favoritecell.setAlignment(Pos.CENTER);
btn.setGraphic(tableViewFavorites);
btn.setOnAction((new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
if ((btn.isSelected())) {
Sound sound = getTableView().getItems().get(getIndex());
sound.setSoundId(soundIdColumn.getCellData(sound));
System.out.println("selected SID: "+ sound.getSoundId());
int selectedSoundId2 = sound.getSoundId();
tableViewFavorites.setImage(favoriteslPressedImage);
tableviewFavoriteButtonIsPressed = false;
//addFavorite();
System.out.println("buttonselectedId"+ selectedSoundId);
addFavorite2(selectedSoundId2);
}else{
Sound sound = getTableView().getItems().get(getIndex());
sound.setSoundId(soundIdColumn.getCellData(sound));
int selectedSoundId2 = sound.getSoundId();
tableViewFavorites.setImage(favoritesImage);
tableviewFavoriteButtonIsPressed = true;
removeFavorite2(selectedSoundId2);
}
}
private void removeFavorite2(int selectedSoundId2) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");
String sql = "UPDATE Sounds " +
"SET Favorite = ?"+
// "soundName = ?"+
"Where soundId = ? AND userId = ?";
PreparedStatement ps;
ps = conn.prepareStatement(sql);
ps.setInt(1,0);
ps.setInt(2 , selectedSoundId2);
ps.setInt(3 , User.getUserId());
ps.executeUpdate();
System.out.println("Data has been removed");
}catch(Exception e){
System.out.println("we have a problem with add favorite 2");
e.printStackTrace();
}
}
}));
}
private void addFavorite2(int favoriteSoundId) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");
String sql = "UPDATE Sounds " +
"SET Favorite = ?"+
// "soundName = ?"+
"Where soundId = ? AND userId = ?";
PreparedStatement ps;
ps = conn.prepareStatement(sql);
ps.setInt(1,1);
ps.setInt(2 , favoriteSoundId);
System.out.println(favoriteSoundId);
ps.setInt(3 , User.getUserId());
ps.executeUpdate();
System.out.println("Data has been inserted");
}catch(Exception e){
System.out.println("we have a problem with add favorite 2");
e.printStackTrace();
}
}
#Override
public void updateItem(Void item , boolean empty) {
super.updateItem(item , empty);
if (btn.isSelected() || dbFavorite) {
tableViewFavorites.setImage(tableFavoriteslPressedImage);
setGraphic(btn);
} if (!btn.isSelected() || !dbFavorite) {
tableViewFavorites.setImage(favoritesImage);
setGraphic(btn);
}
}
};
return favoritecell;
}
};
favoritesColumn2.setCellFactory(cellFactory);
soundBrowser.getColumns().add(favoritesColumn2);
}
public boolean setFavoritesTableButton(int favoriteStatus){
if(favoriteStatus == 1) {
dbFavorite = true;
}else if(favoriteStatus == 0){
dbFavorite = false;
}
return dbFavorite;
}
relevant Intializable code
soundNameColumn.setCellValueFactory(new PropertyValueFactory<>("soundName"));
soundPathColumn.setCellValueFactory(new PropertyValueFactory<>("soundPath"));
soundDurationColumn.setCellValueFactory(new PropertyValueFactory<>("soundDurration"));
favoritesColumn.setCellValueFactory(new PropertyValueFactory<>("Favorite"));
addButtonToTable();
getSounds();
I have tried setting the state of the toggle button in the get sounds method and various Booleans but none of my attempts have worked.
thank you for your time and any help
Thomas Gustafson

Related

Getting issue while retrieve location with different location request mode

For retrieve location i have used GoogleAPIClient with FusedLocationProvider API.
These functions are in onCreate() method.
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
gpsChecker();
Full Code
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void gpsChecker() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
AddVisitActivity.this, 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
For run time permissions i did this.
protected void startLocationUpdates() {
if (ActivityCompat.shouldShowRequestPermissionRationale
(AddVisitActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
Snackbar.make(findViewById(android.R.id.content),
"Please Grant Permissions",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(AddVisitActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AddVisitActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, AddVisitActivity.this);
Log.d(TAG, "Location update started ...: ");
}
}
}).show();
} else {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ...: ");
}
}
}
For checking if the GPS enabled or not in setting screen using gpsChecker() with request code 1000 and in onActivityResult() i have done this.
if (requestCode == 1000) {
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
finish();
break;
}
}
While i execute this code in some devices its working and in some device the location request automatically set to Device Only or Battery Saving though i have set mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Note : Mi Note 4, Vivo V9 Pro, Mi Note 5 Pro and some other device getting the issue
So what should i need to change in my code so will it work proper with the High Accuracy?
Finally solved by changing
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
to
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
and change
private static final long INTERVAL = 1000 * 60 * 60;
private static final long FASTEST_INTERVAL = 1000 * 5;
interval time to 30 minutes and fastest interval to 5 seconds means once get location in 5 seconds after then new location will be get in 30 minutes.
Try this solutin with GPS Provider and make sure that your GPS service is ON.
static final int LOCATION_INTERVAL = 1000;
static final float LOCATION_DISTANCE = 10f;
//put this in onCreate();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider, LOCATION_INTERVAL, LOCATION_DISTANCE, this);
if (location != null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
//put this LocationListener after onCreate();
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(String.format("%f, %f", location.getLatitude(), location.getLongitude()), "");
Log.e("Location available", "Location available");
locationManager.removeUpdates(mLocationListener);
} else {
Log.e("Location is null", "Location is null");
}
current_latitude = location.getLatitude();
current_longitude = location.getLongitude();
/* LatLng latLng = new LatLng(current_latitude, current_longitude);
points.add(latLng);
redrawLine();*/
Log.e("current_latitude", String.valueOf(current_latitude));
Log.e("current_longitude", String.valueOf(current_longitude));
if (location.hasSpeed()) {
//progressBarCircularIndeterminate.setVisibility(View.GONE);
String speed = String.format(Locale.ENGLISH, "%.0f", location.getSpeed() * 3.6) + "km/h";
SpannableString s = new SpannableString(speed);
s.setSpan(new RelativeSizeSpan(0.25f), s.length() - 4, s.length(), 0);
txt_current_speed.setText(s);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};

How to show image on imageview using webservices and json

I am using web service for showing image in imageview. But web service image show in SYSTEM.BYTE[] Format. So how to Convert or display the image in imageview in xamarin android application??
Webservice.asmx:
[WebMethod(MessageName = "BindHospName", Description = "Bind Hospital Name Control")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[System.Xml.Serialization.XmlInclude(typeof(GetHospName))]
public string BindHosp(decimal SpecID)
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
List<GetHospName> HospName = new List<GetHospName>();
try
{
ConnectionString();
cmd = new SqlCommand("select b.HID,b.HospName,b.Logo from HospitalRegBasic b inner join HospitalRegClinical c on b.HID=c.HID " +
"where b.EmailActivationCode <> '' and b.EmailActivationStatus = 1 and b.Status = 1 and c.SPEC_ID = #SpecID ", conn);
cmd.Parameters.AddWithValue("#SpecID", SpecID);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var getHosp = new GetHospName
{
HospID = dr["HID"].ToString(),
HospName = dr["HospName"].ToString(),
HospLogo = dr["Logo"].ToString()
};
HospName.Add(getHosp);
}
}
dr.Close();
cmd.Dispose();
conn.Close();
}
catch (Exception)
{
throw;
}
return objJss.Serialize(HospName);
}
Class.cs:
namespace HSAPP
{
class ContListViewHospNameClass : BaseAdapter<GetHospNames>
{
List<GetHospNames> objList;
Activity objActivity;
public ContListViewHospNameClass (Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
this.objList = objMyList;
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public static Bitmap bytesToBitmap(byte[] imageBytes)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
return bitmap;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
byte[] img =item.HospLogo;
Bitmap bitmap = BitmapFactory.DecodeByteArray(img, 0, img.Length);
convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
return convertView;
}
}
}
This is JSON Code:
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
try
{
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString(),JArrayValue[count]["Logo"]);
list.Add(getHospName);
count++;
}
listView.Adapter = new ContListViewHospNameClass(this, list);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
public static void SetImageFromByteArray (byte[] iArray, UIImageView imageView)
{
if (iArray != null && iArray.Length > 0) {
Bitmap bitmap = BitmapFactory.DecodeByteArray (iArray, 0, iArray.Length);
imageView.SetImageBitmap (bitmap);
}
}
That's it. If this is not working, your byte array may not be a valid image.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}

How can I start AsyncTask's doInBackground repeatedly when I start the 'A activity'? [complete]

I make the HttpURLConnection to get data from MySQL (android+jsp+MySQL) in my android's AsyncTask.
when I start 'A activity', the first is OK. I can start doInBackground. but when I start the 'A activity' next, I can't start doInBackgound when I start 'A activity' repeatedly.
I want to start doInBackground whenever I start the 'A activity' repeatedly.
because I get data from MySQL in doInBackground.
I used to "task.cancel(true)" but this not working.
I'm nuwbe in android, please tell me how to start doInBackground repeatedly.
thank advance.
behind is my code.
oncreate code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_inventory);
...........
connectJSP = new getInventoryFromMySQL();
connectJSP.execute();
...........
}
onBackPressed code
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
connectJSP.cancel(true);
super.onBackPressed();
}
}
AsyncTask code
private class getInventoryFromMySQL extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... sId) {
String sResult = "Error";
try {
//URL setting and access
URL url = new URL("http://-----.com/*****.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//setting
conn.setRequestMethod("POST");
// connection values
String sendBicycleName = bicycleName;
String sendBicycleYear = bicycleYear;
//StringBuffer
StringBuffer buffer = new StringBuffer();
buffer.append("sendBicycleName").append("=").append(sendBicycleName).append("&");
buffer.append("sendBicycleYear").append("=").append(sendBicycleYear);
//put data into JSP
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
osw.write(buffer.toString());
osw.flush();
//get data from JSP
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
String str;
//fit the order with JSP(garbage values)
reader.readLine(); reader.readLine(); reader.readLine(); reader.readLine();
//get data from JSP
for(;;) {
if((str = reader.readLine()) != null && (str != "") && (str != " ") && (str != "null")) {
mysqlStoreId[countInventory] = str;
for(int c=0; c<5; c++) {
for(int s=0; s<8; s++) {
str = reader.readLine();
mysqlInventory[countInventory][c][s] = Integer.parseInt(str);
}
}
countInventory++;
} else if(str == null && str == "null") {
//finish for if values equals null
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sResult;
}
}
I find the answer. I check all code's log.
the problem is that 'doInBackground' have an error. there is no an else in 'for(;;)' so AsyncTack make 'onCancelled()'. but I'm not write the 'onCancelled()' code.
when I add onCancelled(), I can cancel(true) and re-start the Asynctask.
Thank!

Transferring assets : Error code 4005 ASSET_UNAVAILABLE

This is driving me crazy. I wrote a code quite a while ago that was working, and opened it again and it happens that I am not able to transfer my assets from the mobile to the wearable device.
public Bitmap loadBitmapFromAsset(Asset asset) {
if (asset == null) {
throw new IllegalArgumentException("Asset must be non-null");
}
// convert asset into a file descriptor and block until it's ready
Log.d(TAG, "api client" + mApiClient);
DataApi.GetFdForAssetResult result = Wearable.DataApi.getFdForAsset(mApiClient, asset).await();
if (result == null) {
Log.w(TAG, "getFdForAsset returned null");
return null;
}
if (result.getStatus().isSuccess()) {
Log.d(TAG, "success");
} else {
Log.d(TAG, result.getStatus().getStatusCode() + ":" + result.getStatus().getStatusMessage());
}
InputStream assetInputStream = result.getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
// decode the stream into a bitmap
return BitmapFactory.decodeStream(assetInputStream);
}
And this is the code from which I call the loadBitmapFrom Asset method.
DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
ArrayList<DataMap> dataMaps = dataMap.getDataMapArrayList("dataMaps");
ArrayList<String> names = new ArrayList<>();
ArrayList<String> permalinks = new ArrayList<>();
ArrayList<Asset> images = new ArrayList<>();
for (int i = 0 ; i < dataMaps.size() ; i++) {
Log.d(TAG, dataMaps.get(i).getString("name"));
names.add(dataMaps.get(i).getString("name"));
permalinks.add(dataMaps.get(i).getString("permalink"));
images.add(dataMaps.get(i).getAsset("image"));
}
editor.putInt("my_selection_size", names.size());
for (int i=0; i <names.size() ; i++) {
editor.putString("my_selection_name_" + i, names.get(i));
editor.putString("my_selection_permalink_" + i, permalinks.get(i));
Log.d(TAG, "asset number " + i + " " + images.get(i));
Bitmap bitmap = loadBitmapFromAsset(images.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
editor.putString("my_selection_image_" + i, encoded);
}
And on the mobile side :
private void sendData(PutDataMapRequest dataMap) {
PutDataRequest request = dataMap.asPutDataRequest();
request.setUrgent();
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mApiClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
com.orange.radio.horizon.tools.Log.d(TAG, "api client : " + mApiClient);
if (dataItemResult.getStatus().isSuccess()) {
com.orange.radio.horizon.tools.Log.d(TAG, "message successfully sent");
} else if (dataItemResult.getStatus().isInterrupted()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (interrupted)");
} else if (dataItemResult.getStatus().isCanceled()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (canceled)");
}
}
});
Log.d(TAG, "Sending data to android wear");
}
class ConfigTask extends AsyncTask<String, Void, String> {
ArrayList<WatchData> mitems;
int mType;
public ConfigTask(ArrayList<WatchData> items, int type)
{
mitems = items;
mType = type;
}
protected String doInBackground(String... str)
{
DataMap dataMap;
ArrayList<DataMap> dataMaps = new ArrayList<>();
Bitmap bitmap = null;
for (int i = 0 ; i < mitems.size() ; i++) {
dataMap = new DataMap();
URL url = null;
try {
url = new URL(mitems.get(i).mUrlSmallLogo);
Log.d(TAG, "url : " + url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Asset asset = createAssetFromBitmap(bitmap);
dataMap.putAsset("image", asset);
dataMap.putString("name", mitems.get(i).mName);
dataMap.putString("permalink", mitems.get(i).mPermalink);
dataMaps.add(dataMap);
}
PutDataMapRequest request = null;
switch (mType) {
case 0 :
request = PutDataMapRequest.create(SELECTION_PATH);
break;
case 1 :
request = PutDataMapRequest.create(RADIOS_PATH);
break;
case 2 :
request = PutDataMapRequest.create(PODCASTS_PATH);
break;
}
request.getDataMap().putDataMapArrayList("dataMaps", dataMaps);
request.getDataMap().putString("", "" + System.currentTimeMillis()); //random data to refresh
Log.d(TAG, "last bitmap : " + bitmap);
Log.d(TAG, "===============================SENDING THE DATAMAP ARRAYLIST==================================");
sendData(request);
return "h";
}
protected void onPostExecute(String name)
{
}
}
When executing that code, I see the following error happening :
02-02 14:47:59.586 7585-7601/? D/WearMessageListenerService﹕ 4005:ASSET_UNAVAILABLE
I saw that related thread Why does Wearable.DataApi.getFdForAsset produce a result with status 4005 (Asset Unavailable)? but it didn't really help me
I recently had the same problem... I solved it by updating the Google play service, and adding the same signing configuration to both the app and the wearable module. If it doesn't work on the first build go to "invalidate caches / restart" in files and it should work.

Multiple and Repetitive AsyncTask in Android

I have two asynctask working with each other. I'm using them for creating Restaurant menu. First web service gets menu's titles from database. Second web service gets items of title from database. I get title data in my first asynctask and item data in my second asynctask.
For example, I have ten menu titles. There are eight items for each title. I execute first asynctask and get all of menu titles. I want to call second asynctask in first asynctask's onPostExecute for get this title's item and add TextView. I have to wait finished every second task for add item respectively.
In short, I need call first AsyncTask and wait finish it. Then send request to second AsyncTask in First AsyncTask. I have to wait every request to finish. How can I wait ?
Here is the my code.
First AsyncTask
public class BaslikDoldurAS extends AsyncTask<String,String[][],String[][]>{
int ParamID;
public BaslikDoldurAS(String ParamID){
this.ParamID=Integer.parseInt(ParamID);
}
#Override
protected String[][] doInBackground(String... params) {
BaslikDoldur(ParamID);
return sonuc;
}
protected void onPostExecute(String[][] sonuc){
for(int i=0;i<baslikCount;i++){
MenuDoldurAS kontrol = new MenuDoldurAS(firma_id,sonuc[2][i]);
kontrol.execute();
}
}
}
my function which is used in first asyncTask
private String[][] BaslikDoldur(Integer ParamID){
PropertyInfo id = new PropertyInfo();
id.name= "id";
id.setValue(ParamID);
id.type = PropertyInfo.INTEGER_CLASS;
SoapObject request = new SoapObject(NAMESPACE, "BaslikDoldur");
request.addProperty(id);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(MenuURL);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("http://tempuri.org/BaslikDoldur", envelope);
SoapObject response = (SoapObject) envelope.getResponse();
sonuc[2]=new String[response.getPropertyCount()]; //baslik
baslikCount=response.getPropertyCount();
for(int i=0;i<response.getPropertyCount();i++){
Object property = response.getProperty(i);
if(property instanceof SoapObject){
SoapObject menu = (SoapObject) property;
sonuc[2][i] = menu.getProperty("menu_baslik").toString();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return sonuc;
}
Second AsyncTask
public class MenuDoldurAS extends AsyncTask<String,String[][],String[][]>{
int ParamID;
String Baslik;
public MenuDoldurAS(String ParamID,String Baslik){
this.ParamID=Integer.parseInt(ParamID);
this.Baslik=Baslik;
}
#Override
protected String[][] doInBackground(String... params) {
MenuDoldur(ParamID,Baslik);
return sonuc;
}
protected void onPostExecute(String[][] sonuc){
for(int i=0;i<count;i++){
String baslik="";
if(!baslik.equals(sonuc[2][i])){
baslik=sonuc[2][i];
TextView basliktxt = new TextView(Urun.this);
basliktxt.setText(sonuc[2][i]);
basliktxt.setTextSize(20);
basliktxt.setTextColor(Color.RED);
basliktxt.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
urunLayout.addView(basliktxt);
}
else{
TextView aciklamatxt = new TextView(Urun.this);
aciklamatxt.setText(sonuc[3][i]);
aciklamatxt.setTextColor(Color.parseColor("#0c0c7c"));
aciklamatxt.setTextSize(17);
aciklamatxt.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
urunLayout.addView(aciklamatxt);
}
}
}
}
my function which is used in second asyncTask
private String[][] MenuDoldur(Integer ParamID,String Baslik){
PropertyInfo id = new PropertyInfo();
id.name= "id";
id.setValue(ParamID);
id.type = PropertyInfo.INTEGER_CLASS;
PropertyInfo baslik = new PropertyInfo();
baslik.name= "baslik";
baslik.setValue(Baslik);
baslik.type = PropertyInfo.STRING_CLASS;
SoapObject request = new SoapObject(NAMESPACE, "MenuDoldur");
request.addProperty(id);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(MenuURL);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("http://tempuri.org/MenuDoldur", envelope);
SoapObject response = (SoapObject) envelope.getResponse();
sonuc[3]=new String[response.getPropertyCount()]; //aciklama ve fiyat
count = response.getPropertyCount();
for(int i=0;i<response.getPropertyCount();i++){
Object property = response.getProperty(i);
if(property instanceof SoapObject){
SoapObject menu = (SoapObject) property;
sonuc[3][i] = menu.getProperty("menu_aciklama").toString() + " - " + menu.getProperty("menu_fiyat").toString();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return sonuc;
}
If you want to wait until all AsyncTasks are done before proceeding, why don't you just put all of you work in doInBackground of the first AsyncTask?
Or you don't want to do this because you want to run the 10 "second tasks" in parallel? (Which, incidentally you're not doing anyway, because you're not using the THREAD_POOL Executor for your tasks.) If this is the case then why not just do something like
// variable accessible to both tasks
ArrayList<AsyncTask> mRunningTasks = new ArrayList<AsyncTask>();
// AsyncTask1
protected void onPostExecute(String[][] sonuc){
for(int i=0;i<baslikCount;i++){
MenuDoldurAS kontrol = new MenuDoldurAS(firma_id,sonuc[2][i]);
mRunningTasks.add(kontrol);
}
for (AsyncTask task : mRunningTasks) {
task.execute();
}
}
// AsyncTask2
protected void onPostExecute(...) {
boolean allComplete = true;
for (AsyncTask task : mRunningTasks) {
if (!task.getStatus().equals(AsyncTask.Status.FINISHED)) {
allComplete = false;
break;
}
}
if (allComplete) {
//do whatever
mRunningTasks.clear();
}
}

Resources