Android random string doesn't check - android

Random string works fine.
Doesn't work check now.
I enter the text to what has been EditText drawn.
But the check is not working. Why?
Code:
public static StringBuffer random() {
String str = new String(
"G12HIJdefgPQRSTUVWXYZabc56hijklmnopqAB78CDEF0KLMNO3rstu4vwxyz9");
StringBuffer sb = new StringBuffer();
sb.toString();
String ar = null;
Random r = new Random();
int te = 0;
for (int i = 1; i <= 10; i++) {
te = r.nextInt(62);
ar = ar + str.charAt(te);
sb.append(str.charAt(te));
}
return sb;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
random = random().toString();
TextView display = (TextView) findViewById(R.id.textView1);
display.setText("Random Number: " + random); // Show the random number
et = (EditText) findViewById(R.id.etNumbers);
ok = (Button) findViewById(R.id.button1);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = et.getText().toString();
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "Bla bla bla", Toast.LENGTH_LONG)
.show();
}
if (random == charsEntered) {
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}
}
}

Try
if (random.equalsIgnoreCase(charsEntered))

Use String.equals instead of ==

You're trying to compare two strings with the == operator. This cannot compare strings until Java 7, and Android is based on Java 6. Try using:
if (random.equalsIgnoreCase(charsEntered))
If the check is case insensitive or
if (random.equals(charsEntered))
If the check is case sensitive.

You are comparing StringBuffer Class with String Class, try following,
if ( random.toString().equals(charsEntered) )
{
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}

Related

Android SMS multi text groups

My project is a checklist of phone numbers in a recyclerView/cardView. The phone numbers/businesses can be added or subtracted by a checkBox to make individual groups. I want to be able to send a group multi-text to the selected individuals.
My problem is that only the first phone number (recipient) in a group receives the message while the rest receive nothing, but the numbers still display in the edit text (the first is the only functioning number).
I have tried a lot of different ways but nothing has worked, I am about to give up.
No one seems to know how to fix this problem. If this problem can be solved please let me know.
I don't want to loop the numbers and text individually, that was a suggested fix.
This is the phone activity:
public class ACPhone extends AppCompatActivity {
private static final String SEPARATOR = ";";
EditText txtPhoneNo;
EditText txtMessage;
TextView txtView;
Button btnsend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acphone);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
txtView = (TextView)findViewById(R.id.txtMessageMass);
btnsend = (Button) findViewById(R.id.btnSend);
Intent intent = getIntent();
if (intent != null){
ArrayList<CharSequence> selectedNumbers =
intent.getCharSequenceArrayListExtra(SELECTED_NUMBERS);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < selectedNumbers.size(); i++) {
sb.append(selectedNumbers.get(i));
if (i != selectedNumbers.size() - 1){
sb.append(SEPARATOR);
}
}
txtPhoneNo.setText(sb.toString());
}
btnsend.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
String messageView = txtView.getText().toString();
if (phoneNo.length() > 0 && message.length() > 0) {
sendMessage(phoneNo, message, messageView);
} else {
Toast.makeText(getBaseContext(), "Please enter message",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendMessage(String phoneNo,String message, String staticMessage){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo,null,message + "\n" +
staticMessage,null,null);
Toast.makeText(getApplicationContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "Unable to send. Please try again", Toast.LENGTH_SHORT).show();
}
}
}
You could create a list of all the numbers and do a for loop through the list in your onclick or in a method and call it in onclick. That's how I would do it anyway.
Following are the some steps to send one single message to multiple contact when it is checked.
Step 1 : In your MainActivity.class like this,
public class MainActivity extends AppCompatActivity {
ListView listView;
EditText editMessage;
ProgressDialog progressDialog;
Handler progresshandler;
boolean isThreadRunning;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.contactsView);
editMessage = (EditText) findViewById(R.id.editMessage);
listView.setAdapter(new ContactAdapter(this, contacts));
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Sending Messages.. Please wait!");
progresshandler = new Handler() {
public void handleMessage(Message msg) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Messages Sent",
Toast.LENGTH_LONG).show();
}
};
}
}
Step 2 : Create one class within this MainActivity.class(Put this class below onCreate() method)
class SendMessagesThread extends Thread {
Handler handler;
public SendMessagesThread(Handler handler) {
this.handler = handler;
}
public void run() {
SmsManager smsManager = SmsManager.getDefault();
// Find out which contacts are selected
for (int i = 0; i < listView.getCount(); i++) {
View item = (View) listView.getChildAt(i);
boolean selected = ((CheckBox) item.findViewById(R.id.selected)).isChecked();
if (selected) {
String mobile = ((TextView) item.findViewById(R.id.mobile)).getText().toString();
try {
smsManager.sendTextMessage(mobile, null, editMessage.getText().toString(), null, null);
} catch (Exception ex) {
Log.d("Mobile", "Could not send message to " + mobile);
}
}
}
Message m = handler.obtainMessage();
handler.sendMessage(m);
} // run
} // Thread
Step 3: Create one method(put this method below step - 2)
public void sendMessages(View v) {
if (editMessage.getText().toString().length() > 0) {
SendMessagesThread thread = new SendMessagesThread(progresshandler);
thread.start();
progressDialog.show();
} else {
Toast.makeText(this, "Please enter message!", Toast.LENGTH_LONG)
.show();
}
}
Note : According to my project, I am not using any SQLite database or webservice.Basically, I am fetching all the contact from device contact book and displaying that contact to listview. So, Try to understand and modify.
public class TextActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<CharSequence> selectedNumbers
=getIntent().getCharSequenceArrayListExtra(SELECTED_NUMBERS);;
String phNumbers = "";
for (CharSequence s: selectedNumbers) {
phNumbers += s + ";";
}
// for (int i = 0; i < selectedNumbers.size(); i++) {
// phNumbers += selectedNumbers.get(i);
// if (i != selectedNumbers.size()-1){
// phNumbers += ";";
// }
// }
phNumbers = phNumbers.substring(0, phNumbers.length() - 1);
String message = "";
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", phNumbers);
smsIntent.putExtra("sms_body",message);
startActivity(smsIntent);
}
}

FTDI Android - create new activity

This code is able to make the android device as a USB host for the hardware model. It also can read data from the hardware correctly in Main Activity. However, as soon as I moved it to another activity, everything still works but the data reading is incorrect.
For instance, I'm trying to write the data read into file. First activity is to input filename and just a button to send to another activity. The code below is in the second activity
public class Temp extends Activity {
private FileOutputStream outputStream;
public static D2xxManager ftD2xx= null;
Handler mHandler = new Handler();
FT_Device ftDev = null;
int devCount = 0;
UsbDevice device = null;
TextView Text =null;
String temp = null;
_4DPoint P = null;
int rd = 0;
byte[] byt = null;
byte[] Fdata = null;
String outp = "";
String From_Serial = "";
int Min = -1;
String fileName;
Context c;
final Runnable updateResults = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Text.setText("" + Min + '\n' + temp);
}
};
public void getData(){
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byt = new byte[256];//{(byte)'a','b','c','d',};
Toast.makeText(getBaseContext(), "start " + fileName , Toast.LENGTH_LONG).show();
Text = (TextView)findViewById(R.id.test2);
device = (UsbDevice) getIntent().getParcelableExtra("USB");
ftD2xx = D2xxManager.getInstance(c);
ftD2xx.addUsbDevice(device);
devCount = ftD2xx.createDeviceInfoList(c);
if (devCount > 0) {
ftDev = ftD2xx.openByUsbDevice(c, device);
}
if( ftDev.isOpen() == true ) {
ftDev.setBitMode((byte)0 , D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(38400);
ftDev.setDataCharacteristics(D2xxManager.FT_DATA_BITS_8, D2xxManager.FT_STOP_BITS_1, D2xxManager.FT_PARITY_NONE);
ftDev.setFlowControl(D2xxManager.FT_FLOW_NONE, (byte) 0x0b, (byte) 0x0d);
Thread t = new Thread() {
public void run() {
int i;
while(true){
rd=0;
while (rd==0){
rd = ftDev.read(byt, 14);
}
for(i=0; i<rd; i++)
outp += (char)byt[i];
From_Serial = new String(outp);
P = new _4DPoint(From_Serial);
temp = String.format("%s: %f %f %f %f %d\n", From_Serial, P.R, P.G, P.B, P.L, P.camera);
try {
outputStream.write(temp.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outp = "";
mHandler.post(updateResults);
}
}
};
t.start();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (D2xxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color);
// Show the Up button in the action bar.
setupActionBar();
Intent intent = getIntent();
fileName = intent.getStringExtra("File Name");
c = this;
getData();
}
The set up should be fine since it's reading data from hardware, but the data read is incorrect.
Also, I'm wondering why we need to create new thread while reading data. I tried not creating new thread and it didn't work well, but still have no idea why? I tried to contact the person who wrote the code to read data but no reply.
Any help would be really appreciated :)
You state that you receive data, therefor I think you should look at your ftDev settings. Try for example to set ftDev.setBaudRate(115200) (this worked for me) or try playing with your other ftDev Settings a little bit.
The settings I use in my programm are:
int baudRate = 115200;
byte stopBit = 1; /*1:1stop bits, 2:2 stop bits*/
byte dataBit = 8; /*8:8bit, 7: 7bit*/
byte parity = 0; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl = 1; /*0:none, 1: flow control(CTS,RTS)*/
If this won't work, it is wise to first check this data communication with a computer program e.g. or to analyse the incomming 'wrong' data.

isCancelled() not Working in android Async Task

I want to cancel a downloading file using async task, i tried below code, here isCancelled() method is not working, can any one suggest how can i stop download.
vid1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
down d1=new down();
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
d1.execute(url1,"one");
}else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(d1!=null && d1.getStatus()!=AsyncTask.Status.FINISHED){
d1.cancel(true);
}
}
}
});
vid2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Vid 2", "Vid 2");
// TODO Auto-generated method stub
down d2=new down();
if(vid2.getText().toString().equals("Start")){
vid2.setText("Pause");
d2.execute(url2,"two");
}else if(vid2.getText().toString().equals("Pause")){
vid2.setText("Start");
Log.v("Vid 2 Else", "Vid 2 Else ");
d2.cancel(true);
}
}
});
}
private class down extends AsyncTask<String, Void, String>{
RandomAccessFile output ;
boolean cancel=false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Log.v("Pre Execute", "Pre Execute");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
File outputFileCache=new File(Environment.getExternalStorageDirectory()+"/pau/"+params[1]+".mp4");
try {
Long download_ok = null ;
int fileLength;
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection() ;
if (outputFileCache.exists())
{
Log.v(">>>>>>", "Exists");
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + outputFileCache.length() + "-");
}
connection.setConnectTimeout(14000);
connection.setReadTimeout(20000);
connection.connect();
if (connection.getResponseCode() / 100 != 2)
throw new Exception("Invalid response code!");
else
{
String connectionField = connection.getHeaderField("content-range");
if (connectionField != null)
{
String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
download_ok = Long.valueOf(connectionRanges[0]);
Log.v("download ok", ""+download_ok);
}
if (connectionField == null && outputFileCache.exists())
outputFileCache.delete();
if(download_ok==null){
download_ok=(long) 0;
}
fileLength = (int) (connection.getContentLength() + download_ok);
Log.v("file length", ""+fileLength);
input = new BufferedInputStream(connection.getInputStream());
output = new RandomAccessFile(outputFileCache, "rw");
output.seek(download_ok);
byte data[] = new byte[1024];
int count = 0;
int __progress = 0;
while ((count = input.read(data, 0, 1024)) != -1 && __progress!=100)
{
Log.v(">>>>>>>>>>>progress cancelled", "<<<<<<<<<"+isCancelled());
if(isCancelled()){
Log.v(">>>>>>>>>>>>>>>>>>>>>>>>>>>", "<<<<<<<<<"+isCancelled());
break;
}else{
download_ok += count;
output.write(data, 0, count);
__progress = (int) ((download_ok * 100) / fileLength);
}
}
output.close();
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
Found your problem: You are creating a new instance of the Asynctask with every click, e.g.
down d2=new down();
This means that you are calling cancel on a different AsyncTask object. You need to move this line into your check for the start click and also use a field and not a local variable i.e.
if(vid2.getText().toString().equals("Start")) {
d2 = new down();
vid2.setText("Pause");
d2.execute(url2,"two");
}
where d2 is set in your class. Also note that class names should always start with capital letters, i.e. class Down instead of class down.
EDIT
You can store the Asynctask in a global class array that is equal in length to the number of videos.
Down downTasks[] = new Down[TOTAL VIDEOS];
Then you initialise the Views, similar to what you already did, here shown for one View
vid1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
downTasks[0] = new down();
downTasks[0].execute(url1,"one");
}
else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(downTasks[0]!=null && downTasks[0].getStatus()!=AsyncTask.Status.FINISHED){
downTasks[0].cancel(true);
}
}
}
});
Note that this code is quite redundant because you rewrite almost exactly the same code for every View, this can be nicely refactored with a for loop, but I leave that as an exercise for you if you feel like it.

Checking for escape character(0x1B,\033) while reading from socket

Ok, so I'm designing an Android MUD client as part of my school project. I'm having an issue, however, while implementing ANSI color parsing. I read in the data on a byte-by-byte basis. I've tried setting the character "hex" as '\033', '27', and '0x1B' but I can never seem to get it to detect the escape character. Is there anything you guys can see wrong with my checking of it? Also, the line "char check = String.valueOf(j).charAt(0);" is temporary, I was originally trying to check the character variable "hex" against the byte "j". Is there possibly a better way of checking for the character?
while(isConnected) {
int j = 0;
try {
int i = arrayOfByte.length;
j = streamInput.read(arrayOfByte, 0, i);
char check = String.valueOf(j).charAt(0);
Log.d("Console","Char is - " + check);
if (j == -1)
{
Log.d("Console","j = -1");
throw new Exception("Error while reading socket.");
} else if (j == 0) {
Log.d("Console","Continuing");
continue;
} else if (check == hex) {
Log.d("Console","Yo, daddio!");
} else {
final String strData = new String(arrayOfByte, 0, j).replace("\r", "");
runOnUiThread(new Runnable() {
public void run() {
textContent.append(strData);
scrollToBottom();
}
});
}
} catch (Exception e) {
Handler handlerException = GameWindow.this.mHandler;
String strException = e.getMessage();
final String strMessage = "Error while receiving from server:\r\nConnection terminated";
Runnable rExceptionThread = new Runnable()
{
public void run()
{
Toast.makeText(context, strMessage, 3000).show();
}
};
handlerException.post(rExceptionThread);
if(strException.indexOf("reset") != -1 || strException.indexOf("rejected") != -1)
{
isConnected = false;
try
{
connectionSocket.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
isConnected = false;
}
}
Well, you're checking the number of bytes read instead of each individual byte.
j = streamInput.read(arrayOfByte, 0, i);
returns the number of bytes read and put in arrayOfByte those bytes.
Therefore you need to do the following:
for (int n=0; n < j; n++)
{
if (arrayOfByte[n] == hex) Log.d("Console", "Yo, daddio!");
}

Click on pause can‘t get respond when download

When I download,click on pause,but there isn't respond.
I don't konw how to description specific,in fact it is meaning stop,but really can't realize.
the code
public void onClick(View v) {
[color=#FF0000]if (flag == 0){//click mark[/color]
can't display,the red is only a mark.
code as follows
holder.btns .setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
[color=#FF0000]if (flag == 0){//judge the click mark[/color]
holder.ratingBarScore.setVisibility(View.GONE);
holder.pro.setVisibility(View.VISIBLE);
holder.textView.setVisibility(View.VISIBLE);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
}else {
// Toast.makeText(this, "there is no SD card", 1000).show();
Log.v("wjp", "7889900");
}
final String downloadUrl =(String)v.getTag();
Thread thread = new Thread(){
int count = 0;
public void run(){
Log.v("ccf", "onClick");
try {
downLoadFile(context, downloadUrl, gameName, holder);
openFile(context, new File("/sdcard/9twan/"+ gameName +".apk"));
if(!WebHelper.REGISTER_FLAG){
Log.v("GamesInfoListAdapter", "WebHelper.REGISTER_FLAG == false");
String imei, mac, mobile_number, model, brand;
boolean flag;
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
imei = tm.getDeviceId();
if(imei == null){
imei = "CUSTOM" + WebHelper.generateRandomIMEIString(15);
}
mac = null;
// mac = tm.getDeviceId();
if(mac == null){
mac = "CUSTOM" + WebHelper.generateRandomMacString(17);
}
mobile_number = tm.getLine1Number();
model = tm.getLine1Number();
brand = tm.getLine1Number();
flag = WebHelper.regDevice(context, "install", imei, mac, mobile_number, model, brand);
if(flag){
WebHelper.REGISTER_FLAG = true;
Log.v("GamesInfoListAdapter", "WebHelper.REGISTER_FLAG == true");
}
}
}catch (Exception e){
e.printStackTrace();
}
}
};
Log.v("wjp", "running"+thread.getName());
thread.start();
Toast.makeText(context, "begin to download" + gameName, 0).show();
holder.btns.setBackgroundResource(R.drawable.tab_out);
[color=#FF0000]flag =1;[/color]//here is need to pause,how to write?
}else {
if(Thread.currentThread() !=null){
Thread.interrupted();
// Thread = null;
}
// thread.
// Thread.interrupted();//pause return boolean
// Thread.sleep(3000);
// Thread.
holder.btns.setBackgroundResource(R.drawable.tab_install);
flag =0;
}
}
});
}
return convertView;
You are trying to interrupt the current thread, You should interrupt the thread you have started. Also are you changing the value of flag. You seem to have multiple variables named flag
if(thread !=null){
thread.interrupt();
}

Categories

Resources