how to call image from weather api using xmlPullParser? - java

} else if (xpp.getName().equalsIgnoreCase("pressure")) {
if (insideItem) {
Pressure.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("weatherIconUrl")) {
if (insideItem) {
iconImg.add(xpp.nextText());
}
I am trying to call weather items from weather api. All text items that I am trying to call are ok but iconImg is not. iconImg.add(xpp.nextText()) gives an error. I probably shouldn't use imageview here, but I don't know what else to do. Any help will be appreciated.
Here is the entire code:
public class HavaDurumu2 extends FragmentActivity {
private String urll;
public TextView xmlShow;
private EditText lattitudeEditText;
private EditText longitudeEditText;
private Button devam;
public Intent dataShowIntent;
public TextView succcess;
public TextView appTitle;
public TextView lat;
public TextView lon;
GoogleMap googlelMap;
Marker mk;
Button fav;
TextView error;
Intent vj;
public static List<String> Time;
public static List<String> CTemperature;
public static List<String> Wind_Speed_Kmph;
public static List<String> Water_Temperature_C;
public static List<String> Humidity;
public static List<String> Significant_Wave_Height;
public static List<String> Swell_Height;
public static List<String> Swell_Direction;
public static List<String> Swell_Period;
public static List<String> Pressure;
public static List<String> Visibility;
public static List<String> Weather_Condition;
public static List<String> Warning_level;
public static List<Double> Wind_Speed_Kmph_Num;
public static List<Double> Wind_Speed_mps_Num;
public static List<String> Wind_Dir_Degree;
public static List<Double> Beaufort;
public static List<String> nearest_longitude;
public static List<String> nearest_latitude;
public static List<String> nearest_distance_mile;
public static List<String> date;
public static List<String> maxtempc;
public static List<String> mintempc;
public static List<String> nearest_location_name;
public static List<String> sunrise;
public static List<String> sunset;
public static List<ImageView> iconImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_havadurumu2);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
SupportMapFragment mapfragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googlelMap = mapfragment.getMap();
lattitudeEditText = (EditText) findViewById(R.id.enEditText);
longitudeEditText = (EditText) findViewById(R.id.boyEditText);
lat = (TextView) findViewById(R.id.enlem);
lon = (TextView) findViewById(R.id.boylam);
devam = (Button) findViewById(R.id.devam);
googlelMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39, 30), 5.0f));
lattitudeEditText.clearFocus();
longitudeEditText.clearFocus();
Time = new ArrayList<String>();
CTemperature = new ArrayList<String>();
Wind_Speed_Kmph = new ArrayList<String>();
Water_Temperature_C = new ArrayList<String>();
Humidity = new ArrayList<String>();
Significant_Wave_Height = new ArrayList<String>();
Swell_Height = new ArrayList<String>();
Swell_Direction = new ArrayList<String>();
Swell_Period = new ArrayList<String>();
Pressure = new ArrayList<String>();
Visibility = new ArrayList<String>();
Warning_level = new ArrayList<String>();
Wind_Dir_Degree = new ArrayList<String>();
sunrise = new ArrayList<String>();
sunset = new ArrayList<String>();
Wind_Speed_Kmph_Num = new ArrayList<Double>();
Wind_Speed_mps_Num = new ArrayList<Double>();
Beaufort = new ArrayList<Double>();
Weather_Condition = new ArrayList<String>();
iconImg =new ArrayList<ImageView>();
nearest_longitude = new ArrayList<String>();
nearest_latitude = new ArrayList<String>();
nearest_distance_mile = new ArrayList<String>();
date = new ArrayList<String>();
maxtempc = new ArrayList<String>();
mintempc = new ArrayList<String>();
nearest_location_name = new ArrayList<String>();
String message = "Yer secmek için ekrana uzun basın";
Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
t.show();
googlelMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
if (mk == null) {
mk = googlelMap.addMarker(new MarkerOptions().position(point).snippet("Enlem : " + point.latitude + "Boylam : " + point.longitude).title("Kordinatlar"));
lattitudeEditText.setText(("" + point.latitude).substring(0, 9));
longitudeEditText.setText(("" + point.longitude).substring(0, 9));
// fav.setVisibility(View.VISIBLE);
} else {
mk.remove();
mk = googlelMap.addMarker(new MarkerOptions().position(point).snippet("Enlem : " + point.latitude + "Boylam : " + point.longitude).title("Kordinatlar"));
lattitudeEditText.setText("" + point.latitude);
longitudeEditText.setText("" + point.longitude);
}
}
});
} else {
String message = "Google Play servisi uygun değil";
Toast.makeText(HavaDurumu2.this, message, Toast.LENGTH_LONG).show();
//GooglePlayServicesUtil.getErrorDialog(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this),this,1001).show();
}
}
public void clickHandler(View v) {
if (lattitudeEditText.getText().toString().isEmpty() && longitudeEditText.getText().toString().isEmpty()) {
String message = "Lütfen Bir Yer Seçin";
Toast.makeText(HavaDurumu2.this, "Lütfen Bir Yer Seçin", Toast.LENGTH_SHORT).show();
} else if (networkStatus(HavaDurumu2.this)) {
urll = "http://api.worldweatheronline.com/free/v2/marine.ashx?q=" + lattitudeEditText.getText().toString() + "%2C" + longitudeEditText.getText().toString() + "&tp=3&lang=tr&format=xml&key=......";
new LoadAssync().execute();
} else {
String message = "İnternet Bağlantısı Bulunamdı";
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.setGravity(0, 0, 300);
toast.show();
}
}
private class LoadAssync extends AsyncTask<String, Void, Void> {
ProgressDialog dialog = new ProgressDialog(HavaDurumu2.this);
protected void onPreExecute() {
dialog.setMessage("Bilgiler Alınıyor...");
dialog.show();
}
protected Void doInBackground(final String... args) {
try {
getdata();
updateDateandTemperature();
updatedirection();
updateAstronomy();
updateweather();
Log.i("", String.valueOf(date.size()) + " " + String.valueOf(Wind_Dir_Degree.size()) + " " + String.valueOf(sunrise.size()));
} catch (Exception ex) {
String message = "Hata oluştu";
Toast.makeText(HavaDurumu2.this, message, Toast.LENGTH_SHORT).show();
}
return null;
}
protected void onPostExecute(final Void unused) {
if (dialog.isShowing()) {
dialog.dismiss();
if (Time.size() == 0) {
nearest_distance_mile.clear();
nearest_latitude.clear();
nearest_location_name.clear();
nearest_longitude.clear();
maxtempc.clear();
mintempc.clear();
date.clear();
sunrise.clear();
sunset.clear();
String message = "Bu bölge için durum bilgisi yok";
Toast.makeText(HavaDurumu2.this, message, Toast.LENGTH_SHORT).show();
} else {
Intent m = new Intent(HavaDurumu2.this, ShowWeather.class);
startActivity(m);
}
}
}
}
private void updatefeeds() {
try {
Time.clear();
CTemperature.clear();
Wind_Speed_Kmph.clear();
Wind_Speed_Kmph_Num = new ArrayList<Double>();
Water_Temperature_C.clear();
Humidity.clear();
;
Significant_Wave_Height.clear();
Swell_Height.clear();
Swell_Direction.clear();
Swell_Period.clear();
Pressure.clear();
Visibility.clear();
Warning_level.clear();
Beaufort.clear();
Wind_Dir_Degree.clear();
Weather_Condition.clear();
iconImg.clear();
URL url = new URL(urll);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("hourly")) {
insideItem = true;
}
else if (xpp.getName().equalsIgnoreCase("time")) {
if (insideItem) {
Time.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("tempc")) {
if (insideItem) {
CTemperature.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("windspeedKmph")) {
if (insideItem) {
Wind_Speed_Kmph.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("winddirdegree")) {
if (insideItem) {
Wind_Dir_Degree.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("waterTemp_C")) {
if (insideItem) {
Water_Temperature_C.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("humidity")) {
if (insideItem) {
Humidity.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("sigHeight_m")) {
if (insideItem) {
Significant_Wave_Height.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("swellHeight_m")) {
if (insideItem) {
Swell_Height.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("swellDir")) {
if (insideItem) {
Swell_Direction.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("swellPeriod_secs")) {
if (insideItem) {
Swell_Period.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("visibility")) {
if (insideItem) {
Visibility.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("pressure")) {
if (insideItem) {
Pressure.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("weatherIconUrl")) {
if (insideItem) {
iconImg.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("lang_tr")) {
if (insideItem) {
Weather_Condition.add(xpp.nextText());
Log.i("", Weather_Condition.get(Weather_Condition.size() - 1));
}
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("hourly")) {
insideItem = false;
}
eventType = xpp.next();
}
} catch (Exception e) {
Log.i("", e.toString());
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public void updateDateandTemperature() {
try {
URL url = new URL(urll);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
date.clear();
maxtempc.clear();
mintempc.clear();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("weather")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("date")) {
if (insideItem) {
date.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("maxtempc")) {
if (insideItem) {
maxtempc.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("mintempc")) {
if (insideItem) {
mintempc.add(xpp.nextText());
}
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("weather")) {
insideItem = false;
}
eventType = xpp.next();
}
} catch (Exception e) {
}
}
public void updateAstronomy() {
try {
URL url = new URL(urll);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
sunrise.clear();
sunset.clear();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("astronomy")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("sunrise")) {
if (insideItem) {
sunrise.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("sunset")) {
if (insideItem) {
sunset.add(xpp.nextText());
}
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("weather")) {
insideItem = false;
}
eventType = xpp.next();
}
} catch (Exception e) {
}
}
public void getdata() {
updatefeeds();
for (int i = 0; i <= Wind_Speed_Kmph.size() - 1; i++)
Wind_Speed_Kmph_Num.add(Double.parseDouble(Wind_Speed_Kmph.get(i)));
for (int i = 0; i <= Wind_Speed_Kmph.size() - 1; i++)
Wind_Speed_mps_Num.add(Wind_Speed_Kmph_Num.get(i) * 1000.0 / 3600.0);
for (int i = 0; i <= Wind_Speed_mps_Num.size() - 1; i++)
Beaufort.add(Math.cbrt((Wind_Speed_mps_Num.get(i) / 0.837) * (Wind_Speed_mps_Num.get(i) / 0.837)));
updatewarninglevels();
}
public void updatedirection() {
for (int i = 0; i < Swell_Direction.size(); i++) {
if (Double.parseDouble(Swell_Direction.get(i)) >= 337.5 || Double.parseDouble(Swell_Direction.get(i)) <= 22.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°K");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 67.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°KD");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 112.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°D");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 157.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°GD");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 202.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°G");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 247.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°GB");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 292.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°B");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 337.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°KB");
}
for (int i = 0; i < Wind_Dir_Degree.size(); i++) {
if (Double.parseDouble(Wind_Dir_Degree.get(i)) >= 337.5 || Double.parseDouble(Wind_Dir_Degree.get(i)) <= 22.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°K");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 67.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°KD");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 112.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°D");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 157.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°GD");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 202.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°G");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 247.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°GB");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 292.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°B");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 337.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°KB");
}
}
public void updatewarninglevels() {
for (int i = 0; i <= Beaufort.size() - 1; i++) {
if (Beaufort.get(i) > 0 && Beaufort.get(i) <= 3.5)
Warning_level.add("Sakin 0 - 3.5 Bofor Skalası");
else if (Beaufort.get(i) <= 5.6)
Warning_level.add("Rüzgarlı 3.5- 5.5 Bofor Skalası");
else if (Beaufort.get(i) <= 9.5)
Warning_level.add("Fırtına 5.6- 9.5 Bofor Skalası");
else
Warning_level.add("Kasırga 9.5 - üstü Bofor Skalası");
}
}
public void updateweather() {
for (int i = 0; i <= Weather_Condition.size() - 1; i++) {
}
}
any idea?

Use String instead.
String artistPic = null; instead of imageview
get the value like
artistPic = readArtistPic(parser);

Related

Work manager getworkinfobyliveiddata on changed function not being called

This is the implementation of downloadRequestqueue class inside a library .This java file uses work manager inside its add request function.But the work manager getworkinfobyliveId function is not called.I think the problem is because of lifecycle owner of this java class which also I have implemented in this class
public class DownloadRequestQueue extends AppCompatActivity implements LifecycleOwner
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
#Override
public void onStart() {
super.onStart();
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
#NonNull
#Override
public Lifecycle getLifecycle() {
mLifecycleRegistry=new LifecycleRegistry(this);
Log.d("uu",mLifecycleRegistry+"");
return mLifecycleRegistry;
}
public DownloadRequestQueue(Context context) {
this.context = context;
currentRequestMap = new ConcurrentHashMap<>();
sequenceGenerator = new AtomicInteger();
}
public static void initialize(Context context) {
getInstance(context);
}
public static DownloadRequestQueue getInstance(Context context) {
if (instance == null) {
synchronized (DownloadRequestQueue.class) {
if (instance == null) {
instance = new DownloadRequestQueue(context);
}
}
}
return instance;
}
private int getSequenceNumber() {
return sequenceGenerator.incrementAndGet();
}
public void pause(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.PAUSED);
}
}
public void resume(int downloadId) {
final Response response = new Response();
final DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.QUEUED);
request.deliverStartEvent();
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
String json = gson.toJson(request);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
Data data = new Data.Builder().putInt("ID", downloadId).build();
final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(#Nullable WorkInfo workInfo) {
if (workInfo != null) {
Log.d("this","dip");
if (workInfo.getState().isFinished()) {
Data data = workInfo.getOutputData();
String output = data.getString("Response");
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
// request.setFuture(Core.getInstance()
// .getExecutorSupplier()
// .forDownloadTasks()
// .submit(new DownloadRunnable(request)));
}
}
private void cancelAndRemoveFromMap(DownloadRequest request) {
if (request != null) {
request.cancel();
currentRequestMap.remove(request.getDownloadId());
}
}
public void cancel(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
cancelAndRemoveFromMap(request);
}
public void cancel(Object tag) {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
if (request.getTag() instanceof String && tag instanceof String) {
final String tempRequestTag = (String) request.getTag();
final String tempTag = (String) tag;
if (tempRequestTag.equals(tempTag)) {
cancelAndRemoveFromMap(request);
}
} else if (request.getTag().equals(tag)) {
cancelAndRemoveFromMap(request);
}
}
}
public void cancelAll() {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
cancelAndRemoveFromMap(request);
}
}
public Status getStatus(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
return request.getStatus();
}
return Status.UNKNOWN;
}
public void addRequest(final DownloadRequest request) {
Log.d("did", request.getUrl() + "");
final Response response = new Response();
Log.d("yoii", request.getOnProgressListener()+"");
request.setStatus(Status.QUEUED);
abc=request.getOnProgressListener()+"";
onProgressListener1=request.getOnProgressListener();
currentRequestMap.put(request.getDownloadId(), request);
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
request.setOnProgressListener(request.getOnProgressListener());
String json = gson.toJson(request);
ArrayList<Integer> arrayList=new ArrayList<Integer>();
arrayList.add(1);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
if (request != null) {
Log.d("999", currentRequestMap.get(request.getDownloadId()).getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
if (request != null) {
Log.d("all", request.getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
Data data = new Data.Builder().putInt("ID", request.getDownloadId()).putString("status", request.getStatus() + "").build();
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
Log.d("boss", "pls");
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(#Nullable WorkInfo workInfo) {
Log.d("abd","see");
if(workInfo==null){
Log.d("bug","buggy");
}
if (workInfo != null) {
Log.d("boss2", "pls2");
if (workInfo.getState().isFinished()) {
Log.d("boss3", "pls3");
Data data = workInfo.getOutputData();
String output = data.getString("Response");
Log.d("boss4", output);
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("succ")) {
response.setSuccessful(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
}
public void finish(DownloadRequest request) {
currentRequestMap.remove(request.getDownloadId());
}
}
public MyWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
currentRequestMap=new ConcurrentHashMap<>();
mPrefs=PreferenceManager.getDefaultSharedPreferences(context);
}
#NonNull
#Override
public Result doWork() {
int a = getInputData().getInt("ID",2);
String statu = getInputData().getString("status");
Gson gson = new Gson();
String json = mPrefs.getString("SerializableObject", "");
if(json.equals("")){
Log.d("noii","nn");
}
request = gson.fromJson( json, DownloadRequest.class);
Log.d("zoiiii",currentRequestMap.get(a)+"")
if(request!=null){
Log.d("soii",request.getStatus()+"");
}
else{
Log.d("loii","toy");
}
Response response = new Response();
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
try {
Log.d("koko","gogo");
if(request.getOnProgressListener()==null){
Log.d("dope",request.getUrl()+"");
//progressHandler = new ProgressHandler(request.getOnProgressListener());
}
if (request.getOnProgressListener() != null) {
Log.d("toll","lol");
progressHandler = new ProgressHandler(request.getOnProgressListener());
}
Log.d("suppp","ppp");
tempPath = Utils.getTempPath(request.getDirPath(), request.getFileName());
File file = new File(tempPath);
DownloadModel model = getDownloadModelIfAlreadyPresentInDatabase();
Log.d("dupp","nupp");
if (model != null) {
Log.d("love","no");
if (file.exists()) {
request.setTotalBytes(model.getTotalBytes());
request.setDownloadedBytes(model.getDownloadedBytes());
} else {
removeNoMoreNeededModelFromDatabase();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
model = null;
}
}
Log.d("ab","devel");
httpClient = ComponentHolder.getInstance().getHttpClient();
Log.d("ggs","iipu");
httpClient.connect(request);
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
eTag = httpClient.getResponseHeader(Constants.ETAG);
Log.d("sipi","kipi");
if (checkIfFreshStartRequiredAndStart(model)) {
model = null;
Log.d("lova","nova");
}
if (!isSuccessful()) {
Log.d("lvv","nppp");
Error error = new Error();
error.setServerError(true);
error.setServerErrorMessage(convertStreamToString(httpClient.getErrorStream()));
error.setHeaderFields(httpClient.getHeaderFields());
error.setResponseCode(responseCode);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","abc")
.build();
return Result.failure(output);
}
setResumeSupportedOrNot();
Log.d("coder","npppp");
totalBytes = request.getTotalBytes();
if (!isResumeSupported) {
deleteTempFile();
}
if (totalBytes == 0) {
totalBytes = httpClient.getContentLength();
request.setTotalBytes(totalBytes);
}
if (isResumeSupported && model == null) {
createAndInsertNewModel();
}
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
Log.d("dodo","soso");
request.deliverStartEvent();
Log.d("coco","momo");
inputStream = httpClient.getInputStream();
byte[] buff = new byte[BUFFER_SIZE];
if (!file.exists()) {
if (file.getParentFile() != null && !file.getParentFile().exists()) {
if (file.getParentFile().mkdirs()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
} else {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
}
this.outputStream = FileDownloadRandomAccessFile.create(file);
if (isResumeSupported && request.getDownloadedBytes() != 0) {
outputStream.seek(request.getDownloadedBytes());
}
Log.d("miggy","siggy");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
do {
Log.d("left","some");
final int byteCount = inputStream.read(buff, 0, BUFFER_SIZE);
if (byteCount == -1) {
break;
}
outputStream.write(buff, 0, byteCount);
request.setDownloadedBytes(request.getDownloadedBytes() + byteCount);
Log.d("now1","one1");
sendProgress();
Log.d("now2","one2");
syncIfRequired(outputStream);
Log.d("common","yessin");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
sync(outputStream);
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
} while (true);
final String path = Utils.getPath(request.getDirPath(), request.getFileName());
Utils.renameFileName(tempPath, path);
response.setSuccessful(true);
Log.d("yup","dove");
if (isResumeSupported) {
removeNoMoreNeededModelFromDatabase();
}
} catch (IOException | IllegalAccessException e) {
if (!isResumeSupported) {
deleteTempFile();
}
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(e);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","def")
.build();
return Result.failure(output);
} finally {
closeAllSafely(outputStream);
}
Log.d("final","done");
Data output = new Data.Builder()
.putString("Response","succ")
.build();
return Result.success(output);
}
private void deleteTempFile() {
File file = new File(tempPath);
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
private boolean isSuccessful() {
return responseCode >= HttpURLConnection.HTTP_OK
&& responseCode < HttpURLConnection.HTTP_MULT_CHOICE;
}
private void setResumeSupportedOrNot() {
isResumeSupported = (responseCode == HttpURLConnection.HTTP_PARTIAL);
}
private boolean checkIfFreshStartRequiredAndStart(DownloadModel model) throws IOException,
IllegalAccessException {
if (responseCode == Constants.HTTP_RANGE_NOT_SATISFIABLE || isETagChanged(model)) {
if (model != null) {
removeNoMoreNeededModelFromDatabase();
}
deleteTempFile();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
httpClient = ComponentHolder.getInstance().getHttpClient();
httpClient.connect(request);
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
return true;
}
return false;
}
private boolean isETagChanged(DownloadModel model) {
return !(eTag == null || model == null || model.getETag() == null)
&& !model.getETag().equals(eTag);
}
private DownloadModel getDownloadModelIfAlreadyPresentInDatabase() {
return ComponentHolder.getInstance().getDbHelper().find(request.getDownloadId());
}
private void createAndInsertNewModel() {
DownloadModel model = new DownloadModel();
model.setId(request.getDownloadId());
model.setUrl(request.getUrl());
model.setETag(eTag);
model.setDirPath(request.getDirPath());
model.setFileName(request.getFileName());
model.setDownloadedBytes(request.getDownloadedBytes());
model.setTotalBytes(totalBytes);
model.setLastModifiedAt(System.currentTimeMillis());
ComponentHolder.getInstance().getDbHelper().insert(model);
}
private void removeNoMoreNeededModelFromDatabase() {
ComponentHolder.getInstance().getDbHelper().remove(request.getDownloadId());
}
private void sendProgress() {
if (request.getStatus() != Status.CANCELLED) {
Log.d("ttyl","ggyl");
if (progressHandler != null) {
Log.d("mozz","illa");
progressHandler
.obtainMessage(Constants.UPDATE,
new Progress(request.getDownloadedBytes(),
totalBytes)).sendToTarget();
}
else{
Log.d("maybe","into");
}
}
}
private void syncIfRequired(FileDownloadOutputStream outputStream) {
final long currentBytes = request.getDownloadedBytes();
final long currentTime = System.currentTimeMillis();
final long bytesDelta = currentBytes - lastSyncBytes;
final long timeDelta = currentTime - lastSyncTime;
if (bytesDelta > MIN_BYTES_FOR_SYNC && timeDelta > TIME_GAP_FOR_SYNC) {
sync(outputStream);
lastSyncBytes = currentBytes;
lastSyncTime = currentTime;
}
}
private void sync(FileDownloadOutputStream outputStream) {
boolean success;
try {
outputStream.flushAndSync();
success = true;
} catch (IOException e) {
success = false;
e.printStackTrace();
}
if (success && isResumeSupported) {
ComponentHolder.getInstance().getDbHelper()
.updateProgress(request.getDownloadId(),
request.getDownloadedBytes(),
System.currentTimeMillis());
}
}
private void closeAllSafely(FileDownloadOutputStream outputStream) {
if (httpClient != null) {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (outputStream != null) {
try {
sync(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String convertStreamToString(InputStream stream) {
StringBuilder stringBuilder = new StringBuilder();
if (stream != null) {
String line;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(stream));
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException ignored) {
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (NullPointerException | IOException ignored) {
}
}
}
return stringBuilder.toString();
}

Unable to see the winning move in tic tac toe app

I have a tic tac toe application which is only one little step away from being perfect. Basically the game works perfect during game play, the play makes a move by placing an X, then the computer makes a move a couple of seconds earlier placing their O and then it's back to the players move and then after their move a couple of seconds later the computer moves and etc.
The only issue I have which I cannot seem to figure out is when the game board resets. Basically when the winning move is made, we do not see the winning move, the board is reset, toast message is displayed stating who has won and if it is computers move first then their first move is made and this all happens at the same time. For the user they will be like what is going on how was the game won as it all happened in a flash.
I need to make a slight adjust so that the following happens:
1: Player sees the winning move either if it's their move or computers
2:
After seeing the winning move then the game board resets and the toast message appears stating who won or a draw
I don't mind the computer already making the first move already after the game board has reset, but the other two points I believe needs to be addressed.
Below is my code but I cannot seem to figure out how to ensure the above two points are reached when trying to manipulate the code:
public class MainActivityPlayer1 extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean playerOneMove = true;
private int turnsCount;
private int playerOnePoints;
private int playerTwoPoints;
private TextView textViewPlayerOne;
private TextView textViewPlayerTwo;
private TextView textViewPlayerOneTurn;
private TextView textViewPlayerTwoTurn;
private TextView textViewFooterTitle;
Button selectButton;
Random random = new Random();
boolean firstComputerMove = false;
int playerX = Color.parseColor("#e8e5e5");
int playerO = Color.parseColor("#737374");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player1);
Typeface customFont = Typeface.createFromAsset(getAssets(), "fonts/ConcertOne-Regular.ttf");
textViewPlayerOne = findViewById(R.id.textView_player1);
textViewPlayerTwo = findViewById(R.id.textView_player2);
textViewPlayerOneTurn = findViewById(R.id.textView_player1Turn);
textViewPlayerTwoTurn = findViewById(R.id.textView_player2Turn);
textViewFooterTitle = findViewById(R.id.footer_title);
textViewPlayerOne.setTypeface(customFont);
textViewPlayerTwo.setTypeface(customFont);
textViewFooterTitle.setTypeface(customFont);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
if (savedInstanceState != null) {
String btnState = savedInstanceState.getCharSequence(buttonID).toString();
if (btnState.equals("X")) {
buttons[i][j].setTextColor(playerX);
} else {
buttons[i][j].setTextColor(playerO);
}
}
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setTypeface(customFont);
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetGame();
}
});
Button buttonExit = findViewById(R.id.button_exit);
buttonExit.setTypeface(customFont);
buttonExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backToMainActivity();
}
});
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
turnsCount++;
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
isGameOver();
}
}
public void isGameOver() {
if (checkGameIsWon()) {
if (playerOneMove) {
player1Wins();
} else {
player2Wins();
}
} else if (turnsCount == 9) {
draw();
} else {
playerOneMove = !playerOneMove;
if (!playerOneMove) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
computerMove();
}
}, 1000);
}
}
}
private void computerMove() {
String[][] field = new String[3][3];
List<Button> emptyButtons = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
emptyButtons.add(buttons[i][j]);
}
}
}
//IS COMPUTER GOING FIRST
if (firstComputerMove == true){
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
else {
//TAKE MIDDLE SQUARE IF NOT TAKEN
if (field[1][1].equals("")) {
selectButton = buttons[1][1];
}
//FIRST ROW ACROSS
else if (field[0][0] != "" && field[0][0].equals(field[0][1])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
} else if (field[0][0] != "" && field[0][0].equals(field[0][2])
&& field[0][1].equals("")) {
selectButton = buttons[0][1];
} else if (field[0][1] != "" && field[0][1].equals(field[0][2])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
}
//SECOND ROW ACROSS
else if (field[1][0] != "" && field[1][0].equals(field[1][1])
&& field[1][2].equals("")) {
selectButton = buttons[1][2];
} else if (field[1][0] != "" && field[1][0].equals(field[1][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[1][1] != "" && field[1][1].equals(field[1][2])
&& field[1][0].equals("")) {
selectButton = buttons[1][0];
}
//THIRD ROW ACROSS
else if (field[2][0] != "" && field[2][0].equals(field[2][1])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[2][0] != "" && field[2][0].equals(field[2][2])
&& field[2][1].equals("")) {
selectButton = buttons[2][1];
} else if (field[2][1] != "" && field[2][1].equals(field[2][2])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
}
//FIRST COLUMN DOWN
else if (field[0][2] != "" && field[0][2].equals(field[1][2])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[0][2] != "" && field[0][2].equals(field[2][2])
&& field[1][2].equals("")) {
selectButton = buttons[1][2];
} else if (field[1][2] != "" && field[1][2].equals(field[2][2])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
}
//SECOND COLUMN DOWN
else if (field[0][1] != "" && field[0][1].equals(field[1][1])
&& field[2][1].equals("")) {
selectButton = buttons[2][1];
} else if (field[0][1] != "" && field[0][1].equals(field[2][1])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[1][1] != "" && field[1][1].equals(field[2][1])
&& field[0][1].equals("")) {
selectButton = buttons[0][1];
}
//THIRD COLUMN DOWN
else if (field[0][0] != "" && field[0][0].equals(field[1][0])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
} else if (field[0][0] != "" && field[0][0].equals(field[2][0])
&& field[1][0].equals("")) {
selectButton = buttons[1][0];
} else if (field[2][0] != "" && field[2][0].equals(field[1][0])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
}
//DIAGAONAL TOP RIGHT BOTTOM LEFT
else if (field[2][0] != "" && field[2][0].equals(field[0][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[2][0] != "" && field[2][0].equals(field[1][1])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
} else if (field[1][1] != "" && field[1][1].equals(field[0][2])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
}
//DIAGAONAL TOP LEFT BOTTOM RIGHT
else if (field[0][0] != "" && field[0][0].equals(field[2][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[0][0] != "" && field[0][0].equals(field[1][1])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[1][1] != "" && field[1][1].equals(field[2][2])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
} else {
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
}
selectButton.setText("O");
selectButton.setTextColor(playerO);
firstComputerMove = false;
turnsCount++;
isGameOver();
}
private boolean checkGameIsWon() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
private void player1Wins() {
playerOnePoints++;
Toast.makeText(this, "Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
playerTwoPoints++;
Toast.makeText(this, "Computer wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
firstComputerMove = true;
computerMove();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
playerOneMove = !playerOneMove;
switchPlayerTurn();
if (!playerOneMove){
firstComputerMove = true;
computerMove();
}
}
#SuppressLint("SetTextI18n")
private void updatePointsText() {
textViewPlayerOne.setText("PLAYER 1: " + playerOnePoints + " ");
textViewPlayerTwo.setText("COMPUTER: " + playerTwoPoints + " ");
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
turnsCount = 0;
switchPlayerTurn();
}
private void resetGame() {
playerOnePoints = 0;
playerTwoPoints = 0;
turnsCount = 0;
playerOneMove = true;
updatePointsText();
resetBoard();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("turnsCount", turnsCount);
outState.putInt("playerOnePoints", playerOnePoints);
outState.putInt("playerTwoPoints", playerTwoPoints);
outState.putBoolean("playerOneMove", playerOneMove);
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
outState.putCharSequence(buttonID, btn.getText());
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { ;
super.onRestoreInstanceState(savedInstanceState);
turnsCount = savedInstanceState.getInt("turnsCount");
playerOnePoints = savedInstanceState.getInt("playerOnePoints");
playerTwoPoints = savedInstanceState.getInt("playerTwoPoints");
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
savedInstanceState.putCharSequence(buttonID, btn.getText());
}
}
}
private void switchPlayerTurn(){
if (playerOneMove){
textViewPlayerOneTurn.setVisibility(View.VISIBLE);
textViewPlayerTwoTurn.setVisibility(View.INVISIBLE);
}
else{
textViewPlayerOneTurn.setVisibility(View.INVISIBLE);
textViewPlayerTwoTurn.setVisibility(View.VISIBLE);
}
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
}
I would recommend that you use Thread.sleep if a player wins to give time to show the final move.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resetBoard();
firstComputerMove = true;
computerMove();
You could also incorporate an AlertDialog to ask the user to play again after pause and the final move
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("Play again?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Play Again
resetBoard();
firstComputerMove = true;
computerMove();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Exit Game
}
})
.show();

how can I add single button programmatically to this activity? ( Telegram api)

actually I'm using this part of code but nothing shown in screen
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, elativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
And this is the activity codes
public class LaunchActivity extends Activity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationCenter.NotificationCenterDelegate, DialogsActivity.DialogsActivityDelegate {
private boolean finished;
private String videoPath;
private String sendingText;
private ArrayList<Uri> photoPathsArray;
private ArrayList<String> documentsPathsArray;
private ArrayList<Uri> documentsUrisArray;
private String documentsMimeType;
private ArrayList<String> documentsOriginalPathsArray;
private ArrayList<TLRPC.User> contactsToSend;
private int currentConnectionState;
private static ArrayList<BaseFragment> mainFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> layerFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> rightFragmentsStack = new ArrayList<>();
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;
private ActionBarLayout actionBarLayout;
private ActionBarLayout layersActionBarLayout;
private ActionBarLayout rightActionBarLayout;
private FrameLayout shadowTablet;
private FrameLayout shadowTabletSide;
private View backgroundTablet;
protected DrawerLayoutContainer drawerLayoutContainer;
private DrawerLayoutAdapter drawerLayoutAdapter;
private PasscodeView passcodeView;
private AlertDialog visibleDialog;
private RecyclerListView sideMenu;
private AlertDialog localeDialog;
private boolean loadingLocaleDialog;
private HashMap<String, String> systemLocaleStrings;
private HashMap<String, String> englishLocaleStrings;
private Intent passcodeSaveIntent;
private boolean passcodeSaveIntentIsNew;
private boolean passcodeSaveIntentIsRestore;
private boolean tabletFullSize;
private Runnable lockRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
ApplicationLoader.postInitApplication();
NativeCrashManager.handleDumpFiles(this);
AndroidUtilities.checkDisplaySize(this, getResources().getConfiguration());
Log.i(this.getClass().getName(), "onCreate: ");
if (!UserConfig.isClientActivated()) {
Intent intent = getIntent();
if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
super.onCreate(savedInstanceState);
finish();
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
long crashed_time = preferences.getLong("intro_crashed_time", 0);
boolean fromIntro = intent.getBooleanExtra("fromIntro", false);
if (fromIntro) {
preferences.edit().putLong("intro_crashed_time", 0).commit();
}
if (Math.abs(crashed_time - System.currentTimeMillis()) >= 60 * 2 * 1000 && intent != null && !fromIntro) {
preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", MODE_PRIVATE);
Map<String, ?> state = preferences.getAll();
if (state.isEmpty()) {
Intent intent2 = new Intent(this, IntroActivity.class);
intent2.setData(intent.getData());
startActivity(intent2);
super.onCreate(savedInstanceState);
finish();
return;
}
}
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(R.style.Theme_TMessages);
getWindow().setBackgroundDrawableResource(R.drawable.transparent);
if (UserConfig.passcodeHash.length() > 0 && !UserConfig.allowScreenCapture) {
try {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
FileLog.e(e);
}
}
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 24) {
AndroidUtilities.isInMultiwindow = isInMultiWindowMode();
}
Theme.createChatResources(this, false);
if (UserConfig.passcodeHash.length() != 0 && UserConfig.appLocked) {
UserConfig.lastPauseTime = ConnectionsManager.getInstance().getCurrentTime();
}
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
actionBarLayout = new ActionBarLayout(this);
drawerLayoutContainer = new DrawerLayoutContainer(this);
setContentView(drawerLayoutContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
if (AndroidUtilities.isTablet()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
RelativeLayout launchLayout = new RelativeLayout(this) {
private boolean inLayout;
#Override
public void requestLayout() {
if (inLayout) {
return;
}
super.requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
inLayout = true;
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
tabletFullSize = false;
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTabletSide.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
rightActionBarLayout.measure(MeasureSpec.makeMeasureSpec(width - leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
} else {
tabletFullSize = true;
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
backgroundTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
layersActionBarLayout.measure(MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(530), width), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(528), height), MeasureSpec.EXACTLY));
inLayout = false;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
shadowTabletSide.layout(leftWidth, 0, leftWidth + shadowTabletSide.getMeasuredWidth(), shadowTabletSide.getMeasuredHeight());
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
rightActionBarLayout.layout(leftWidth, 0, leftWidth + rightActionBarLayout.getMeasuredWidth(), rightActionBarLayout.getMeasuredHeight());
} else {
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
}
int x = (width - layersActionBarLayout.getMeasuredWidth()) / 2;
int y = (height - layersActionBarLayout.getMeasuredHeight()) / 2;
layersActionBarLayout.layout(x, y, x + layersActionBarLayout.getMeasuredWidth(), y + layersActionBarLayout.getMeasuredHeight());
backgroundTablet.layout(0, 0, backgroundTablet.getMeasuredWidth(), backgroundTablet.getMeasuredHeight());
shadowTablet.layout(0, 0, shadowTablet.getMeasuredWidth(), shadowTablet.getMeasuredHeight());
}
};
drawerLayoutContainer.addView(launchLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
backgroundTablet = new View(this);
//BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.catstile);
//drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
backgroundTablet.setBackgroundResource(R.drawable.catstile);
launchLayout.addView(backgroundTablet, LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
launchLayout.addView(actionBarLayout);
rightActionBarLayout = new ActionBarLayout(this);
rightActionBarLayout.init(rightFragmentsStack);
rightActionBarLayout.setDelegate(this);
launchLayout.addView(rightActionBarLayout);
shadowTabletSide = new FrameLayout(this);
shadowTabletSide.setBackgroundColor(0x40295274);
launchLayout.addView(shadowTabletSide);
shadowTablet = new FrameLayout(this);
shadowTablet.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
shadowTablet.setBackgroundColor(0x7f000000);
launchLayout.addView(shadowTablet);
shadowTablet.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!actionBarLayout.fragmentsStack.isEmpty() && event.getAction() == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
int location[] = new int[2];
layersActionBarLayout.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
if (layersActionBarLayout.checkTransitionAnimation() || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY && y < viewY + layersActionBarLayout.getHeight()) {
return false;
} else {
if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
a--;
}
layersActionBarLayout.closeLastFragment(true);
}
return true;
}
}
return false;
}
});
shadowTablet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layersActionBarLayout = new ActionBarLayout(this);
layersActionBarLayout.setRemoveActionBarExtraHeight(true);
layersActionBarLayout.setBackgroundView(shadowTablet);
layersActionBarLayout.setUseAlphaAnimations(true);
layersActionBarLayout.setBackgroundResource(R.drawable.boxshadow);
layersActionBarLayout.init(layerFragmentsStack);
layersActionBarLayout.setDelegate(this);
layersActionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
layersActionBarLayout.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
launchLayout.addView(layersActionBarLayout);
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
} else {
drawerLayoutContainer.addView(actionBarLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
sideMenu = new RecyclerListView(this);
sideMenu.setBackgroundColor(Theme.getColor(Theme.key_chats_menuBackground));
sideMenu.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
sideMenu.setAdapter(drawerLayoutAdapter = new DrawerLayoutAdapter(this));
drawerLayoutContainer.setDrawerLayout(sideMenu);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) sideMenu.getLayoutParams();
Point screenSize = AndroidUtilities.getRealScreenSize();
layoutParams.width = AndroidUtilities.isTablet() ? AndroidUtilities.dp(320) : Math.min(AndroidUtilities.dp(320), Math.min(screenSize.x, screenSize.y) - AndroidUtilities.dp(56));
layoutParams.height = LayoutHelper.MATCH_PARENT;
sideMenu.setLayoutParams(layoutParams);
sideMenu.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
#Override
public void onItemClick(final View view, int position) {
int id = drawerLayoutAdapter.getId(position);
if (position == 0) {
Bundle args = new Bundle();
args.putInt("user_id", UserConfig.getClientUserId());
presentFragment(new ChatActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 2) {
if (!MessagesController.isFeatureEnabled("chat_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
presentFragment(new GroupCreateActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 3) {
Bundle args = new Bundle();
args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true);
args.putBoolean("createSecretChat", true);
args.putBoolean("allowBots", false);
presentFragment(new ContactsActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 4) {
if (!MessagesController.isFeatureEnabled("broadcast_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (!BuildVars.DEBUG_VERSION && preferences.getBoolean("channel_intro", false)) {
Bundle args = new Bundle();
args.putInt("step", 0);
presentFragment(new ChannelCreateActivity(args));
} else {
presentFragment(new ChannelIntroActivity());
preferences.edit().putBoolean("channel_intro", true).commit();
}
drawerLayoutContainer.closeDrawer(false);
} else if (id == 6) {
presentFragment(new ContactsActivity(null));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 7) {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
/*AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTopImage(R.drawable.permissions_contacts, 0xff35a8e0);
builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("ContactsPermissionAlert", R.string.ContactsPermissionAlert)));
builder.setPositiveButton(LocaleController.getString("ContactsPermissionAlertContinue", R.string.ContactsPermissionAlertContinue), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(LocaleController.getString("ContactsPermissionAlertNotNow", R.string.ContactsPermissionAlertNotNow), null);
showAlertDialog(builder);*/
showLanguageAlert(true);
} else {
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText());
startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500);
} catch (Exception e) {
FileLog.e(e);
}
drawerLayoutContainer.closeDrawer(false);
}
} else if (id == 8) {
presentFragment(new SettingsActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 9) {
Browser.openUrl(LaunchActivity.this, LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 10) {
presentFragment(new CallLogActivity());
drawerLayoutContainer.closeDrawer(false);
}
}
});
drawerLayoutContainer.setParentActionBarLayout(actionBarLayout);
actionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
actionBarLayout.init(mainFragmentsStack);
actionBarLayout.setDelegate(this);
Theme.loadWallpaper();
passcodeView = new PasscodeView(this);
drawerLayoutContainer.addView(passcodeView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this);
currentConnectionState = ConnectionsManager.getInstance().getConnectionState();
NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.needShowAlert);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.wasUnableToFindCurrentLocation);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetNewWallpapper);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetPasscode);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadInterface);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.suggestedLangpack);
if (actionBarLayout.fragmentsStack.isEmpty()) {
if (!UserConfig.isClientActivated()) {
actionBarLayout.addFragmentToStack(new LoginActivity());
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
DialogsActivity dialogsActivity = new DialogsActivity(null);
dialogsActivity.setSideMenu(sideMenu);
actionBarLayout.addFragmentToStack(dialogsActivity);
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
try {
if (savedInstanceState != null) {
String fragmentName = savedInstanceState.getString("fragment");
if (fragmentName != null) {
Bundle args = savedInstanceState.getBundle("args");
switch (fragmentName) {
case "chat":
if (args != null) {
ChatActivity chat = new ChatActivity(args);
if (actionBarLayout.addFragmentToStack(chat)) {
chat.restoreSelfArgs(savedInstanceState);
}
}
break;
case "settings": {
SettingsActivity settings = new SettingsActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
case "group":
if (args != null) {
GroupCreateFinalActivity group = new GroupCreateFinalActivity(args);
if (actionBarLayout.addFragmentToStack(group)) {
group.restoreSelfArgs(savedInstanceState);
}
}
break;
case "channel":
if (args != null) {
ChannelCreateActivity channel = new ChannelCreateActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "edit":
if (args != null) {
ChannelEditActivity channel = new ChannelEditActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "chat_profile":
if (args != null) {
ProfileActivity profile = new ProfileActivity(args);
if (actionBarLayout.addFragmentToStack(profile)) {
profile.restoreSelfArgs(savedInstanceState);
}
}
break;
case "wallpapers": {
WallpapersActivity settings = new WallpapersActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
if (fragment instanceof DialogsActivity) {
((DialogsActivity) fragment).setSideMenu(sideMenu);
}
boolean allowOpen = true;
if (AndroidUtilities.isTablet()) {
allowOpen = actionBarLayout.fragmentsStack.size() <= 1 && layersActionBarLayout.fragmentsStack.isEmpty();
if (layersActionBarLayout.fragmentsStack.size() == 1 && layersActionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
}
if (actionBarLayout.fragmentsStack.size() == 1 && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false);
}
checkLayout();
handleIntent(getIntent(), false, savedInstanceState != null, false);
try {
String os1 = Build.DISPLAY;
String os2 = Build.USER;
if (os1 != null) {
os1 = os1.toLowerCase();
} else {
os1 = "";
}
if (os2 != null) {
os2 = os1.toLowerCase();
} else {
os2 = "";
}
if (os1.contains("flyme") || os2.contains("flyme")) {
AndroidUtilities.incorrectDisplaySizeFix = true;
final View view = getWindow().getDecorView().getRootView();
view.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if (Build.VERSION.SDK_INT >= 21) {
height -= AndroidUtilities.statusBarHeight;
}
if (height > AndroidUtilities.dp(100) && height < AndroidUtilities.displaySize.y && height + AndroidUtilities.dp(100) > AndroidUtilities.displaySize.y) {
AndroidUtilities.displaySize.y = height;
FileLog.e("fix display size y to " + AndroidUtilities.displaySize.y);
}
}
});
}
} catch (Exception e) {
FileLog.e(e);
}
MediaController.getInstance().setBaseActivity(this, true);
}

ClassCast exception Java generic types

first time asking around here. I'm doing an AVLTree generic and there is a method in the Node that gives me an Iterator that returns me a Object array. The thing is that when I try to get that array with the objects of one of my none generic classes it sends me this.
Exception in thread "main" java.lang.ClassCastException: [LestructuraDeDatos.NodoAVL; cannt be cast to [Lmundo.Categoria;
Here is the node class
public class NodoAVL <T extends Comparable <T>>
{
//--------------------------------------------------------------------------------------------
//Atributos
//--------------------------------------------------------------------------------------------
private NodoAVL<T> izquierdo;
private NodoAVL<T> derecho;
private T elemento;
private String criterio;
//--------------------------------------------------------------------------------------------
//Constructor
//--------------------------------------------------------------------------------------------
public NodoAVL(T elem, String crit)
{
elemento = elem;
izquierdo = null;
derecho = null;
criterio = crit;
}
//--------------------------------------------------------------------------------------------
//Metodos
//--------------------------------------------------------------------------------------------
public NodoAVL<T> getIzquierdo() {
return izquierdo;
}
public void setIzquierdo(NodoAVL<T> izquierdo) {
this.izquierdo = izquierdo;
}
public NodoAVL<T> getDerecho() {
return derecho;
}
public void setDerecho(NodoAVL<T> derecho) {
this.derecho = derecho;
}
public String getCriterio() {
return criterio;
}
public void setCriterio(String criterio) {
this.criterio = criterio;
}
public boolean soyHoja()
{
if(izquierdo == null && derecho == null)
{
return true;
}
return false;
}
public T getElemento() {
return elemento;
}
public void setElemento(T elemento) {
this.elemento = elemento;
}
public void agregarElemento(T elemento, String Crit)
{
//Buscarlo antes de agregar, no puede haber iguales en el arbol
if(buscarElemento(Crit)==null)
if(soyHoja())
{
if(elemento.compareTo(this.elemento)>0)
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento, Crit);
setDerecho(nuevo);
}else if(elemento.compareTo(this.elemento)<0)
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento, Crit);
setIzquierdo(nuevo);
}
}else
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento,Crit);
if(this.elemento.compareTo(elemento)>0 && izquierdo == null)
{
izquierdo = nuevo;
}
else if(this.elemento.compareTo(elemento)>0)
{
izquierdo.agregarElemento(elemento,Crit);
}
else if(this.elemento.compareTo(elemento)<0 && derecho == null)
{
derecho = nuevo;
}
else if( this.elemento.compareTo(elemento)<0)
{
derecho.agregarElemento(elemento, Crit);
}
}
balanciarSubArbol();
}
public NodoAVL<T> rotarIzq(NodoAVL<T> rotar)
{
NodoAVL<T> temp = rotar.derecho;
rotar.setDerecho(temp.izquierdo);
temp.setIzquierdo(rotar);
return temp;
}
public NodoAVL<T> rotarDer(NodoAVL<T> rotar)
{
NodoAVL<T> temp = rotar.izquierdo;
rotar.setIzquierdo(temp.derecho);
temp.setDerecho(rotar);
return temp;
}
public int darBalance()
{
if(soyHoja())
{
return 0;
}
else
{
int izq = (izquierdo == null)?0:izquierdo.darAltura();
int der = (derecho == null)? 0 :derecho.darAltura();
return (izq - der);
}
}
public NodoAVL<T> dobleRotacionDerIzq(NodoAVL<T> nodo)
{
nodo.setDerecho(rotarDer(nodo.getDerecho()));
return rotarIzq(nodo);
}
public NodoAVL<T> dobleRotacionIzqDer(NodoAVL<T> nodo)
{
nodo.setIzquierdo(rotarIzq(nodo.getIzquierdo()));
return rotarDer(nodo);
}
public void balanciarSubArbol()
{
int valor = darBalance();
if(-2==valor || valor==2)
{
if(valor<0 && derecho.darBalance()<0)
{
if(derecho.darBalance()<-2)
{
derecho.balanciarSubArbol();
}else
{
rotarIzq(this);
}
}else if(valor<0 && derecho.darBalance()>0)
{
if(derecho.darBalance()>2)
{
derecho.balanciarSubArbol();
}else
{
dobleRotacionDerIzq(this);
}
}else if(valor>0 && izquierdo.darBalance()>0)
{
if(izquierdo.darBalance()>2)
{
izquierdo.balanciarSubArbol();
}else
{
rotarDer(this);
}
}else if(valor>0 && izquierdo.darBalance()<0)
{
if(izquierdo.darBalance()<-2)
{
izquierdo.balanciarSubArbol();
}else
{
dobleRotacionIzqDer(this);
}
}
}
}
public NodoAVL<T> eliminarElemento(T elemento)
{
if(soyHoja() && this.elemento==elemento)
{
return null;
}else if(soyHoja() && this.elemento!=elemento)
{
return this;
}
else
{
if(this.elemento.compareTo(elemento)==0)
{
if(izquierdo != null && derecho != null)
{
NodoAVL<T> temp = derecho;
izquierdo.setDerecho(temp.getIzquierdo());
temp.setIzquierdo(izquierdo);
return temp;
}
else if(izquierdo != null)
{
return izquierdo;
}
else
{
return derecho;
}
}
else if(this.elemento.compareTo(elemento)>0)
{
izquierdo = izquierdo.eliminarElemento(elemento);
return this;
}
else if(this.elemento.compareTo(elemento)<0)
{
derecho = derecho.eliminarElemento(elemento);
return this;
}
balanciarSubArbol();
return this;
}
}
public T buscarElemento(String criterio)
{
if(this.criterio.equalsIgnoreCase(criterio))
{
return this.elemento;
}
else
{
T izq = (izquierdo != null)?izquierdo.buscarElemento(criterio):null;
T der = (derecho != null) ? derecho.buscarElemento(criterio):null;
if(izq != null)
{
return izq;
}else if(der != null)
{
return der;
}
}
return null;
}
public IteradorAVL<T> darElementos()
{
IteradorAVL<T> ite = new IteradorAVL<T> (this);
return ite;
}
public int darPeso()
{
if(soyHoja())
{
return 1;
}else
{
int izq = (izquierdo == null)? 0: izquierdo.darPeso();
int der = (derecho == null) ? 0:derecho.darPeso();
return (izq+der+1);
}
}
public int darAltura()
{
if(soyHoja())
{
return 1;
}
else
{
int izq = ( izquierdo == null ) ? 0 : izquierdo.darAltura( );
int der = ( derecho == null ) ? 0 : derecho.darAltura( );
return(izq>der || izq == der)?izq+1:der+1;
}
}
}
and the iterator class
public class IteradorAVL<T extends Comparable <T>> implements Iterator<T>{
//--------------------------------------------------------------------------------------------
//Atributos
//--------------------------------------------------------------------------------------------
private NodoAVL<T> arbolitoAVL;
private Object [] elementos;
private int posActual;
private int total;
private Stack<NodoAVL> nodePath = new Stack<NodoAVL>();
//--------------------------------------------------------------------------------------------
//Constructor
//--------------------------------------------------------------------------------------------
public IteradorAVL ( NodoAVL <T> nodo)
{
arbolitoAVL = nodo;
posActual = 0;
total = nodo.darPeso();
elementos = new NodoAVL[total];
}
//--------------------------------------------------------------------------------------------
//Metodos
//--------------------------------------------------------------------------------------------
#Override
public boolean hasNext()
{
return(total>posActual)?true:false;
}
#Override
public T next() {
T siguienteT =null;
NodoAVL<T> respuesta = arbolitoAVL;
//Guardo el nodo actual en la lista
//Avancce
while (arbolitoAVL != null) {
nodePath.push(arbolitoAVL);
elementos[posActual] = arbolitoAVL;
arbolitoAVL = arbolitoAVL.getIzquierdo();
posActual++;
}
if (!nodePath.isEmpty()) {
arbolitoAVL = nodePath.pop();
posActual++;
elementos[posActual] = arbolitoAVL;
siguienteT = arbolitoAVL.getElemento();
arbolitoAVL = arbolitoAVL.getDerecho();
}
return siguienteT;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
public Object[] darArreglo()
{
return elementos;
}
The reason ClassCastException occurs is only one that your trying to typecast an object of one class to an object of another class which are not compatible.
Example :
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.

how to random questions in the quiz using JSON array in android?

i developing a quiz wherein i have 50 questions stored and i want it to display random in the quiz everytime the user will play..how can i do that? is it possible to randomize question using json?please help me.. i really appreciate ur help..thanks.
public class Question1 extends Activity {
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question10);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1 * 1000);
finish();
loadQuestions();
Intent intent = new Intent(Question1.this,
Question2.class);
Question1.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList(){
return quesList;
}
}
public class Question2 extends Activity {
/** Called when the activity is first created. */
TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startquiz);
try {
items = (TextView)findViewById(R.id.displayitems);
question = (TextView) findViewById(R.id.displayquestion);
answer1 = (RadioButton) findViewById(R.id.option1);
answer2 = (RadioButton) findViewById(R.id.option2);
answer3 = (RadioButton) findViewById(R.id.option3);
answers = (RadioGroup) findViewById(R.id.QueGroup1);
next = (Button) findViewById(R.id.selected);
next.setOnClickListener(nextListener);
selected = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0, review);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex, boolean review) {
try {
JSONObject aQues = Question1.getQuesList().getJSONObject(
qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.BLACK);
answer2.setTextColor(Color.BLACK);
answer3.setTextColor(Color.BLACK);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("", selected[qIndex] + "");
if (selected[qIndex] == 0)
answers.check(R.id.option1);
if (selected[qIndex] == 1)
answers.check(R.id.option2);
if (selected[qIndex] == 2)
answers.check(R.id.option3);
setText();
if (quesIndex == (Question1.getQuesList().length() - 1))
next.setEnabled(false);
if (quesIndex < (Question1.getQuesList().length() - 1))
next.setEnabled(true);
if (review) {
Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
Log.d("", Arrays.toString(selected));
Log.d("", Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) || (correctAns[i] == selected[i]))
{
if (correctAns[i] == selected[i])
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
quesIndex++;
if (quesIndex >= Question1.getQuesList().length())
//quesIndex = Question1.getQuesList().length() - 1;
showQuestion(quesIndex, review);
}
}
};
private void setText() {
this.setTitle("Question " + (quesIndex + 1) + "out of "
+ Question1.getQuesList().length());
items.setGravity(250);
}
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
Use ((int) Math.random() * <size of your array>) to generate a random index for your array of questions

Categories

Resources