Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am developing an application program which holds students names in a list and their group number.
Each student can transfer to another group so there is another field which carries their wishes.
I want the program to carry matching group number with students wishes and getting the best result with 0 conflict and updating an SQLite database.
Someone has told me to use the stable marriage algorithm: it would be perfect for this type of problem.
The problem is that I don't know much about this last one and how it would be looks like in android so if you can offer me a simple explanation and an example which has SQLite, Java code it would be perfect.
A very good explanation:
http://www.cs.berkeley.edu/~kamil/cs70/lec/lec05.html
Animation:
You can check out this animation which explains the problem nicely
http://goanimate.com/videos/0g8OutVDdMJo
This is the implementation of Gale Shapely which is a famous solution to stable marriage problem.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args)
{
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = {"1", "2", "3"};
/** list of women **/
String[] w = {"1", "2", "3"};
/** men preference **/
String[][] mp = null ;
/** women preference **/
String[][] wp= null ;
// Input.txt is like
// 3 <--defines the size of array
// male preference array
// 1 3 2
// 1 2 3
// 2 3 1
//female preference array
//1 3 2
//2 1 3
//2 1 3
try{
FileInputStream fstream = new FileInputStream("input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line=0;
int k=0;
int n=0;
int i=0;
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
GaleShapley gs = new GaleShapley(m, w, mp, wp);
}
}
I was able to execute the code below after making some changes.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
public GaleShapley() {}
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("src\\input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
The result is:
Gale Shapley Marriage Algorithm
Couples are :
1 1
2 2
3 3
Related
I need to fill a vector with integers, but I have some troubles, I need to fill it with random numbers, but not two numbers in a row. (ex. not like this: 1,4,4,3,5,9)
I made this code but it does not work well :
# first time loja=1;
but until the game : loja++;
int[] con;
Random Method :
private int nasiqim (int max){
Random nasiqimi = new Random();
int i = 0;
i=nasiqimi.nextInt(max);
return i;
}
Working Code :
int i;
con = new int [loja];
for (i=0; i<loja; i++)
{
con[i] = nasiqim(8);
if(i>0){
while(con[i]==con[i-1])
{
con[i] =nasiqim(8);
}
}
i++;
}
The results are like this:
1
1,4
1,4,1
1,4,1,4
1,4,1,4,1
5,3,5,3,5,3
5,3,5,3,5,3,5
And this is not what I need, I need the numbers to really random, not like this,
Will be great if list will be like this something : 1,5,6,7,3,0,2,4,1,0,2,3...
Thank you!!
private int[] con = null;
private final Random nasiqimi = new Random();
/**
* Test run random.
*/
#Test
public void testRunRandom() {
int loja = 10;
con = new int[loja];
for (int i = 0; i < loja; i++) {
int nextRandom = 0;
while (true) {
nextRandom = nasiqim(8);
if (i == 0 || con[i - 1] != nextRandom) {
con[i] = nextRandom;
break;
}
}
}
}
/**
* Gets the random.
*
* #param max the max
* #return the random
*/
private int nasiqim(int max) {
return nasiqimi.nextInt(max);
}
I've created a sample class
import java.util.*;
public class Foo {
static Random r = new Random();
static int[] con;
static int loja = 8;
private static int randomInt(int max) {
return r.nextInt(max);
}
public static void main(String args[]) {
int i;
con = new int[loja];
for (i = 0; i < loja; i++) {
con[i] = randomInt(8);
if (i > 0) {
while (con[i] == con[i - 1]) {
con[i] = randomInt(8);
}
}
}
System.out.println( Arrays.toString(con));
}
}
All variables are static, notice I get rid of the i++; increment at the end of the for loop.
I want to make an application to find differences between two strings. How do I solve this?
st = "this is a cat.this is my cat."
st1 = "this is cat. this my cat."
The output should be "a is" as the missing words.
Here is my code
#SuppressLint("DefaultLocale")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String st="this is a cat. this is my cat.";
TextView tv1=(TextView) findViewById(R.id.textView2);
String st1="This is cat. this my cat.";
String blank="";
if(st.toLowerCase().contains(st1.toLowerCase()))
{
st=st.toLowerCase().replace(st1.toLowerCase(), blank);
tv1.setText(st);
}
}
You need a sort of DIFF function.
Check these answers:
Extract the difference between two strings in Java
How to perform string Diffs in Java?
You could use StringUtils.differences, it's the source:
6020 public static String difference(String str1, String str2) {
6021 if (str1 == null) {
6022 return str2;
6023 }
6024 if (str2 == null) {
6025 return str1;
6026 }
6027 int at = indexOfDifference(str1, str2);
6028 if (at == INDEX_NOT_FOUND) {
6029 return EMPTY;
6030 }
6031 return str2.substring(at);
6032 }
6033
6034 /**
6035 * <p>Compares two Strings, and returns the index at which the
6036 * Strings begin to differ.</p>
6037 *
6038 * <p>For example,
6039 * <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
6040 *
6041 * <pre>
6042 * StringUtils.indexOfDifference(null, null) = -1
6043 * StringUtils.indexOfDifference("", "") = -1
6044 * StringUtils.indexOfDifference("", "abc") = 0
6045 * StringUtils.indexOfDifference("abc", "") = 0
6046 * StringUtils.indexOfDifference("abc", "abc") = -1
6047 * StringUtils.indexOfDifference("ab", "abxyz") = 2
6048 * StringUtils.indexOfDifference("abcde", "abxyz") = 2
6049 * StringUtils.indexOfDifference("abcde", "xyz") = 0
6050 * </pre>
6051 *
6052 * #param str1 the first String, may be null
6053 * #param str2 the second String, may be null
6054 * #return the index where str2 and str1 begin to differ; -1 if they are equal
6055 * #since 2.0
6056 */
6057 public static int indexOfDifference(String str1, String str2) {
6058 if (str1 == str2) {
6059 return INDEX_NOT_FOUND;
6060 }
6061 if (str1 == null || str2 == null) {
6062 return 0;
6063 }
6064 int i;
6065 for (i = 0; i < str1.length() && i < str2.length(); ++i) {
6066 if (str1.charAt(i) != str2.charAt(i)) {
6067 break;
6068 }
6069 }
6070 if (i < str2.length() || i < str1.length()) {
6071 return i;
6072 }
6073 return INDEX_NOT_FOUND;
6074 }
6075
6076 /**
6077 * <p>Compares all Strings in an array and returns the index at which the
6078 * Strings begin to differ.</p>
6079 *
6080 * <p>For example,
6081 * <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7</code></p>
6082 *
6083 * <pre>
6084 * StringUtils.indexOfDifference(null) = -1
6085 * StringUtils.indexOfDifference(new String[] {}) = -1
6086 * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
6087 * StringUtils.indexOfDifference(new String[] {null, null}) = -1
6088 * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
6089 * StringUtils.indexOfDifference(new String[] {"", null}) = 0
6090 * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
6091 * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
6092 * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
6093 * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
6094 * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
6095 * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
6096 * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
6097 * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
6098 * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
6099 * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
6100 * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
6101 * </pre>
6102 *
6103 * #param strs array of strings, entries may be null
6104 * #return the index where the strings begin to differ; -1 if they are all equal
6105 * #since 2.4
6106 */
6107 public static int indexOfDifference(String[] strs) {
6108 if (strs == null || strs.length <= 1) {
6109 return INDEX_NOT_FOUND;
6110 }
6111 boolean anyStringNull = false;
6112 boolean allStringsNull = true;
6113 int arrayLen = strs.length;
6114 int shortestStrLen = Integer.MAX_VALUE;
6115 int longestStrLen = 0;
6116
6117 // find the min and max string lengths; this avoids checking to make
6118 // sure we are not exceeding the length of the string each time through
6119 // the bottom loop.
6120 for (int i = 0; i < arrayLen; i++) {
6121 if (strs[i] == null) {
6122 anyStringNull = true;
6123 shortestStrLen = 0;
6124 } else {
6125 allStringsNull = false;
6126 shortestStrLen = Math.min(strs[i].length(), shortestStrLen);
6127 longestStrLen = Math.max(strs[i].length(), longestStrLen);
6128 }
6129 }
6130
6131 // handle lists containing all nulls or all empty strings
6132 if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) {
6133 return INDEX_NOT_FOUND;
6134 }
6135
6136 // handle lists containing some nulls or some empty strings
6137 if (shortestStrLen == 0) {
6138 return 0;
6139 }
6140
6141 // find the position with the first difference across all strings
6142 int firstDiff = -1;
6143 for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
6144 char comparisonChar = strs[0].charAt(stringPos);
6145 for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
6146 if (strs[arrayPos].charAt(stringPos) != comparisonChar) {
6147 firstDiff = stringPos;
6148 break;
6149 }
6150 }
6151 if (firstDiff != -1) {
6152 break;
6153 }
6154 }
6155
6156 if (firstDiff == -1 && shortestStrLen != longestStrLen) {
6157 // we compared all of the characters up to the length of the
6158 // shortest string and didn't find a match, but the string lengths
6159 // vary, so return the length of the shortest string.
6160 return shortestStrLen;
6161 }
6162 return firstDiff;
6163 }
then
difference("this is a cat.this is my cat.", "this is cat. this my cat.");
You could just implement this methods, or the entire library if you need more methods from this library.
Documentation here.
The easy way is to split the both strings on the bases of spaces.
e.g
String[] separated_st = st.split(" ");
String[] separated_st1 = st1.split(" ");
now you have two arrays. loop through them and find what is missing and what is not.
Alternatively you can use StringTokenizer class.
Hope this will help.
Try this one.
import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Classwithoutnewkeyword {
public static void main(String args[]) {
try {
String s1 = "this is a cat.this is my cat.";
String s2 = "this is cat. this my cat."
String arr1[] = s1.split(" ");
String arr2[] = s2.split(" ");
java.util.List<String> list1 = new ArrayList<String>(
Arrays.asList(arr1));
java.util.List<String> list2 = new ArrayList<String>(
Arrays.asList(arr2));
ArrayList<String> tmp1 = new ArrayList<String>();
ArrayList<String> tmp2 = new ArrayList<String>();
for (int i = 0; i < arr1.length; i++) {
int k = 0;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equalsIgnoreCase(arr2[j])) {
tmp1.add(arr1[i]);
} else {
tmp2.add(arr1[i]);
}
}
}
for (String strs : tmp1) {
list1.remove(strs);
}
System.out.print(list1.toString());
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Сorrect solution is given below:
import java.util.ArrayList;
public class Classwithoutnewkeyword {
public static void main(String args[]) {
try {
String s1 = "this is a cat. this is my cat.";
String s2 = "this is cat. my cat.";
String arr1[] = s1.split(" ");
String arr2[] = s2.split(" ");
ArrayList<String> tmp1 = new ArrayList<String>();
ArrayList<String> tmp2 = new ArrayList<String>();
for (int i = 0,j=0; i < arr1.length; i++) {
if (arr1[i].equalsIgnoreCase(arr2[j])) {
tmp1.add(arr1[i]);
j++;
} else {
tmp2.add(arr1[i]);
}
}
System.err.println(tmp2);
} catch(Exception e)
{
e.printStackTrace();
}
}
}
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(
In my web service I'm making a query to a database, and I would like to return 2 columns of the database and put these columns in a 2d array.
Also I would like to convert the array to JSON and send it to the client. The client using gson parses the message from the server in a 2d array. Is it possible?
I have tried a lot but no luck till now. Thank you in advance.
The last version i've tried is this:
private static String[][] db_load_mes (String u){
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
JSONObject messages = new JSONObject();
Connection c = null;
try{
// Load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:dsn1","mymsg","mymsg");
Statement s = c.createStatement();
// SQL code:
ResultSet r;
r = s.executeQuery("select * from accounts ");
int i = 0, j = 0;
int k = 0;
String x,y;
while(r.next()) {
x = r.getString("username");
array1.add(x);
y = r.getString("password");
array2.add(y);
k = k + 1;
}
int count = array1.size();
String[][] row = new String[count][2];
Iterator<String> iter = array1.iterator();
while (iter.hasNext()) {
row[i][0]=iter.next();
i++;
}
Iterator<String> iter2 = array2.iterator();
while (iter2.hasNext()) {
row[j][1]=iter2.next();
j++;
}
for(int z=0;z<count;z++)
System.out.println(row[z][0] + "\t" + row[z][1] + "\n");
if (k == 0)
System.err.println("no accounts!");
c.close();
s.close();
}
catch(SQLException se)
{
System.err.println(se);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ...;
}
With the above code I can create the 2d array but how can I send this array to the client.
Here is how I made it using Gson from google...
Download gson from here
include it in your project.
package javaapplication1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JavaApplication1 {
public static void main(String[] args) {
int rows = 3;
String records[][] = new String[][]{{"bob", "123-pass"},
{"erika", "abc123"},
{"richard", "123123123"}
};
Gson gson = new Gson();
String recordsSerialized = gson.toJson(records);
System.out.println(recordsSerialized);
/* prints this
[["bob","123-pass"],["erika","abc123"],["richard","123123123"]]
*/
// if you want a better output import com.google.gson.GsonBuilder;
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String recordsSerializedPretty = gsonPretty.toJson(records);
System.out.println(recordsSerializedPretty);
/* PRINTS IN different lines.. I can't paste it here */
// for retrieval
String retrievedArray[][] = gsonPretty.fromJson(recordsSerializedPretty, String[][].class);
for (int i = 0; i < retrievedArray.length; i++) {
for (int j = 0; j < retrievedArray[0].length; j++) {
System.out.print(retrievedArray[i][j]+" ");
}
System.out.println("");
}
// PRINTS THIS
/*
bob 123-pass
erika abc123
richard 123123123
*/
}
}
i'm using feed.jar of libs-for-android, and i need to parse json data.
I've founded JsonContentHandler.java class similar to XmlContentHandler.java used in demos.
Can you give me an example on how to use JsonContentHandler?
thank you.
ps: https://code.google.com/p/libs-for-android/
Example input:
{"results": [{"id": "1f3d", "title": "Result title", "content": "Some content"}, ...]}
Example code:
public class MyContentHandler extends JsonContentHandler {
private final MatrixCursor mOutput;
public MyContentHandler(MatrixCursor cursor) {
mOutput = cursor;
}
#Override
protected Object getContent(String source) throws JSONException {
JSONObject data = new JSONObject(source);
int columnCount = output.getColumnCount();
JSONArray results = data.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String id = result.getString("id");
String title = result.getString("title");
String content = result.getString("content");
// Generate a positive integer ID for compatibility with CursorAdapter
Long baseId = Long.valueOf(Math.abs(id.hashCode()));
RowBuilder builder = output.newRow();
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
String columnName = output.getColumnName(columnIndex);
if (columnName.equals(MyContract.Items._ID)) {
builder.add(baseId);
} else if (columnName.equals(MyContract.Items.ID)) {
builder.add(id);
} else if (columnName.equals(MyContract.Items.TITLE)) {
builder.add(title);
} else if (columnName.equals(MyContract.Items.CONTENT)) {
builder.add(content);
} else {
throw new RuntimeException("Unknown column: " + columnName);
}
}
}
// Tell FeedLoader how many rows were added
return FeedLoader.documentInfo(results.length());
}
}