Please help, I can find the distance of one beacon but I can't populate a listview with other beacons in the region. I've tested the listview by just using a string array, populates fine. Everything else works but I'm at a total loss for this last part, close to the edge here...
Here's my code for the main activity`import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.*;
import org.altbeacon.beacon.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class MainActivity extends Activity implements BeaconConsumer{
private BeaconManager beaconManager;
int distance;
Identifier minorID;
double distanceLong;
private Handler mHandler;
private int i;
public TextView distanceText;
public TextView distanceName1;
public ImageView distanceImage;
public String name1;
public boolean exitRegion = false;
public String minorString;
List<String> beaconList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
name1 = intent.getStringExtra("beacon1");
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser()
.setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
distanceText = (TextView) findViewById(R.id.distanceText);
distanceText.setText("No beacons found yet, please wait");
distanceName1 = (TextView) findViewById(R.id.name1);
distanceName1.getText();
distanceName1.setText("How far away is "+name1+"?");
distanceText = (TextView) findViewById(R.id.distanceText);
distanceText.getText();
distanceText.setText("Distance: " + distance+ " metres");
distanceImage = (ImageView) findViewById(R.id.distanceImage);
//alertDialogue();
i = 0;
mHandler = new Handler() {
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord record) {
}
};
beaconList = new ArrayList<String>();
ListAdapter beaconAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, beaconList);
ListView beaconListView = (ListView) findViewById(R.id.beaconListView);
beaconListView.setAdapter(beaconAdapter);
distanceText.post(mUpdate);
distanceImage.post(mUpdate);
}
private Runnable mUpdate = new Runnable() {
public void run() {
distanceText.setText("Distance: " + distance+ " ms");
imageDistance(distance);
alertDialogue(distance);
i++;
distanceText.postDelayed(this, 10000);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
public void onBeaconServiceConnect() {
final Region region = new Region("myBeacons", Identifier.parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), null, null);
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
try {
Log.d(TAG, "didEnterRegion");
exitRegion=false;
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didExitRegion(Region region) {
try {
Log.d(TAG, "didExitRegion");
exitRegion = true;
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for(Beacon oneBeacon : beacons) {
distanceLong = oneBeacon.getDistance();
distance = (int) distanceLong;
minorID = oneBeacon.getId3();
minorString = minorID.toString();
String distanceString = String.valueOf("Distance of " + minorID +" beacon: "+ (int) distanceLong+ " metres");
beaconList.add(distanceString);
Beacon.setHardwareEqualityEnforced(true);
}
}
});
try {
beaconManager.startMonitoringBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
`
My layout code is here, as I said the UI mostly works already but maybe I've missed something with the listview...
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}">
<TextView
android:layout_width="wrap_content"
android:layout_height="60dp"
android:textColor="#color/material_blue_grey_800"
android:textSize="25sp"
android:id="#+id/name1"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="60dp"
android:id="#+id/distanceText"
android:textColor="#color/material_blue_grey_800"
android:textSize="25sp"
android:layout_margin="10dp"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/name1"
/>
<ImageView android:layout_width="150dp"
android:layout_height="150dp"
android:id="#+id/distanceImage"
android:layout_margin="10dp"
android:layout_below="#+id/distanceText"
android:layout_gravity="center_horizontal"
/>
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/beaconListView"
android:textColor="#color/material_blue_grey_800"
android:textSize="25sp"
></ListView>
</LinearLayout></ScrollView>
A few tips:
You don't need the separate beaconList, only the beaconAdapter. But you do need to move the declaration of the beaconAdapter to be a class level variable like this:
...
public String minorString;
private ListAdapter beaconAdapter;
...
Then you can initialize it the same place you do now, just remove the declaration part. You can also remove the reference to beaconList, which is unneeded:
beaconAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
In the didRangeBeaconsInRegion callback, you then update the entries in the beaconAdapter. Like this:
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
beaconAdapter.clear();
for(Beacon oneBeacon : beacons) {
distanceLong = oneBeacon.getDistance();
distance = (int) distanceLong;
minorID = oneBeacon.getId3();
minorString = minorID.toString();
String distanceString = String.valueOf("Distance of " + minorID +" beacon: "+ (int) distanceLong+ " metres");
beaconAdapter.add(distanceString);
Beacon.setHardwareEqualityEnforced(true);
}
beaconAdapter.notifyDataSetChanged()
}
Note that in the code above, notifyDataSetChanged() is called as #niels-masdorp correctly says to do in his answer.
Related
Main Activity
public class MainActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener{
private MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private Button button;
private ArrayList <String> mNames=new ArrayList<>();
private ArrayList <String> mImages=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,getString(R.string.token));
setContentView(R.layout.activity_main);
mapView=(MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
button = findViewById(R.id.startnav);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = true;
NavigationViewOptions options = NavigationViewOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
button.setEnabled(true);
button.setBackgroundResource(R.drawable.button_press);
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
}
});
}
});
getImages();
}
private void getImages() {
Log.d(TAG, "initImageBitmaps: preparing bitmaps");
mImages.add("https://c1.staticflickr.com/5/4636/25316407448_de5fbf183d_o.jpg");
mNames.add("Havasu Falls");
mImages.add("https://i.redd.it/tpsnoz5bzo501.jpg");
mNames.add("Trondheim");
mImages.add("https://i.redd.it/qn7f9oqu7o501.jpg");
mNames.add("Portugal");
mImages.add("https://i.redd.it/j6myfqglup501.jpg");
mNames.add("Rocky Mountain National Park");
mImages.add("https://i.redd.it/0h2gm1ix6p501.jpg");
mNames.add("Mahahual");
mImages.add("https://i.redd.it/k98uzl68eh501.jpg");
mNames.add("Frozen Lake");
mImages.add("https://i.redd.it/glin0nwndo501.jpg");
mNames.add("White Sands Desert");
mImages.add("https://i.redd.it/obx4zydshg601.jpg");
mNames.add("Austrailia");
mImages.add("https://i.imgur.com/ZcLLrkY.jpg");
mNames.add("Washington");
InitRecyclerView();
}
private void InitRecyclerView() {
Log.d(TAG, "InitRecyclerView: init recyclerview");
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView=findViewById(R.id.myrecyclerview);
recyclerView.setLayoutManager(linearLayoutManager);
MainAdapter adapter=new MainAdapter(this,mNames,mImages);
recyclerView.setAdapter(adapter);
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// verifica daca are permission si le cere
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
} else {
permissionsManager = new PermissionsManager( this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LostLocationEngine(MainActivity.this);
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
}
And the MainAdapter
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private static final String TAG="MainAdapter";
private ArrayList <String> mNames=new ArrayList<>();
private ArrayList <String> mImages=new ArrayList<>();
private Context mContext;
public MainAdapter(Context context , ArrayList<String> images, ArrayList<String> names) {
mNames=names;
mImages=images;
mContext=context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: called ");
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.image);
holder.name.setText(mNames.get(position));
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on a image"+mNames.get(position));
Toast.makeText(mContext,mNames.get(position),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
CircleImageView image;
TextView name;
public ViewHolder(View itemView) {
super(itemView);
image=itemView.findViewById(R.id.image_view);
name=itemView.findViewById(R.id.name);
}
}
}
This is activitymain layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.matei.meetup.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/myrecyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
mapbox:mapbox_cameraZoom="12" >
</com.mapbox.mapboxsdk.maps.MapView>
<Button
android:id="#+id/startnav"
android:layout_width="316dp"
android:layout_height="41dp"
android:layout_margin="20px"
android:background="#drawable/button_unpressed"
android:padding="5px"
android:text="Start navigation"
android:textColor="#color/mapboxWhite"
mapbox:layout_constraintBottom_toBottomOf="parent"
mapbox:layout_constraintLeft_toLeftOf="parent"
mapbox:layout_constraintRight_toRightOf="parent"
mapbox:layout_constraintTop_toBottomOf="#+id/mapView"
mapbox:layout_constraintVertical_bias="1.0" />
</android.support.constraint.ConstraintLayout>
And here is the other layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="1dp">
<android.support.v7.widget.CardView
android:layout_width="100dp"
android:layout_height="100dp"
app:cardCornerRadius="4dp"
app:cardElevation="1dp"
app:cardMaxElevation="2dp"
android:layout_centerInParent="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="centerCrop"
android:layout_centerHorizontal="true"
android:id="#+id/image_view"
android:src="#mipmap/ic_launcher"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="18dp"
android:text="Chestie"
android:layout_below="#+id/image_view"
android:layout_centerHorizontal="true"
android:gravity="center"
android:layout_marginTop="5dp"
android:textColor="#000"
android:layout_marginBottom="5dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
The app does not crash on runtime, it only displays the map without the RecyclerView. In my gradle file i inlcuded the dependencies i needed. I tried messing around with the gradle file, nothing seems to work. In my logcat I have the following java.io.FileNotFoundException-No such file or directory.
Problem in library de.hdodenhof.circleimageview.CircleImageView. check this
https://github.com/hdodenhof/CircleImageView/issues/121
If you need to circle imageview you can use glide transformation with imageview
https://bumptech.github.io/glide/doc/transformations.html
Example glide v4:
RequestOptions options = new RequestOptions();
options.CircleCrop();
Glide.with(fragment)
.load(url)
.apply(options)
.into(imageView);
My app consists of two strings and two buttons, one English string and Hindi string, when i click on English speak button, the English string is pronouncing, when i come to Hindi string it is not responding to given word as it was mentioned.
Here is my MainActivity look likes,
public class MainActivity extends AppCompatActivity {
private TextView englishString, hindiString;
private Button englishButton, hindiButton;
private TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
englishString = (TextView) findViewById(R.id.englishString);
hindiString = (TextView) findViewById(R.id.hindiString);
englishButton = (Button) findViewById(R.id.englishButton);
hindiButton = (Button) findViewById(R.id.hindiButton);
englishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadSpeakingLanguages(englishString.getText().toString());
}
});
hindiButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadSpeakingLanguages(hindiString.getText().toString());
}
});
}
private void loadSpeakingLanguages(String textToTranslate) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ttsGreater21(textToTranslate);
} else {
ttsUnder20(textToTranslate);
}
}
#SuppressWarnings("deprecation")
private void ttsUnder20(String text) {
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void ttsGreater21(String text) {
String utteranceId = this.hashCode() + "";
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
}
#Override
protected void onResume() {
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});
super.onResume();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
textToSpeech = null;
}
super.onPause();
}}
Here is my activity_main looks like,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="ravi.texttospeech.MainActivity">
<TextView
android:id="#+id/englishString"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="25dp" />
<TextView
android:id="#+id/hindiString"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/englishString"
android:text="नमस्ते दुनिया"
android:textSize="25dp" />
<Button
android:id="#+id/englishButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/hindiString"
android:text="Speak English Text" />
<Button
android:id="#+id/hindiButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/englishButton"
android:text="Speak Hindi Text" />
And here is how my app look like
I have done some modifications in your code.
hindiButton.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
loadSpeakingLanguages(hindiString.getText().toString());
textToSpeech.setLanguage(Locale.forLanguageTag("hin"));
}
});
its working fine for me.
You need to use ISO 639 3-letter word or ISO 639 2-letter word
check out the ISO country names and there corresponding codes in this link
Note: This method works only above lollipop and next versions .
setLanguage(new Locale("hi","IN"))
Try this:-
Locale locale = new Locale("hi", "IN");
int avail = textToSpeech.isLanguageAvailable(locale);
switch (avail) {
case TextToSpeech.LANG_AVAILABLE:
textToSpeech.setLanguage(Locale.forLanguageTag("hi"));
isLanguageAvailable = true;
break;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
textToSpeech.setLanguage(locale);
isLanguageAvailable = true;
break;
}
Changing the default engine to com.google.android.tts, worked for me.
Example:
new TextToSpeech(
context.getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
if (textToSpeech != null) {
textToSpeech.setLanguage(new Locale("en", "IN"));
textToSpeech.setSpeechRate(1);
}
}
}
},
"com.google.android.tts");
Add this import:
import android.speech.tts.TextToSpeech
Implement this listener
class DetailDay : AppCompatActivity(), TextToSpeech.OnInitListener {
Then override (paste) this method:
override fun onInit(intVar: Int) {
if(intVar==TextToSpeech.SUCCESS){
var local= Locale("hi","IN")
val resultado=tts!!.setLanguage(local)
if(resultado==TextToSpeech.LANG_MISSING_DATA){
Log.i(TAG,"lang not found")
}
}
}
Then create this variable:
private var tts:TextToSpeech?=null
Initialize in onCreate (recommended)
tts= TextToSpeech(this,this)
To start playing, call this method:
tts!!.speak(stringData, TextToSpeech.QUEUE_FLUSH, null);
To Stop playing,
tts!!.stop()
I am trying to implement "Swipe to load more" method in my application but I got that error when I swipe down in the first time. This is what it showed in the console:
E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have an active
pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have
an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but
don't have an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE
event but don't have an active pointer id.
This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="training.com.chatgcmapplication.ChatActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="380dp">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
</android.support.v4.widget.SwipeRefreshLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.92"
android:inputType="text" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
And when I swipe in the second time: it load double data.
This is ChatActivity, what implement that method:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
private static EditText txt_chat;
private String registId;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private int offsetNumber = 5;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Button btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(this);
ListView lv_message = (ListView) findViewById(R.id.listMessage);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
Bundle bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), 0);
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), offsetNumber);
messageAdapter.insertToTheFirst(messages);
messageAdapter.notifyDataSetChanged();
offsetNumber += 5;
Log.i("Offset number", offsetNumber + "");
swipeRefreshLayout.setRefreshing(false);
}
}
UPDATE ISSUE's REASON
I found the reason of that issue. It due to I force the listview scroll to the bottom when it init with this code :
android:stackFromBottom="true"
I replace that code with this but still have same issue:
lv_message.post(new Runnable() {
#Override
public void run() {
lv_message.setSelection(lv_message.getCount() -1);
}
});
I think the problem is , You are trying to show , dismiss and refresh swipeRefreshLayout inside the same method i.e onRefresh().
Make seperate methods for showing and dismissing dialog and invoke them from the place where they are required as I have done below:
#Override
public void onRefresh() {
// refresh code here.
}
#Override
public void showDialog() {
swipeRef.post(new Runnable() {
#Override
public void run() {
if(swipeRef != null)
swipeRef.setRefreshing(true);
}
});
}
#Override
public void dismissDialog() {
if(swipeRef!=null && swipeRef.isShown() )
swipeRef.setRefreshing(false);
}
I am trying to develop an app with in app purchases in it, simply what I want to do is to have two buttons one to make the purchase(enabled) the second button to open the activity after purchase (at first is disabled then after purchase is enabled).
Two problems the first was to save the buttons state after the purchase as they were getting reset every time I restart the app. So I did some researches and found about shared preference and I did implemented it but the second problem came out that buttons statuses doesn’t seem to work right (between disabled to enabled) after implementing shared preference.
Note that in the app I have two buttons that do the same thing one enables the other buttons but with no purchase made and they work fine with shared preference, but the buttons associated with the in app purchase stopped changing their status from disabled to enabled after the purchase is made (they stay disabled after the purchase)
Here is my xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainScreen">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 1"
android:id="#+id/act1"
android:onClick="Activity1"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/buyall"
android:layout_toStartOf="#+id/buyall"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Act 1"
android:id="#+id/buyButton"
android:onClick="buyClick"
android:layout_alignTop="#+id/act1"
android:layout_toRightOf="#+id/act1"
android:layout_toEndOf="#+id/act1"
android:layout_marginLeft="45dp"
android:layout_marginStart="45dp"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 2"
android:id="#+id/act2"
android:layout_below="#+id/act1"
android:layout_alignLeft="#+id/act1"
android:layout_alignStart="#+id/act1"
android:onClick="Activity2"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 2"
android:id="#+id/buyact2"
android:layout_alignBottom="#+id/act2"
android:layout_alignLeft="#+id/buyButton"
android:layout_alignStart="#+id/buyButton"
android:onClick="buyAct2"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 3"
android:id="#+id/act3"
android:layout_below="#+id/act2"
android:layout_alignLeft="#+id/act2"
android:layout_alignStart="#+id/act2"
android:onClick="Activity3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 3"
android:id="#+id/buyact3"
android:layout_alignBottom="#+id/act3"
android:layout_alignLeft="#+id/buyact2"
android:layout_alignStart="#+id/buyact2"
android:onClick="buyAct3"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy all"
android:id="#+id/buyall"
android:onClick="buyAll"
android:enabled="true"
android:layout_below="#+id/eact4"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACT 4"
android:id="#+id/act4"
android:onClick="ACT4"
android:layout_below="#+id/act3"
android:layout_alignLeft="#+id/act3"
android:layout_alignStart="#+id/act3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable ACT 4"
android:id="#+id/eact4"
android:onClick="EACT4"
android:layout_below="#+id/buyact3"
android:layout_alignLeft="#+id/buyact3"
android:layout_alignStart="#+id/buyact3"
android:enabled="true" />
And that’s my java code:
package com.aseng90_test.smiap2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.aseng90_test.smiap2.util.IabHelper;
import com.aseng90_test.smiap2.util.IabResult;
import com.aseng90_test.smiap2.util.Purchase;
public class MainScreen extends ActionBarActivity {
private static final String TAG = "com.aseng90_test.smiap2";
IabHelper mHelper;
private static final String ITEM_SKU = "com.aseng90_test.smiap2_button555";
private static final String ITEM_SKU2 = "com.aseng90_test.smiap2_buyact222";
private static final String ITEM_SKU3 = "com.aseng90_test.smiap2_buyact333";
private static final String ITEM_SKU4 = "com.aseng90_test.smiap2_buyall_11";
private Button Activity1;
private Button Activity2;
private Button Activity3;
private Button buyButton;
private Button buyAct2;
private Button buyAct3;
private Button buyAll;
private Button EAct4;
private Button Act4;
private SharedPreferences prefs;
private String prefName = "MyPref";
boolean Activity1_isEnabled;
boolean Activity2_isEnabled;
boolean Activity3_isEnabled;
boolean Act4_isEnabled;
boolean buyButton_isEnabled;
boolean buyAct2_isEnabled;
boolean buyAct3_isEnabled;
boolean buyAll_isEnabled;
boolean EAct4_isEnabled;
private static final String Activity1_state = "Activity1_state";
private static final String Activity2_State = "Activity2_state";
private static final String Activity3_State = "Activity3_state";
private static final String buyButton_State = "buyButton_state";
private static final String buyAct2_State = "buyAct2_state";
private static final String buyAct3_State = "buyAct3_state";
private static final String buyAll_State = "buyAll_state";
private static final String Act4_State = "Act4_state";
private static final String EAct4_State = "EAct4_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
buyButton = (Button) findViewById(R.id.buyButton);
buyAct2 = (Button) findViewById(R.id.buyact2);
buyAct3 = (Button) findViewById(R.id.buyact3);
buyAll = (Button) findViewById(R.id.buyall);
Activity1 = (Button) findViewById(R.id.act1);
Activity2 = (Button) findViewById(R.id.act2);
Activity3 = (Button) findViewById(R.id.act3);
EAct4 = (Button) findViewById(R.id.eact4);
Act4 = (Button) findViewById(R.id.act4);
String base64EncodedPublicKey =
"";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void EACT4(View view) {
EAct4.setEnabled(false);
Act4.setEnabled(true);
}
public void ACT4(View view) {
Toast.makeText(MainScreen.this,
"ACt4 Clicked", Toast.LENGTH_LONG).show();
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
public void buyAct2(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU2, 10002, mPurchaseFinishedListener, "buyact2");
}
public void buyAct3(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU3, 10003, mPurchaseFinishedListener, "buyact3");
}
public void buyAll(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU4, 10004, mPurchaseFinishedListener, "buyall");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
}
if (purchase.getSku().equals(ITEM_SKU)) {
Activity1.setEnabled(true);
buyButton.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU2)) {
Activity2.setEnabled(true);
buyAct2.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU3)) {
Activity3.setEnabled(true);
buyAct3.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU4)) {
Activity1.setEnabled(true);
Activity2.setEnabled(true);
Activity3.setEnabled(true);
buyAll.setEnabled(false);
buyButton.setEnabled(false);
buyAct2.setEnabled(false);
buyAct3.setEnabled(false);
}
}
};
public void Activity1(View view) {
startActivity(new Intent(MainScreen.this, Click1.class));
}
public void Activity2(View view) {
startActivity(new Intent(MainScreen.this, Activity2.class));
}
public void Activity3(View view) {
startActivity(new Intent(MainScreen.this, Activity3.class));
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
#Override
protected void onPause(){
super.onPause();
if (Act4.isEnabled()){
Act4_isEnabled = true;
}
else {
Act4_isEnabled = false;
}
if (Activity1.isEnabled()){
Activity1_isEnabled = true;
}
else {
Activity1_isEnabled = false;
}
if (Activity2.isEnabled()){
Activity2_isEnabled = true;
}
else {
Activity2_isEnabled = false;
}
if (Activity3.isEnabled()){
Activity3_isEnabled = true;
}
else {
Activity3_isEnabled = false;
}
if (buyButton.isEnabled()){
buyButton_isEnabled = true;
}
else {
buyButton_isEnabled = false;
}
if (buyAct2.isEnabled()){
buyAct2_isEnabled = true;
}
else {
buyAct2_isEnabled = false;
}
if (buyAct3.isEnabled()){
buyAct3_isEnabled = true;
}
else {
buyAct3_isEnabled = false;
}
if (buyAll.isEnabled()){
buyAll_isEnabled = true;
}
else {
buyAll_isEnabled = false;
}
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Activity1_state,this.getLocalClassName());
editor.putBoolean(Act4_State,Act4_isEnabled);
editor.putBoolean(EAct4_State,EAct4_isEnabled);
editor.putBoolean(Activity1_state,Activity1_isEnabled);
editor.putBoolean(Activity2_State,Activity2_isEnabled);
editor.putBoolean(Activity3_State,Activity3_isEnabled);
editor.putBoolean(buyButton_State,buyButton_isEnabled);
editor.putBoolean(buyAct2_State,buyAct2_isEnabled);
editor.putBoolean(buyAct3_State,buyAct3_isEnabled);
editor.putBoolean(buyAll_State,buyAll_isEnabled);
editor.apply();
}
#Override
protected void onResume(){
super.onResume();
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
Act4.setEnabled(prefs.getBoolean(Act4_State,false));
Activity1.setEnabled(prefs.getBoolean(Activity1_state,false));
Activity2.setEnabled(prefs.getBoolean(Activity2_State,false));
Activity3.setEnabled(prefs.getBoolean(Activity3_State,false));
EAct4.setEnabled(prefs.getBoolean(EAct4_State,true));
buyButton.setEnabled(prefs.getBoolean(buyButton_State,true));
buyAct2.setEnabled(prefs.getBoolean(buyAct2_State,true));
buyAct3.setEnabled(prefs.getBoolean(buyAct3_State,true));
buyAll.setEnabled(prefs.getBoolean(buyAll_State,true));
}
So Any suggestions if I have something wrong in my code?
Thanks a lot.
Try to call methods from Java part , don't call from xml using android:onClick
Use default value of the button(buy) state to false in shared preference .
and in this screen implement this if check inside oncreate() method as:
if(button(buy) state ==false)
{
//make button(buy) state enable
//make activity button state disable
}
else
{
//make button(buy) state disable
//make activity button state enable
}
And make button(buy) and activity calling button state to true/false according to result after in app purchase and also update shared prefrence state according to result
I am writing an random number generator program to show the output every sec.
The overview is that every second when the random number change I would want to random number to be output to the 'EditText' box. Is it possible?
I have research on it but result in unsuccessfully (mainly because of how the async works).
This is the code that I have written:
package com.example;
import java.util.Random;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AsyncTasksActivity extends Activity {
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String ranString = "";
try{
ranString = "";
for(int a = 0; a < 33; a++)
{
Random rn = new Random();
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(ranString);
}
public class runRandomly extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
}
In case you need to run the code to ensure it works, I have place the xml code here:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Null"
/>
<EditText
android:id="#+id/Null"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="numberDecimal"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Random Key"/>
<EditText
android:id="#+id/txtMessage"
android:layout_width="fill_parent"
android:gravity="center"
android:editable="false" android:layout_height="61dp" android:layout_weight="0.14"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Much Thanks!
From my point of view,
Make a constructor of your AsyncTask class passing activity signature,
like,
public runRandomly(Activity activity) {
this.activity = activity;
context = activity;
}
also override this method
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
if (values[0] == 0) {
mDialog.setTitle("Processing...");
}
mDialog.setProgress(values[0]);
}
update the onProgressUpdate(call it) from your doInBackground(String... params) method
EDIT: you can also give a reference of your EditText view in AsyncTask constructor and do update in onProgressUpdate method.
EDIT: use this code..
public class NewClass extends Activity {
/** Called when the activity is first created. */
EditText edt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newclass);
edt=(EditText)findViewById(R.id.ed);
new runRandomly(this,edt).execute();
}
public class runRandomly extends AsyncTask<String, String, String> {
String ranString="";
Activity activity;
EditText edtt;
public runRandomly(Activity activity,EditText edit) {
this.activity = activity;
edtt=edit;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
for(int a = 0; a < 33; a++)
{
Random rn = new Random();
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
onProgressUpdate();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
edtt.setText(""+ranString);
super.onProgressUpdate(values);
}
}
}
Simple, Thanx.
put this line outside of the for loop it will re-generate new object so no need it in loop
Random rn = new Random();
for(int a = 0; a < 33; a++)
{
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
you need to Handler and Runnable object which call the AsynTask execute method using runRandomly object
like create this object
Handler handler = new Handler();
runRandomly randomly = new runRandomly();
Runnable callRandom = new Runnable(){
public void run(){
//// call the execute method
randomly.execute();
///// here handler call this runnable every 1 sec i.e 1000 delay time
handler.postDelay(callRandom,1000);
}
}
in onBackground generate the number
#Override
protected String doInBackground(String... params) {
String ranString = "";
Random rn = new Random();
for(int a = 0; a < 33; a++)
{
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
return ranString;
}
this above method will generate the random number string and when it finish this will return that string to the postExecute();
#Override
protected void onProgressUpdate(String values) {
super.onProgressUpdate(values);
if(values!=null & !values.equals(""))
txtMessage.setText(ranString);
}