android autocomplete doesn't work at first time - android

I'm trying to get the data from remote address, put them in to a list and then do autocomplete, but i encountered a wired problem, when i first type a character in to editText, i monitored that there's correct data in the list, but the autocomplete does not work, if i delete this and type the same character again, it'll work fine, here's my code
private OnKeyListener mKeyListener = new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// do something when the button is clicked
if (event.getAction() == KeyEvent.ACTION_UP) {
//do something here
companyList.clear();
EditText getInput = (EditText) findViewById(R.id.editText1);
char pressedKey = (char) event.getUnicodeChar();
String inputStr = Character.toString(pressedKey);
inputStr = getInput.getText().toString();
Logger.getLogger("test1").info(inputStr);
if(keyCode == 67){
return false;
}
String urlStr = "http://autoc.finance.yahoo.com/autoc?query=" + inputStr +
"&callback=YAHOO.Finance.SymbolSuggest.ssCallback";
Logger.getLogger("url success").info(urlStr);
AsyncHttpClient client = new AsyncHttpClient();
Logger.getLogger("client success").info(urlStr);
client.get(urlStr, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Logger.getLogger("testsuccess").info(response);
String jString = (String) response.subSequence(39, response.length()-1);
try {
JSONObject jsonObj = new JSONObject(jString);
JSONArray jsonArr = jsonObj.getJSONObject("ResultSet").getJSONArray("Result");
int i=0;
for(i = 0; i < jsonArr.length(); i++){
JSONObject tmpObj = jsonArr.getJSONObject(i);
String line = tmpObj.getString("symbol") + ", " + tmpObj.getString("name") + " (" + tmpObj.getString("exch") + ")";
companyList.add(line);
}
JSONObject firstObj = jsonArr.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(String word : companyList){
Logger.getLogger("companyList").info(word);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, companyList);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.editText1);
Logger.getLogger("text2").info(textView.getText().toString());
textView.setAdapter(adapter);
Logger.getLogger("text3").info(textView.getText().toString());
textView.setThreshold(1);
Logger.getLogger("text4").info(textView.getText().toString());
});
}
});
return false;
}
return false;
}
};
when first type the character, logger text2 text3 text4 both appeared in logcat, but autocomplete doesn't work, does anyone know why? Thanks!

May be you need to use the same adapter and call
notifyDataSetChanged
If you don't find the answer, I suggest you switch to implementation described here

Related

Swipeable-Cards Adapter get Item Info

I m using this framework, I already trying many times for making this problem, but I cant do it. I already asking on stackoverflow but no one cant help me. Actually I m tried.
I m using this framework : https://github.com/kikoso/Swipeable-Cards
And I m using SimpleCardStackAdapter like this :
for (int i = 0; i < user.length(); i++) {
final JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
// adapter.add(new CardModel(name, email, image1));
//Set JSON Data in TextView
Log.i("image1image1image1image1", image1);
// CardModel cardModel = new CardModel(" cardModel", " CardModel", r.getDrawable(R.drawable.picture1));
card = new CardModel(name, email, image1);
card.setOnClickListener(new CardModel.OnClickListener() {
#Override
public void OnClickListener() {
Log.i("Swipeable Cards", "I am pressing the card");
// Intent no = new Intent(HomeListview.this, YayDetailActivity.class);
/// startActivity(no);
}
});
card.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
#Override
public void onLike(CardModel card) {
Log.i("Swipeable Cards", "I dislike the card");
}
#Override
public void onDislike(CardModel card) {
Log.i("Swipeable Cards", "I like the card");
// new sendNewYay().execute(sharedToken, card.getTitle());
Toast.makeText(getApplicationContext(), card.getDescription(), Toast.LENGTH_SHORT).show();
}
});
// I m added adapter
adapter.add(card);
mCardContainer.setAdapter(adapter);
}
At the onDislike method, I need to get item name.
in this line : new sendNewYay().execute(sharedToken, name);
I send the item name, But it dont work.
1.How can I get the item name, in this method?
2.I have two button, one of them for onLike method, another one for onDislike Method. Ho can I triggered this two method with my button?
Thank you.
Decleare two variable global as string
String itemname;
try {
JSONArray c = new JSONArray(user.toString());
for (int i = 0 ; i < c.length();i++) {
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
System.out.println("Position : " + "" + i + ""+ c.getString(i));
itemname = name.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Final itemname is " + itemname);

Activity with two JSONClasses

I have an activity that suppose to use JSON twice. In the first time it works perfectly, but on the second time it seems that the JSON class goes directly to the onPostExecute function without activating the doInBackground function. This is the activity that calls the JSON:
public class Registration extends ActionBarActivity {
public void regis(View view) {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass1 = (EditText) findViewById(R.id.PassTxt);
EditText pass2 = (EditText) findViewById(R.id.RePassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
CheckBox agree = (CheckBox) findViewById(R.id.checkAgree);
TextView err = (TextView) findViewById(R.id.err);
String uName = userName.getText().toString(), pss1 = pass1.getText().toString(),
pss2 = pass2.getText().toString(), disName = displayName.getText().toString(),
eMail = mail.getText().toString();
if ((uName.length() > 0) && (pss1.length() > 0) && (pss2.length() > 0) && (disName.length() > 0)
&& (eMail.length() > 0)) {
if (pss1.equals(pss2)) {
if (agree.isChecked()) {
err.setVisibility(TextView.INVISIBLE);
String str = "?uname=" + uName;
new JSONClass(this, 2, str, this).execute();
} else {
err.setText("You must approve the use terms");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("The two passwords must match!");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("You must insert values in every cell");
err.setVisibility(TextView.VISIBLE);
}
}
public void checkExist(JSONArray ans) {
try {
int cnt = Integer.parseInt(ans.getJSONObject(0).getString("cnt"));
if (cnt == 1) {
TextView err = (TextView) findViewById(R.id.err);
err.setText("User name already exists!");
err.setVisibility(TextView.VISIBLE);
} else {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass = (EditText) findViewById(R.id.PassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
String uName = userName.getText().toString(), pss = pass.getText().toString(),
disName = displayName.getText().toString(), eMail = mail.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
String str = "?uname=" + uName + "&password=" + pss + "&email=" + eMail + "&disnam=" +
disName + "&dt=" + currentDateandTime;
Log.e("log_tag", "Just for me: " + str);
new JSONClass(this, 3, str, this).execute();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void openLogin() {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}
}
I removed unnecessary functions. This is my JSON class:
public class JSONClass extends AsyncTask<String,Void,JSONArray>{
private String link;
private int flag;
private Login log = null;
private Registration reg = null;
private Context context;
public JSONClass(Context context, int queryNo, String params, Registration regg) {
this.context = context;
link = "http://pickupfriend.fulba.com/android_project/query" + queryNo + ".php" + params;
reg = regg;
flag = queryNo;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected JSONArray doInBackground(String... arg0) {
JSONArray arr = new JSONArray();
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(link);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
arr = new JSONArray(result);
}catch(Exception e){
}
return arr;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void onPostExecute(JSONArray result) {
switch (flag) {
case 1:
log.getResults(result);
break;
case 2:
reg.checkExist(result);
break;
case 3:
reg.openLogin();
break;
default:
break;
}
}
}
At first I activate the regis function that works perfectly with the json class. Afterwards it suppose to activate checkExist if the cnt parameter is 0, which is 0. Then it is suppose to activate the json class again but it seems that it goes directly to openLogin function without going to the php file and activating it. Am I doing something wrong?

Connecting to a web browser in Android using Eclipse

I am creating an Android application using Eclipse in which the user enters their lottery numbers. The app then retrieves the lottery numbers from the latest live draw using Jsoup to parse the html lottery numbers from the National Lottery Website. The user then pushes a check button after which a new activity opens displaying the match between the users numbers and the lottery draw numbers to check if the user has won the lottery. At this point I would like to have a button that allows the user to open the lottery webpage to enable them to check their prize, if they have matched their numbers. However I am having difficulty opening the browser. After the user has entered their numbers and hits check button, the program crashes, so they are not even reaching the point of comparing their numbers with the lottery numbers. I am getting the error that I am unable to start the activity DisplayNumbersActivity as there is a null pointer exception. Can anyone please help me to identify what the problem is with my code or how I could resolve it? Thanks in advance! I have included the main activity and DisplayNumbers activity code below.
public class DisplayNumbersActivity extends Activity {
private EditText urlText;
private Button checkWeb;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_numbers);
// Show the Up button in the action bar.
setupActionBar();
//get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//create the text view
TextView textView = new TextView(this);
textView.setTextSize(20);
textView.setTextColor(Color.RED);
textView.setText(message);
//set the text view as the activity layout
setContentView(textView);
urlText = (EditText) findViewById(R.id.url_field);
checkWeb = (Button) findViewById(R.id.checkWeb);
//set up event handlers
checkWeb.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openBrowser();
}//onClick
});//setOnClickListener
urlText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
openBrowser();
return true;
}
return false;
}//onKey
});//setOnKeyListener
}//onCreate
//open a browser on the URL specified in the text box
private void openBrowser() {
Uri uri = Uri.parse(urlText.getText().toString());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}//openBrowser
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}//setUpActionBar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}//onOptionsItemSelected
}//class
public class MainActivity extends Activity {
private final static String NATIONAL_LOTTERY_DRAW_URL = "http://www.national-lottery.co.uk/player/p/drawHistory.do";
public final static String EXTRA_MESSAGE = ".com.example.lottochecker.MESSAGE";
boolean bonus = false;
boolean jackpot = false;
int lottCount = 0;
Button check;
Integer [] numbers;
int bonusBall;
String userInput = "";
final int MAX = 49;
boolean validType = false;
int userGuess;
private LotteryDraw lotteryDraw;
#Override
//when the activity is created, call the layout class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}//onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}//onCreateOptionsMenu
//called when the user clicks the send button
public void checkNumbers(View view) {
//set up an array of text boxes for the user to put in their numbers
EditText[] text_fields = new EditText[6];
//set up an array of string variables for holding user input
String[] str_nums = new String[6];
//set up an array to hold integer values having been converted from the user input as a String
int[] int_nums = new int[6];
//populate the array of text boxes with user input
text_fields[0] = (EditText) findViewById(R.id.enter_numbers);
text_fields[1] = (EditText) findViewById(R.id.enter_numbers2);
text_fields[2] = (EditText) findViewById(R.id.enter_numbers3);
text_fields[3] = (EditText) findViewById(R.id.enter_numbers4);
text_fields[4] = (EditText) findViewById(R.id.enter_numbers5);
text_fields[5] = (EditText) findViewById(R.id.enter_numbers6);
for(int i=0; i<6; i++)
{
str_nums[i] = text_fields[i].getText().toString();
// if the text box is empty, print error and stop processing.
// if not empty convert string to int and store in array
if(str_nums[i].equals(""))
{
Toast.makeText(MainActivity.this, "Please enter valid number in text box "+(i+1), Toast.LENGTH_LONG).show();
return;
}
else
{
int_nums[i] = Integer.parseInt(str_nums[i]);
}
}
// check validity of numbers entered
for(int i=0; i<6; i++)
{
// check numbers are in range
if (int_nums[i] < 1 || int_nums[i] > MAX)
{
Toast.makeText(MainActivity.this, "Number " + int_nums[i] + " in text box " + (i+1) + " is out of range. Please enter a number between 1 and 49", Toast.LENGTH_LONG).show();
return;
}
// check for duplicates
for(int j=0; j<6; j++)
{
if(i != j)
{
if (int_nums[i] == int_nums[j])
{
Toast.makeText(MainActivity.this, "The number " + int_nums[i] + " is dublicated in text boxes " + (i+1) + " and " + (j+1) + ". Duplicates can not be accepted", Toast.LENGTH_LONG).show();
return;
}
}
}
}
// numbers entered are valid
int matches = 0;
boolean bonus_match = false;
final int[] LOTTONUMBERS = lotteryDraw.getNumbers();
// check the 6 lotto numbers
for(int lotto_num = 0; lotto_num < 6; lotto_num++)
{
for(int user_num = 0; user_num < 6; user_num++)
{
if(LOTTONUMBERS[lotto_num] == int_nums[user_num])
{
matches++;
break;
}
}
}
// check the bonus ball
for(int user_num = 0; user_num < 6; user_num++)
{
if(lotteryDraw.getBonusBall() == int_nums[user_num])
{
bonus_match = true;
break;
}
}
//inform the user of the results
String output = "The lotto numbers are:\n";
for(int i=0; i<6; i++)
{
output = output + LOTTONUMBERS[i] + " ";
}
output = output + " bonus: " + lotteryDraw.getBonusBall();
output = output + "\n\nYour numbers are:\n";
for(int i=0; i<6; i++)
{
output = output + str_nums[i] + " ";
}
output = output + "\n\nYou have matched "+ matches + " numbers ";
if(bonus_match)
{
output = output + "and the bonus";
}
if(matches == 6)
{
output = output + "\n\nCONGRATULATIONS - YOU HAVE WON THE JACKPOT";
}
else if (matches >= 3)
{
output = output + "\n\nCONGRATULATIONS - you have won a prize";
}
else
{
output = output + "\n\nBad Luck - not enough matches to win";
}
//display the lottery results to the new activity
Intent intent = new Intent(this, DisplayNumbersActivity.class);
intent.putExtra(EXTRA_MESSAGE, output);
startActivity(intent);
}//method
public void getLotteryDrawFromWebsite(View view) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(NATIONAL_LOTTERY_DRAW_URL);
} else {
//TODO: add error info
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
lotteryDraw = extractLotteryDraw(result);
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(lotteryDraw.toString());
//when the lottery draw has been received enable the check button for the user to check numbers
Button checkNumbers = (Button)findViewById(R.id.check);
checkNumbers.setEnabled(true);
//Log.d("DownloadWebpageTask", lotteryDraw.toString());
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 100000 characters of the retrieved
// web page content.
int len = 200000;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setRequestProperty( "User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4" );
// Starts the query
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return (new String(buffer)).trim();
}
private LotteryDraw extractLotteryDraw(String html) {
Log.d("extractLotteryDraw",html);
LotteryDraw lotteryDraw = new LotteryDraw();
Document doc = Jsoup.parse(html);
Elements elements = doc.getElementsByClass("drawhistory");
//System.out.println(elements.toString());
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String[] split = noElement.text().split(" - ");
int[] numbers = new int[split.length];
int i = 0;
for (String strNo : split) {
numbers[i] = Integer.valueOf(strNo);
i++;
}
lotteryDraw.setNumbers(numbers);
Log.v("DEBUG", "the value of numbers is " + numbers);
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
lotteryDraw.setBonusBall(bonusBall);
Log.v("DEBUG", "the value of numbers is " + numbers);
return lotteryDraw;
}//extractLotteryDraw
}//class
Add activity reference in your AndroidManifest.xml inside application tag
<activity android:name=".DisplayNumbersActivity"/>

Compare contents of two files line by line

public class MainActivity extends Activity {
FileOutputStream fos;
FileInputStream fOne, fTwo;
ArrayList<String> arr1 = new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
ArrayList<String> wordsTwo = new ArrayList<String>();
int count = 0;
int countTwo = 0;
int countThree = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fileOne = (Button)findViewById(R.id.file1);
Button fileTwo = (Button)findViewById(R.id.file2);
Button compare = (Button)findViewById(R.id.compare);
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr1.add("4");
//arr1.add("3");
arr2.add("1");
arr2.add("2");
fileOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File1", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr1.size(); temp++)
{
fos.write((arr1.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
fileTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File2", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr2.size(); temp++)
{
fos.write((arr2.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
compare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fOne = openFileInput("File1");
fTwo = openFileInput("File2");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanFile = new Scanner(new DataInputStream(fOne));
Scanner scanFileT = new Scanner(new DataInputStream(fTwo));
words = new ArrayList<String>();
wordsTwo = new ArrayList<String>();
while (scanFile.hasNextLine())
{
if(scanFile.nextLine()!=null)
{
count++;
}
while(scanFileT.hasNextLine())
{
if(scanFileT.nextLine()!=null)
{
countTwo++;
}
}
}
try
{
fOne.close();
fTwo.close();
scanFile.close();
scanFileT.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "One : " + count, 1000).show();
Toast.makeText(getBaseContext(), "Two : " + countTwo, 1000).show();
Toast.makeText(getBaseContext(), "Three : " + countThree, 1000).show();
count = 0 ;
countTwo = 0;
countThree = 0;
}
});
}
}
Above is the code to write and read the file. What I did here, write two files and read the contents..Now I have to compare contents of files line by line. What needs to be done?
Try following code. This will give you desired output. I took files from asset directory. So you need to replace that line of code if you are taking files from other directory.
private void compareFiles() throws Exception {
String s1 = "";
String s2 = "", s3 = "", s4 = "";
String y = "", z = "";
// Reading the contents of the files
BufferedReader br = new BufferedReader(new InputStreamReader(
getAssets().open("first.txt")));
BufferedReader br1 = new BufferedReader(new InputStreamReader(
getAssets().open("second.txt")));
while ((z = br1.readLine()) != null) {
s3 += z;
s3 += System.getProperty("line.separator");
}
while ((y = br.readLine()) != null) {
s1 += y;
s1 += System.getProperty("line.separator");
}
// String tokenizing
StringTokenizer st = new StringTokenizer(s1);
String[] a = new String[10000];
for (int l = 0; l < 10000; l++) {
a[l] = "";
}
int i = 0;
while (st.hasMoreTokens()) {
s2 = st.nextToken();
a[i] = s2;
i++;
}
StringTokenizer st1 = new StringTokenizer(s3);
String[] b = new String[10000];
for (int k = 0; k < 10000; k++) {
b[k] = "";
}
int j = 0;
while (st1.hasMoreTokens()) {
s4 = st1.nextToken();
b[j] = s4;
j++;
}
// comparing the contents of the files and printing the differences, if
// any.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
}
}
Log.d("Home", "No. of differences : " + x);
if (x > 0) {
Log.d("Home", "Files are not equal");
} else {
Log.d("Home", "Files are equal. No difference found");
}
}
Input File 1
Hi
Hello
Chintan
Rathod
Input File 2
Hi
HellO
Chintan
RathoD
Output
08-26 12:07:58.219: DEBUG/Home(2350): Hello3. -- HellO3.
08-26 12:07:58.219: DEBUG/Home(2350): Rathod -- RathoD
08-26 12:07:58.229: DEBUG/Home(2350): No. of differences : 2
08-26 12:07:58.229: DEBUG/Home(2350): Files are not equal
Edit
To get Difference between two files
Use StringUtils library which is provide by Apache and check this Documentation for more about that library.
And modify following lines of code.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
//to print difference
if (a[m].length() < b[m].length())
Log.d("Home", "" + StringUtils.difference(a[m], b[m]));
else
Log.d("Home", "" + StringUtils.difference(b[m], a[m]));
}
}
Output
08-26 17:51:26.949: DEBUG/Home(17900): 12 -- 123
08-26 17:51:26.949: DEBUG/Home(17900): Difference String : 3
08-26 17:51:26.949: DEBUG/Home(17900): No. of differences : 1
08-26 17:51:26.949: DEBUG/Home(17900): Files are not equal
Try using java.util.Scanner
while (sc1.hasNext() && sc2.hasNext()) {
String str1 = sc1.next();
String str2 = sc2.next();
if (!str1.equals(str2))
System.out.println(str1 + " != " + str2);
}
Change your while loop to the following:
while (scanFile.hasNextLine() && scanFileT.hasNextLine())
{
if(scanFileT.nextLine().equals(scanFile.nextLine()))
{
// The lines are equal.
} else {
// The lines are not equal.
}
}
if(scanFile.hasNextLine() || scanFileT.hasNextLine())
{
// If more lines remain in one of the files, they are not equal.
} else {
// If no content remains in both files, they are equal.
}
Depending on the size of your file, I would recommend some optimisation like checking the file sizes before you go through them line by line.
The overall logic reads as follows; if both have another line, compare it to see if it is equal. If they don't have another line, check if one of them has lines remaining, if so, they are not equal.
Update
After clarifying the objective of the comparison in chat, see the comments to this question, I have come to the conclusion that another comparison would be more effective and, as a matter of fact, correct. The comparison algorithm above works great if comparing the structure of text but not if comparing a data vector which may or may not be sorted. After some discussion, we came to the conclusion that data needs to be sorted or the comparison will blow the complexity to at least O(n^2)which could be done in O(2n) if the data is sorted. Here the algorithm's skeleton:
if(! scanGroupFriends.hasNextLine())
{
//simple sanity check to see if we need to compare at all. In this case, add all friends.
} else {
String nextFriend = scanGroupFriends.nextLine();
while(scanAllFriends.hasNextLine())
{
if(scanAllFriends.nextLine().equals(nextFriend))
{
// Friend already figures, do not add him and advance the list of group friends.
if(scanGroupFriends.hasNextLine())
{
nextFriend = scanGroupFriends.nextLine();
} else {
// There are no more friends in the group, add all remaining friends to list to show.
break; // Terminate the `while` loop.
}
}
}
}
However, I personally think it is bad to make to many assumptions. What I would suggest is that the friends be saved in a Set, a TreeSet for example. Then, serialize the object rather than manually writing it to file. Sets are neat because they hold several interesting objects. For example, you could easily use the following code to remove all friends in a group from the set of all friends:
allFriends.removeAll(groupFriends);
However, be aware that this removes it from the set completely so you should make a copy beforehand.

receive a string message from user input in android and parse to an int so can be stored in an array and compared with another array of integers

I am having a problem with the above task in my android application. I am accepting user input from the EditText widget in the form of String. I accepting numbers from the user so I have to parse them to integers so they can be compared with another array of integers. I have the line:
String message = editText.getText().toString()
then to try and parse the String to an int I have the code line:
int userNumbers = Integer.parseInt(message).
However when I attempt to compare the array userArray with the array numbers I am getting the error that "Incompatible operand types String and Integer.
Can anyone see where my problem is or how I can solve it? Here's my code:
Thanks in advance.
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = ".com.example.lotterychecker.MESSAGE";
static boolean bonus = false;
static boolean jackpot = false;
static int lottCount = 0;
Button check;
Integer [] numbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//link to the intended web site and get the lottery numbers while the app is opening
try {
Document doc = Jsoup.connect("http://www.national-lottery.co.uk/player/p/drawHistory.do").userAgent("Mozilla").get();
Elements elements = doc.getElementsByClass("drawhistory");
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String [] split = noElement.text().split(" - ");
// set up an array to store numbers from the latest draw on the lottery web page
Integer [] numbers = new Integer [split.length];
int i = 0;
for (String strNo : split) {
numbers [i] = Integer.valueOf(strNo);
i++;
}
for (Integer no : numbers) {
System.out.println(no);
}
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
System.out.println("Bonus ball: " + bonusBall);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//called when the user clicks the send button
public void checkNumbers(View view) {
final int SIZE =6;
String [] userArray = new String[SIZE];
//create an intent to display the numbers
Intent intent = new Intent(this, DisplayNumbersActivity.class);
EditText editText = (EditText) findViewById(R.id.enter_numbers);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message );
startActivity(intent);
//parse string message to an int for user numbers
try{
int userNumbers = Integer.parseInt(message); //is this right?
}//try
catch (NumberFormatException e)
{
System.out.println("Not a number" + e.getMessage());
}
Toast.makeText(MainActivity.this, "Here are your numbers", Toast.LENGTH_LONG).show();
for (int count =0; count < SIZE; count ++)
{
if (check.isPressed())
{
userArray[count] = editText.getText().toString();
}
}//for
//compare the two arrays of integers
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (userArray[loop] == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}//for
}//for main
You have this
Integer [] numbers; // numbers is an integer array
You have string array
String [] userArray = new String[SIZE]; // userArray is a string array
You compare like below
if (userArray[loop] == numbers[loopOther])
So you get the error Incompatible operand types String and Integer.
try
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
Enclosing the above with try catch block
String message = editText.getText().toString();
try{
int userNumbers = Integer.parseInt(message);
//is this right? yes
}
catch (NumberFormatException e)
{
e.printStacktrace();
}
Change String to Int here:
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.valueOf(userArray[loop]) == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (Integer.valueOf(userArray[loop]) == bonus)
{
bonus = true;
}
}//for
}//for main
Parse Like this :
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}
}

Categories

Resources