I have two TextView, two EditText and two Buttons. I want to set a DialogBox or Toast when the button is clicked without entering any values in the textview. I have two stings, s and s1. If s and s1 or either s or s1 is not entered in the edittext, I must get a toast. I wrote a code for toast but it's not working fine!
Can you help me with this?
This is my code:
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
AnimationDrawable frameanimation;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender=(Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview=(ImageView)findViewById(R.id.imageanim);
imgview.setBackgroundResource(R.drawable.myanim);
frameanimation=(AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
//code for toast//
//if s nd s1 is empty then execute this else executee the rest//
if((s==" ") && (s1==" "))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
else
{
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0,
n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
Change your validation to this :
if((s.equals("")) && (s1.equals("")))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}
Or you can check like this:
if((s.length() == 0) && (s1.length() == 0))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
Tried your code and validation is working :
import java.io.DataInputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN
// ,WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender = (Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview = (ImageView) findViewById(R.id.imageanim);
frameanimation = (AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
// code for toast//
// if s nd s1 is empty then execute this else executee the rest//
if ((s.equals("")) || (s1.equals(""))) {
Toast.makeText(getBaseContext(), "cnt b empty",
Toast.LENGTH_SHORT).show();
} else {
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0, n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
}
}
}
Try if (s.isEmpty() || s1.isEmpty()) to check if your strings are empty. == and .equals will not work with string comparison because they are comparing the objects and not solely the contents. To check if two strings are equal, you can use firstString.compareTo(anotherString) == 0.
Trim your edittext value then compare
if((("").equals(s.trim())) && (("").equals(s1.trim())))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}
Related
Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);
When I run the game using unity I get this error continuously in the console window and the loading screen is not going further next. Help me to fix this issue.
IndexOutOfRangeException: Array index is out of range.
DataCache.GetAchievementCacheData () (at
Assets/Scripts/Mission/Plugin/DataCache.cs:329)
Here is my code below
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;
//Class luu mission current
public class CurrentMission
{
public string FB_id { get; set; }
public string Name { get; set; }
public string Mission { get; set; }
public CurrentMission(string id, string name, string mission)
{
this.FB_id = id;
this.Name = name;
this.Mission = mission;
}
public CurrentMission()
{
this.FB_id = "";
this.Name = "";
this.Mission = "";
}
}
public class MissionDataSave
{
public int Mission;
public long Score;
public int Star;
public int Open;//0-false. 1-true
public MissionDataSave(int mission, long score, int star, int open)
{
Mission = mission;
Score = score;
Star = star;
Open = open;
}
public MissionDataSave()
{
Mission = 0;
Score = 0;
Star = 0;
Open = 0;
}
}
public class AchievementCache
{
//group nhiem vu
public int Group;
//Level hien tai cua group
public int Level;
//Gia tri hien tai
public int Value;
//Thong bao mission hoan thanh
public int Notify;//0 - False, 1 - true
//public AchievementCache()
//{
// this.Group = 1;
// this.Level = 1;
// this.Value = 0;
//}
public AchievementCache(int group, int level, int value, int notify)
{
this.Group = group;
this.Value = value;
this.Level = level;
this.Notify = notify;
}
public AchievementCache()
{
this.Group = 1;
this.Value = 0;
this.Level = 1;
this.Notify = 0;
}
}
public class DataCache
{
public static string FB_ID = "FB_ID";
public static string FB_USER = "FB_USER";
public static string Achievement_data_key = "Achievement_data_key";
public static string Mission_data_key = "Mission_data_key";
public static string Current_mission_data_key = "Current_mission_data_key";
public static AchievementCache[] dataAchievementCache;
public static MissionDataSave[] dataMissionCache;
public static CurrentMission[] dataCurrentMissionCache;
//public static string XML_Current_Mission_Path = "CurrentMissionSave.xml";
//public static string XML_Data_Mission_Path = "DataMissionSave.xml";
//public static string XML_Data_Achievement_Path = "AchievementCache.xml";
//serialize xml theo tung phan tu
//public static List<MissionDataSave> DeserializeMissionDataSaveListFromXML(string filePath)
//{
// if (!System.IO.File.Exists(filePath))
// {
// Debug.LogError("File " + filePath + " not exist!");
// return new List<MissionDataSave>();
// }
// XmlSerializer deserializer = new XmlSerializer(typeof(List<MissionDataSave>), new XmlRootAttribute("MissionDataSaveRoot"));
// TextReader textReader = new StreamReader(filePath);
// List<MissionDataSave> movies = (List<MissionDataSave>)deserializer.Deserialize(textReader);
// textReader.Close();
// return movies;
//}
//public static void readXMLTest()
//{
// string xmlDataCache1 = Application.persistentDataPath + "/" + XML_Current_Mission_Path;
// TextReader textReader = new StreamReader(xmlDataCache1);
// XmlDocument xmlDoc = new XmlDocument();
// xmlDoc.Load(textReader);
// XmlNodeList xmlNodeList = xmlDoc.DocumentElement.ChildNodes;
// Debug.Log("TRUOC");
// foreach (XmlNode node in xmlNodeList)
// {
// Debug.Log("aaaaaaaaaaaaaaaaaaaaa " + node.Attributes["Id"].Value);
// }
// Debug.Log("SAU");
// XmlNode root = xmlDoc.DocumentElement;
// XmlElement elem = xmlDoc.CreateElement("CurrentMissionCache");
// elem.SetAttribute("Id", "112312");
// elem.SetAttribute("Name", "NameDG");
// elem.SetAttribute("Mission", "MissionDG");
// root.AppendChild(elem);
// textReader.Close();
// xmlDoc.Save(xmlDataCache1);
//}
//Add mission xml node
public static void UpdateMissionScore(long score, int star, int mission, int open)
{
MissionDataSave data = dataMissionCache[mission - 1];
if (data.Star < star)
{
data.Star = star;
}
if (data.Score < score)
{
data.Score = score;
}
data.Open = open;
}
public static void SaveMissionDataCache(bool submitToServer = false)
{
string dataSave = "";
string dataSendServer = "";
for (int i = 0; i < dataMissionCache.Length; i++)
{
dataSave += dataMissionCache[i].Mission + "-" + dataMissionCache[i].Score + "-" + dataMissionCache[i].Star + "-" + dataMissionCache[i].Open + ",";
//Chi gui nhung mission da open len server
if (dataMissionCache[i].Open == 1)
{
if (dataSendServer.Length > 0)
dataSendServer += ",";
dataSendServer += dataMissionCache[i].Mission + "-" + dataMissionCache[i].Score + "-" + dataMissionCache[i].Star + "-" + dataMissionCache[i].Open;
}
}
Debug.Log("Data save " + dataSave);
PlayerPrefs.SetString(Mission_data_key, dataSave);
if (submitToServer)
{
Debug.Log("Data send server " + dataSendServer);
AudioControl.getMonoBehaviour().StartCoroutine(DHS.PostMeInfoMissionUpdate(FB.UserId, dataSendServer));
}
}
public static void GetMissionDataCache()
{
int max_mission = 100;
if (dataMissionCache != null)
{
dataMissionCache = null;
}
dataMissionCache = new MissionDataSave[max_mission];
//Tao moi neu chua co
if (!PlayerPrefs.HasKey(Mission_data_key))
{
string datas = "1-0-0-1,";
for (int i = 2; i <= max_mission; i++)
{
//Mission - Score - Star - Open
if (DataMissionControlNew.test)
{
datas += i + "-0-0-1,";
//if (i < 16)
// datas += i + "-0-0-1,";
//else datas += i + "-0-0-0,";
}
else
{
datas += i + "-0-0-0,";
}
}
PlayerPrefs.SetString(Mission_data_key, datas);
}
string missionData = PlayerPrefs.GetString(Mission_data_key);
string[] data = missionData.Split(',');
for (int i = 0; i < max_mission; i++)
{
string[] infoData = data[i].Split('-');
//Debug.Log("Info " + data[i]);
string mission = infoData[0];
string score = infoData[1];
string star = infoData[2];
string open = infoData[3];
dataMissionCache[i] = new MissionDataSave(Convert.ToUInt16(mission), Convert.ToUInt32(score), Convert.ToUInt16(star), Convert.ToUInt16(open));
}
}
//-------------------------CURRENT MISSION---------------------------
//Add current mission xml node
public static void SaveCurrentMission(string data = "")
{
if (String.IsNullOrEmpty(data))
{
string dataSave = "";
for (int i = 0; i < dataCurrentMissionCache.Length; i++)
{
if (dataSave.Length > 0)
dataSave += ",";
dataSave += dataCurrentMissionCache[i].FB_id + "-" + dataCurrentMissionCache[i].Name + "-" + dataCurrentMissionCache[i].Mission;
}
PlayerPrefs.SetString(Current_mission_data_key, dataSave);
}
else
{
PlayerPrefs.SetString(Current_mission_data_key, data);
GetCurrentMission();
}
}
public static void GetCurrentMission()
{
if (!PlayerPrefs.HasKey(Current_mission_data_key))
{
PlayerPrefs.SetString(Current_mission_data_key, "Me-User-1");
}
if (dataCurrentMissionCache != null)
{
dataCurrentMissionCache = null;
}
string current_data = PlayerPrefs.GetString(Current_mission_data_key);
string[] data = current_data.Split(',');
dataCurrentMissionCache = new CurrentMission[data.Length];
for (int i = 0; i < data.Length; i++)
{
string[] info = data[i].Split('-');
//fb - User name - missison
dataCurrentMissionCache[i] = new CurrentMission(info[0], info[1], info[2]);
}
}
public static void SetMeCurrentMission(int mission)
{
for (int i = 0; i < DataCache.dataCurrentMissionCache.Length; i++)
{
if ("Me".Equals(DataCache.dataCurrentMissionCache[i].FB_id))
{
int old = Convert.ToInt16(DataCache.dataCurrentMissionCache[i].Mission);
if (old < mission)
{
DataCache.dataCurrentMissionCache[i].Mission = "" + mission;
DataCache.UpdateMissionScore(0, 0, mission, 1);//Them mission moi vao xml
}
}
}
DataCache.SaveCurrentMission();
}
//-------------------------ACHIEVEMENT---------------------------
//Ghi de len du lieu cu
public static void ReplaceAchievementCache(int groupLevel, int value, int level = -1)
{
dataAchievementCache[groupLevel - 1].Value = value;
if (level != -1)
{
dataAchievementCache[groupLevel - 1].Level = level;
}
}
//Cap nhat them du lieu
public static void AddAchievementCache(int groupLevel, int addValue, int addLevel = 0)
{
dataAchievementCache[groupLevel - 1].Level += addLevel;
dataAchievementCache[groupLevel - 1].Value += addValue;
}
public static void GetAchievementCacheData()
{
Debug.Log("-------------GetAchievementCacheData--------------------");
if (dataAchievementCache != null)
{
dataAchievementCache = null;
}
dataAchievementCache = new AchievementCache[22];
//Tao achievement
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
string achi = "";
for (int i = 1; i <= 22; i++)
{
achi += i + "-1-0-0,";
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi);
}
string achievement = PlayerPrefs.GetString(Achievement_data_key);
//Debug.Log(achievement);
string[] achie = achievement.Split(',');
for (int i = 0; i< dataAchievementCache.Length; i++)
{
//Debug.Log(achie[i]);
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
string value = infoAchie[2];
string notify = infoAchie[3];
//Debug.Log(group +" " + dataAchievementCache[i].Group);
dataAchievementCache[i] = new AchievementCache();
dataAchievementCache[i].Group = Convert.ToInt16(group);
dataAchievementCache[i].Level = Convert.ToInt16(level);
dataAchievementCache[i].Value = Convert.ToInt32(value);
dataAchievementCache[i].Notify = Convert.ToInt16(notify);
}
}
public static void SaveAchievementCache(bool sendServer = false)
{
try
{
Debug.Log("-------------------SaveAchievementCache-----------------");
if (dataAchievementCache != null)
{
string achievement = "";
for (int i = 0; i < dataAchievementCache.Length; i++)
{
string s = "" + dataAchievementCache[i].Group + "-" + dataAchievementCache[i].Level + "-" + dataAchievementCache[i].Value + "-" + dataAchievementCache[i].Notify + ",";
achievement += s;
}
//Debug.Log("----------LUU ACHIEVEMENT------------ " + achievement);
PlayerPrefs.SetString(Achievement_data_key, achievement);
if (FB.IsLoggedIn && sendServer)
{
//Nếu chưa có playerprefs thì sẽ submit lên luôn
//Nếu có rồi thì phải check nó cập nhật hoàn thành từ server về thì mới cho up lên
bool check = !PlayerPrefs.HasKey(DataMissionControlNew.key_update_achievement_data_from_server) ||
(PlayerPrefs.HasKey(DataMissionControlNew.key_update_achievement_data_from_server) && PlayerPrefs.GetInt(DataMissionControlNew.key_update_achievement_data_from_server) == 1);
if (check)
{
AudioControl.getMonoBehaviour().StartCoroutine(DHS.PostMeInfoUpdate(DFB.UserId, "" + VariableSystem.diamond, "" + achievement, "", (www) =>
{
Debug.Log("----------Update achievement to server success!------------- " + achievement);
}));
}
else
{
Debug.Log("----------KHONG CHO UP ACHIEVEMENT VA DIAMOND LEN SERVER------------- " + PlayerPrefs.GetInt(DataMissionControlNew.key_update_mission_data_from_server, 0));
}
}
}
}
catch (Exception e)
{
Debug.Log("------------ERROR ---------------" + e.Message);
if (DataMissionControlNew.test)
{
MobilePlugin.getInstance().ShowToast("ERROR " + e.Message);
}
}
}
public static void DeleteUserData()
{
PlayerPrefs.DeleteKey(FB_ID);
PlayerPrefs.DeleteKey(Mission_data_key);
PlayerPrefs.DeleteKey(Current_mission_data_key);
PlayerPrefs.DeleteKey(Achievement_data_key);
PlayerPrefs.DeleteKey("diamond");
PlayerPrefs.DeleteKey(DataMissionControlNew.key_update_mission_data_from_server);
VariableSystem.diamond = 8;
VariableSystem.heart = 5;
}
public static void RestoreUserData(int diamond, string achievement)
{
Debug.Log("Restore user data");
VariableSystem.diamond = diamond;
VariableSystem.heart = PlayerPrefs.GetInt("heart", 5);
string[] achie = achievement.Split(',');
if (achie.Length > 5)
{
for (int i = 0; i < dataAchievementCache.Length; i++)
{
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
string value = infoAchie[2];
string notify = infoAchie[3];
dataAchievementCache[i].Group = Convert.ToInt16(group);
dataAchievementCache[i].Level = Convert.ToInt16(level);
dataAchievementCache[i].Value = Convert.ToInt32(value);
dataAchievementCache[i].Notify = Convert.ToInt16(notify);
}
//Debug.Log("---Luu achievement----");
SaveAchievementCache();
GetAchievementCacheData();
}
Debug.Log("----------------ACHIEVEMENT da dc cap nhat tu -----------------");
PlayerPrefs.SetInt(DataMissionControlNew.key_update_achievement_data_from_server, 1);
}
The line 329 is this
string level = infoAchie[1];
The problem is coming from the last comma you are adding in the string you are adding to your PlayerPrefs in this part:
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
string achi = "";
for (int i = 1; i <= 22; i++)
{
achi += i + "-1-0-0,";
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi);
}
This code generates this string:
1-1-0-0,2-1-0-0,3-1-0-0,4-1-0-0,5-1-0-0,6-1-0-0,7-1-0-0,8-1-0-0,9-1-0-0,10-1-0-0,11-1-0-0,12-1-0-0,13-1-0-0,14-1-0-0,15-1-0-0,16-1-0-0,17-1-0-0,18-1-0-0,19-1-0-0,20-1-0-0,21-1-0-0,22-1-0-0,
Keep in memory that last comma at the end of the string.
You are later doing a split on the ',' character, and iterating over them.
string[] achie = achievement.Split(',');
for (int i = 0; i< dataAchievementCache.Length; i++)
{
//Debug.Log(achie[i]);
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
...
}
The problem is that by doing so, your achie string array contains an empty last element. So when you are later splitting on the "-" character, your infoAchie string array only contains one element: the empty string. The first line:
string group = infoAchie[0];
Still works, but is filled with the empty string. Then:
string level = infoAchie[1];
Can't work, as you are indeed out of the bounds of the infoAchie array.
The solution would be to add the comma to your string only if it is not the last element.
Also, I strongly advise you to use a StringBuilder over a simple string for optimization purposes. Your code could then look like, for instance:
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
StringBuilder achi = new StringBuilder();
for (int i = 1; i <= 22; i++)
{
achi.Append(i).Append("-1-0-0");
if(i != 22)
achi.Append(",");
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi.ToString());
}
Which generates this string:
1-1-0-0,2-1-0-0,3-1-0-0,4-1-0-0,5-1-0-0,6-1-0-0,7-1-0-0,8-1-0-0,9-1-0-0,10-1-0-0,11-1-0-0,12-1-0-0,13-1-0-0,14-1-0-0,15-1-0-0,16-1-0-0,17-1-0-0,18-1-0-0,19-1-0-0,20-1-0-0,21-1-0-0,22-1-0-0
here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.
package com.example.intracollegeapp;// package name
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import LibPack.UserInfoLib;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class LoginForm extends Activity {
Button login;
TextView username;
TextView password;
UserInfoLib ui;
long msgLength;
long bitLength;
char msg[];
long requiredBits;
long requiredBytes;
int toPad[];
private static final String NAMESPACE = "link to server package on which webservices are stored";
private static final String URL = "link to wsdl file stored on server";
private static final String SOAP_ACTION = "IntraCollegeWS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
login=(Button)findViewById(R.id.butLogin);
username=(TextView)findViewById(R.id.editText1);
password=(TextView)findViewById(R.id.editText2);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ui= new UserInfoLib();
ui.userId=username.getText().toString();
ui.password=getSHA1(password.getText().toString());
ui=(UserInfoLib)callService(objectToString(ui), "UserLogin", "userInfo");
//ui=(UserInfoLib)stringToObject(temp);
if(ui.firstName.equals("")){
Toast.makeText(v.getContext(), "Please Verify User Name Or Password", Toast.LENGTH_LONG).show();
finish();
}else{
Toast.makeText(v.getContext(), "Login Successfull", Toast.LENGTH_LONG).show();
System.out.println("NAME :"+ui.firstName);
Intent i = new Intent(v.getContext(), MainForm.class);
i.putExtra("uid", ui);
startActivity(i);
finish();
}
}
});
}
public long leftRotateBy(long l, int times) {
return ((l << times) & 0xFFFFFFFFl) | ((l & 0xFFFFFFFFl) >> (32 - times));
}
public int getByteAt(int at) {
if (at < msgLength) {
return (msg[at]);
} else {
at = at - (int) msgLength;
return toPad[at];
}
}
public void padBits(String pass) {
System.out.println("\n\n\n\n");
msg = pass.toCharArray();
msgLength = msg.length;
bitLength = msgLength * 8;
System.out.println("Msg Bit Length: " + bitLength);
System.out.println("MSg Byte Length: " + msgLength);
System.out.println("Required Minimum Bits: " + (bitLength + 65));
long remainder = (bitLength + 65) % 512;
System.out.println("Mod (Bits): " + remainder);
if (remainder == 0) {
requiredBits = 65;
System.out.println("No Padding Needed.");
} else {
requiredBits = (512 - remainder) + 65;
System.out.println(requiredBits + " Bits Padding Needed.");
}
requiredBytes = requiredBits / 8;
toPad = new int[(int) requiredBytes];
System.out.println("Required Bits: " + requiredBits);
System.out.println("Required Bytes: " + requiredBytes);
// manually append 1 to start of pad bits...
toPad[0] = 0x80;
for (int i = 1; i < requiredBytes - 8; i++) {
toPad[i] = 0;
}
long temp = bitLength;
for (int i = (int) (requiredBytes - 1); i >= (int) (requiredBytes - 8); i--) {
int t = (int) (temp & 0xff);
temp = temp >> 8;
toPad[i] = t;
}
System.out.println("TO PAD: ");
for (int i = 0; i < requiredBytes; i++) {
System.out.print(Integer.toHexString(toPad[i]) + " ");
}
System.out.println();
}
public String getSHA1(String pass) {
int kconst[] = new int[]{
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6};
long h0 = 0x67452301;
long h1 = 0xEFCDAB89;
long h2 = 0x98BADCFE;
long h3 = 0x10325476;
long h4 = 0xC3D2E1F0;
long a, b, c, d, e;
padBits(pass);
long totalLength = msgLength + requiredBytes;
System.out.println("TOTAL LENGTH: " + totalLength);
System.out.println("BLOCKS: " + (totalLength / 8));
long w[] = new long[80];
for (int i = 0; i < (int) totalLength; i += 64) {
for (int j = i, kk = 0; j < (i + 64); j += 4, kk++) {
w[kk] = 0xffffffffl & ((getByteAt(j) << 24) | (getByteAt(j + 1) << 16) | (getByteAt(j + 2) << 8) | (getByteAt(j + 3)));
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
for (int kk = 16; kk < 80; kk++) {
w[kk] = (w[kk - 3] ^ w[kk - 8] ^ w[kk - 14] ^ w[kk - 16]);
w[kk] = leftRotateBy(w[kk], 1);
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
long temp = 0;
for (int t = 0; t < 20; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | ((~b) & d)) + e + w[t] + kconst[0];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 20; t < 40; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[1];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 40; t < 60; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | (b & d) | (c & d)) + e + w[t] + kconst[2];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 60; t < 80; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[3];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
h0 = (h0 + a) & 0xFFFFFFFFl;
h1 = (h1 + b) & 0xFFFFFFFFl;
h2 = (h2 + c) & 0xFFFFFFFFl;
h3 = (h3 + d) & 0xFFFFFFFFl;
h4 = (h4 + e) & 0xFFFFFFFFl;
}
return Long.toHexString(h0) + Long.toHexString(h1) + Long.toHexString(h2) + Long.toHexString(h3) + Long.toHexString(h4);
}
Object callService(String INPUT_DATA, String METHOD_NAME, String PARAMETER_NAME){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
PropertyInfo pi = new PropertyInfo();
pi.setName(PARAMETER_NAME);
pi.setValue(INPUT_DATA);
pi.setType(String.class);
request.addProperty(pi);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject)envelope.bodyIn;
String resp = resultsRequestSOAP.getPrimitivePropertyAsString("return");
return stringToObject(resp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Object stringToObject(String inp){
byte b[] = Base64.decode(inp);
Object ret = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInput in = new ObjectInputStream(bis);
ret = (Object) in.readObject();
bis.close();
in.close();
} catch(Exception e) {
System.out.println("NOT DE-SERIALIZABLE: " + e);
}
return ret;
}
String objectToString(Object obj){
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(obj);
b = bos.toByteArray();
} catch(Exception e) {
System.out.println("NOT SERIALIZABLE: " + e);
}
return Base64.encode(b);
}
}
/* i have developed an android application which connects to server for login purpose. For connection i have used ksoap2 library. Intracollege webservice is stored on server. The application works fine when connected to server using wifi. if it is not connected to wifi it displays message "application is crashed" and then application stops working.
I only want to display a simple message "Application is not connected to server" if it is not connected to server using wifi.*/
Try this........
public boolean isNet()
{
boolean status=false;
String line;
try
{
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
while(( line = reader.readLine()) != null)
{
}
status=true;
}
catch (IOException ex)
{
System.out.println("ex in isNet : "+ex.toString());
if(ex.toString().equals("java.net.UnknownHostException: www.google.com"))
status=false;
}
catch(Exception e)
{
}
return status;
}
if(status==true)
{
//Do your operation
}
else
show("No Internet Connection.");
When status is true do your login process.Otherwise show message "Application is not connected to server".
To check for the internet connection try this out
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Check this code, this will help you :
Initialize in the class where you want to check network availability.
OtherUtils otherUtils = new OtherUtils();
if (!otherUtils.isNetworkAvailable(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "No Network Available", Toast.LENGTH_LONG).show();
return;
}
Add below class:
public class OtherUtils{
Context context;
public boolean isNetworkAvailable(Context context) {
this.context = context;
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
// boitealerte(this.getString(R.string.alertNoNetwork),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
This will surely help you.
public class master extends Activity {
ProgressDialog progressDialog;
EditText tahmini_kelime;
EditText girilen_sayi ;
EditText toplam_harf_sayisi ;
Button tamamdir;
TextView jTextArea1;
Vector vector_all,vect_end,vect,recent_search;
BufferedReader read;
String recent_tahmin_kelime;
boolean bayrak,bayrak2 ;
int column_number ;
InputStreamReader inputreader ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.master);
column_number=0;
bayrak=true;
toplam_harf_sayisi=(EditText)findViewById(R.id.toplam_harf);
tahmini_kelime=(EditText)findViewById(R.id.tahmini_kelime);
girilen_sayi=(EditText)findViewById(R.id.sayi_gir);
tamamdir=(Button)findViewById(R.id.tamamdirrrr);
jTextArea1=(TextView)findViewById(R.id.jte);
bayrak2=true;
recent_search = new Vector();
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
tamamdir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if( bayrak2 )
{
if(Integer.parseInt(toplam_harf_sayisi.getText().toString())>8 || Integer.parseInt(toplam_harf_sayisi.getText().toString())<=1)
{
toplam_harf_sayisi.setText("");
Dialog dl=new Dialog(master.this);
dl.setTitle("hatalı giriş");
dl.setCanceledOnTouchOutside(true);
dl.show();
return;
}
int findwordlength = Integer.parseInt(toplam_harf_sayisi.getText().toString());
int k = 0;
String result = "";
jTextArea1.setText("");
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
String resultword = "";
try {
vect = new Vector();
while (read.ready()) {
result = read.readLine();
if (result.length() == findwordlength) {
vect.addElement(result);
resultword = resultword + result + "\n";
k = k + 1;
}
jTextArea1.setText("");
}
jTextArea1.append(resultword + "\n");
RandomKelime(vector_all,0 );
} catch (IOException ex) {
}
toplam_harf_sayisi.setEnabled(false);
girilen_sayi.setEnabled(true);
bayrak2=false;
}
else
{
progressDialog = ProgressDialog.show(master.this, "Bir Düşüneyim :D", "lütfen bekleyiniz...");
Thread thread = new Thread(new Runnable() {
public void run() {
mainGuessWord(column_number);
handler.sendEmptyMessage(0);
}
});
thread.start();
girilen_sayi.setText("");
}
}
});
}
private void mainGuessWord(int look) {
int result_int = 0;
String randomword = "";
int randomword2 = 0;
randomword = tahmini_kelime.getText().toString();
result_int = Integer.parseInt(girilen_sayi.getText().toString());
if (result_int == 0) {
mevcut_degil(vect, randomword);
} else {
elemeAgaci(vect, randomword, result_int);
}
}
public void elemeAgaci(Vector vect, String elem, int length) {
String word = elem.toString();
Vector cmp_vect;
cmp_vect = new Vector();
vect_end = new Vector();
int count = 0;
int countword = 0; // toplam word sayısı
int each_word_total = 0; // her kelimede bulunan harf sayısı
jTextArea1.setText("");
String compare = "";
for (int i = 0; i < vect.size(); i++) {
each_word_total = 0;
compare = "";
for (int j = 0; j < word.length(); j++) {
if(!compare.contains(""+word.charAt(j)))
{
for (int k = 0; k < vect.get(i).toString().length(); k++) {
if (vect.get(i).toString().charAt(k) == word.charAt(j)) {
each_word_total++;
}
}
compare=""+compare+word.charAt(j);
}
}
System.out.println("" + vect.get(i) + " => " + each_word_total);
if (length == each_word_total) {
cmp_vect.add(vect.get(i));
jTextArea1.append(vect.get(i) + "\n");
countword++;
}
}
vect.clear();
for (int l = 0; l < cmp_vect.size(); l++) {
vect.add(cmp_vect.get(l));
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
} else {
column_number = column_number + 1;
if(vect.size()<10){
RandomKelime_Table(vect);
}else{
RandomKelime(vector_all, column_number);
}
}
}
public void mevcut_degil(Vector vect, String m) {
char control[];
control = m.toCharArray();
boolean flag = false;
int countword = 0;
Vector detect;
detect = new Vector();
jTextArea1.setText("");
for (int k = 0; k < vect.size(); k++) {
flag = false;
for (int s = 0; s < control.length; s++) {
if (vect.get(k).toString().contains("" + control[s])) {
flag = true;
}
}
if (!flag) {
detect.addElement(vect.get(k));
countword = countword + 1;
}
}
vect.clear();
for (int s = 0; s < detect.size(); s++) {
vect.addElement(detect.get(s));
}
for (int a = 0; a < countword; a++) {
jTextArea1.append(vect.get(a).toString() + "\n");
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
}
else {
column_number = column_number + 1;
RandomKelime(vect, column_number);
}
}
public void RandomKelime(Vector vector, int k)
{
String sesli[]={"a","e","ı","i","o","ö","u","ü"};
Random a = new Random();
if (k == 0) {
String passedword = "";
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
while (passedword.length() < 8) {
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
tahmini_kelime.setText(passedword);
recent_tahmin_kelime=passedword;
// jTable1.setValueAt(vector_all.get((int) (Math.random() * vector_all.size())), k, 0);
} else {
recent_search.addElement(recent_tahmin_kelime );
int say = 0;
String design = "";
String guess_words = "";
String as="";
int f=0;
int count=0;
int calculate_all=0;
for (int u = 0; u < recent_search.size(); u++) {
design = recent_search.get(u).toString();
bayrak = false;
as="";
count=0;
for(int s=0;s<sesli.length;s++)
{
if(design.contains(""+sesli[s]) && count==0){
as+=""+sesli[s];
count++;
}
}
guess_words = vector_all.get((int) a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
while (say < design.length()) {
calculate_all=0;
while (guess_words.contains("" + as) && !design.equals(guess_words)) {
say = 0;
calculate_all++;
guess_words = vector_all.get( a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
f=f+1;
System.out.println("Tahmın: " + guess_words + " => " + design);
if(calculate_all>vect.size())
{
break;
}
}
say++;
System.out.println("coutn: " + say);
}
}
if (true) {
tahmini_kelime.setText(guess_words);
}
}
}
public void RandomKelime_Table(Vector vector ) {
String passedword = "";
Random a = new Random();
try {
passedword = vect.get(a.nextInt(vect.size())).toString();
} catch (Exception e) {
Dialog dl=new Dialog(master.this);
dl.setTitle("Hatalı Giriş.Yeniden Başlayın.");
dl.setCanceledOnTouchOutside(true);
dl.show();
yeniden_basla();
}
tahmini_kelime.setText(passedword );
}
public void yeniden_basla()
{
bayrak2=true;
girilen_sayi.setEnabled(false);
toplam_harf_sayisi.setEnabled(true);
toplam_harf_sayisi.setText("");
vect.clear();
vector_all.clear();
vect_end.clear();
recent_search.clear();
jTextArea1.setText("");
recent_tahmin_kelime="";
column_number=0;
bayrak=true;
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
this all of my code.
You don't show where you create your handler (onCreate ? onStart ? somewhere else ?). Is it started from the main thread ? If so, you need to be provide a more complete stack trace so we can understand.
If you're starting it from another thread then that's the issue because it's attempting to change progressDialog and that must be done from the main thread.
PS: if you used an AsyncTask you wouldn't have to scratch your head around this as it's designed to do exactly what you want and be thread safe.
Post comment : use an AsyncThread : add the progress bar in onPreExecute(), change run() to doInBackground() and move the dismiss() to onPostExecute(