Error in execution of Try/catch statement in Android - java

This code is used to find if a book is available or not.
Now IF the bookname for eg is Analog Electronics
and if i Enter input just as Analog or electronics it will display the full bookname Analog electronics which means that the 1st n 2nd try/catch block were executed properly.
But when i Enter input as Analog electronics with a space in between the two words it delivers an error and says "Check your internet connection " even when my internet connection is proper. It catches the error in the 1st try/catch block which should'nt have happened. I am getting an error all because of the "space".
try {
response = CustomHttpClient.executeHttpPost(
"http://duh.com/lol.php?name="+input,
postParameters);
String result = response.toString();
try{
returnString = "";
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", Bookname: "+json_data.getString("Bookname")+
);
returnString += "\n" + "Book+ json_data.getString("Bookname");
}
}
catch(JSONException e){
Toast toast = Toast.makeText(getBaseContext(), "Book is not availabe" ,Toast.LENGTH_LONG);
toast.show();
toast.getView().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getBaseContext(), MainActivity.class));
finish();
}
}, 3500);
}
try{
tv.setText(returnString);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Error in Display" ,Toast.LENGTH_LONG).show();;
}
}
catch (Exception e) {
Toast toast = Toast.makeText(getBaseContext(), "Check your Internet connection" ,Toast.LENGTH_LONG);
toast.show();
toast.getView().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getBaseContext(), MainActivity.class));
finish();
}
}, 3500);
};
}
LOG cat error :
04-22 20:51:52.589: E/log_tag(1322): Check your internet connection!!java.lang.IllegalArgumentException: Illegal character in query at index 52: http://duh.com/lol.php?name=analog electonics
04-22 20:51:52.759: W/EGL_emulation(1322): eglSurfaceAttrib not implemented

as per your logcat error:
04-22 20:51:52.589: E/log_tag(1322): Check your internet connection!!java.lang.IllegalArgumentException: Illegal character in query at index 52: http://duh.com/lol.php?name=analog electonics
you have an illegal character in your query.
URLs aren't allowed to have a space character in them without it being encoded (see this page for more details), so you will need to encode your query string before requesting the page.
see this SO answer for the correct way to encode a URL on Android

Related

Intent not working with if operator Android

I try when it displays a message when I press a button to redirect me to a page, but it doesn't work. When successful, the message is displayed but does not forward me.
private void registerUser() {
try {
Account account = new Account();
account.setpAddress(edt_adress.getText().toString());
account.setpBloodGroup(edt_blood.getSelectedItem().toString());
account.setpFirstName(edt_first.getText().toString());
account.setpMidName(edt_mid.getText().toString());
account.setpFamilyName(edt_fam.getText().toString());
account.setpGender(edt_gender.getSelectedItem().toString());
account.setpPhone(edt_phone.getText().toString());
account.setpEgn(edt_egn.getText().toString());
account.setuPassword(edt_password.getText().toString());
account.setuUsername(edt_username.getText().toString());
INodeJS accountservice = RetrofitClient.getInstance().create(INodeJS.class);
Call call = accountservice.create(account);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
Account result = (Account) response.body();
Toast.makeText(getApplicationContext(), result.getNotes(), Toast.LENGTH_LONG).show();
if (result.getNotes().equals("Success")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
// startActivity(intent);
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(), getString(R.string.createfield), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
looks like result.getNotes().equals("Success") isnt true, are you shure it should be? equals is case-sensitive so "success" doesn't equal "Success" and also " Success " - note whitespaces
maybe you can try with this statement:
result.getNotes().toLowerCase(Locale.getDefault()).trim().equals("success")
toLowerCase will make all your letters small caps and trim will remove all whitespaces at beggining and end of String
also there is equalsIgnoreCase method so it may also looks like below:
result.getNotes().trim().equalsIgnoreCase("success")

Android Studio: 2 different activities in 1 button

I want to make the login button to dispatch into 2 different activities using the flag column on the database??
if the tenant logged in it will redirect to the tenant activity
and when the landlord is logged in it will redirect to the other activity?
public void onResponse(String response) {
Log.e(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String id = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();
// go to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
Inside the onClickListener() method of your log in button,you can put a if() statement.
Steps To Do this
1. Get the data from the username and password field and use that in your query to retrieve the data from the database
2. Store the data you retrieved in a String like below because you will get only one row:
String flag = cursor.getString(7); //skipping the cursor and other database part
3. Now you can put the if() statement in the onClickListener of login button after getting the String flag value like:
if(flag.equals(landlord)){
Intent intent = new Intent(this,Landlord.class);
startActivity(intent);
}
else{
Intent intent = new Intent(this,Tenant.class);
startActivity(intent);
}
Anyhow you will be querying to verify username & password, at the same time you could also fetch the flag information and store it in locally(reduces the database calls).
Store those data in a map with key as username (Assumption username will be unique) and flag as value.
Map<String,String> mapToRouting = new Map<String,String>();
Now for routing different activities, inside the button click method try like
public static void buttonClickMethod(){
//textFieldUserName is the username of user trying to login
if(isLanlord(textFieldUserName)){
//this means user is Landlord & put code to redirect to corresponding screen
}
else{
//put code to which redirects to tenants screen!
}
}
Method to find whether the user is landlor or not.
public static void isLandlord(String userName){
boolean result = false;
if(mapToRouting.get(userName).equalsIgnorecase("Landlord"))
result = true;
return result;
}
Hope this will be helpful.

Why Retrofit can't resolve No connection - Check internet connection on Android?

Hello guys I have one specific problem. I'm using retrofit library for all of my network calls. And I have one method to send points to another user and if any error occurs, the server will return me code 400 and string alongside it that I will have to show to user. This thing is working I created it like this ( NetworkSDK is sending a body with params and expect to recieve an error status string if it occurs) so logically I am processing my errors in onResponse method (if Networksdk recieve an object with error string) and if onFailure occurs there is no error. But now I have a bigger problem. If there is no connection at all, if user turns off internet in that fragment it will again go to onFailure and show message that points are sent. Ordinary I would do that via status code if status code is 200 than it's okey but for some reasons I can't get any status code via response.code() command. Here is the code :
#Override
public void onClick(View v) {
try {
final String cardNo;
String amountstring = bodovi.getText().toString();
final Integer amount = Integer.valueOf(amountstring);
cardNo = brojkartice.getText().toString();
Log.d("Broj bodova:", amount.toString());
Log.d("Broj kartice:", cardNo);
final SendPoints Posiljka = new SendPoints();
Posiljka.setAmount(amount);
Posiljka.setCardNumber(cardNo);
NetworkSDK.getInstance().SendPoints(Posiljka, new Callback<SendPointsResponse>() {
#Override
public void onResponse(Call<SendPointsResponse> call, Response<SendPointsResponse> response) {
Log.d("Response code:", "" + response.code());
Log.d("Kartica", Posiljka.getCardNumber());
Log.d("Broj bodova", Posiljka.getAmount().toString());
try {
SendPointsResponse error = (new Gson()).fromJson(response.errorBody().string(), SendPointsResponse.class);
if (error.getCode().equals("-1"))
Toast.makeText(getActivity(), "Neuspješno slanje bodoava. Neispravni ulazni podaci.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-2"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnički podaci nisu popunjeni.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-3"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ima rezervisanu nagradu.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-4"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. U toku jednog mjeseca bodove je moguće poslati maksimalno dva puta.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-5"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Bodove nije moguće poslati samom sebi.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-6"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ne može primiti bodove.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-100"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Greška nepoznata.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<SendPointsResponse> call, Throwable t) {
Toast.makeText(getActivity(), "Uspješno slanje bodova.", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e) {
Toast.makeText(getActivity(), "Podaci nisu ispravni, provjerite podatke !", Toast.LENGTH_SHORT).show();
} }
});
}
I basicly need some idea in OnFailure method to detect if user is turned off internet and to display proper message.
You can check this link where is explained in detail if internet connection status is available usgin the ConnectivityManager through the Connectivity Service.
Notice that your app will need permissions for obtaining the network status:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Speech to Text to get previous word after saying another word Android

I have a project using Speech to Text where you can text someone without typing and sending it via voice.
Now I have a code where the user says the words/sentence that he/she wants to send, and I also have a confirmation where the user needs to say YES to send.
Now my codes are
//Voice recording message via mic
public void promptSpeechInput() {
//Create intent to recognize the speech and we have putExtra to have other values than voice itself
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something!");
//StartActivityForResult always binded by intent, getting the result from previous intent
try {
startActivityForResult(i, 100);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "You device does not support LazySpeech App", Toast.LENGTH_LONG).show();
}
}
Here is my onActivityResult code
#Override
protected void onActivityResult(int request_code, int result_code, Intent data) {
super.onActivityResult(request_code, result_code, data);
switch (request_code) {
case 100:
if (result_code == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
sampleTextView.setText(result.get(0));
String getMessage = sampleTextView.getText().toString();
messageHolder(getMessage);
String getAnswer = sampleTextView2.getText().toString();
switch(getAnswer){
case"yes":
ttsobject.speak("yes?", TextToSpeech.QUEUE_FLUSH, null);
sampleTextView3.setText(getMessage);
break;
case"no":
ttsobject.speak("No?", TextToSpeech.QUEUE_FLUSH, null);
break;
default:
break;
}
}
}
}
and Here is my confirmation text
public String messageHolder(String getMessage){
if(getMessage != ""){
if (Build.VERSION.RELEASE.startsWith("15")) {
ttsobject.speak("You want to send this message".concat(getMessage) + "?", TextToSpeech.QUEUE_FLUSH, null, null);
activateMicButton();
} else {
ttsobject.speak("You want to send this message".concat(getMessage) + "?", TextToSpeech.QUEUE_FLUSH, null);
activateMicButton();
}
}else{
if (Build.VERSION.RELEASE.startsWith("15")) {
ttsobject.speak("say your words again", TextToSpeech.QUEUE_FLUSH, null, null);
activateMicButton();
} else {
ttsobject.speak("say your words again", TextToSpeech.QUEUE_FLUSH, null);
activateMicButton();
}
}
return getMessage;
}
and for example he/she said
"Hey wanna have dinner?".
The question is, How can I get the words(Hey wanna have dinner) that he/she wants to send, because all I can get is the "YES" or "NO" text from my confirmation.
I have tried creating something like this
sampleTextView2.setText(result.get(1));
String getSentence = sampleTextView.getText().toString();
I also have tried making static string, put it in globalvariable,
and still no luck. the words kept changing everytime I say something on mic,
anyone knows how to solve this?
You can save your previous words by just copying the string, not the pointer to it, like you did it with global variable. You can do it by creating new String object, using the following constructor:
String theWords = new String(result.get(0));
And then you can use theWords variable to get the message user wants to send.

TextToSpeech interact dynamically

I'm using TextToSpeech to send an sms to someone in my contacts. I use a very ugly way to do it because i need say the all expression "send message to contact text message is hello" in one way. It would be better something like "Send message" and the app ask me to who and go on in this way.. So i can interact with the application like google now in dinamically way. The code i use so far is this one:
if(resultList.getText().toString().toLowerCase().contains(getResources().getString(R.string.messaggio))) //invio sms
{
splitMessage = message.split(getResources().getString(R.string.destinatario), 2);
if(splitMessage.length>1){
if((splitMessage[0].trim()).equalsIgnoreCase(getResources().getString(R.string.inviamessaggio)))
{
splitMessage[0] = "message";
splitMessage[1] = splitMessage[1].trim();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
splitMessageWithNameAndBody = splitMessage[1].split(getResources().getString(R.string.testomessaggio), 2);
if(splitMessageWithNameAndBody.length>1)
{
splitMessage[0] = "text message";
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
splitMessage[1] = splitMessageWithNameAndBody[0].trim();
splitMessageWithNameAndBody[1] = splitMessageWithNameAndBody[1].trim();
if(Name.compareToIgnoreCase(splitMessage[1])== 0)
{
nameMatchFound = true;
flag=1;
String url = "sms:"+Number;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra("sms_body", splitMessageWithNameAndBody[1]);
startActivity(intent);
}
}
if(!nameMatchFound)
{
Toast.makeText(getApplicationContext(), "Contatto non trovato o ci sono più corrispondenze", Toast.LENGTH_SHORT).show();
DialogFragment df=new DialogTrial();
df.show(getSupportFragmentManager(), "MyDialog");
}
} else {
//Toast.makeText(getApplicationContext(), "Please say contact name followed by call or message keyword", Toast.LENGTH_LONG).show();
while (phones.moveToNext()){
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(Name.compareToIgnoreCase(splitMessage[1]) == 0){
nameMatchFound = true;
String url = "sms:"+Number;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra("sms_body", splitMessageWithNameAndBody[1]);
startActivity(intent);
}
}
}
}
else
{
Toast.makeText(getApplicationContext(), "Please say contact name followed by call keyword", Toast.LENGTH_LONG).show();
}
}
//break;
}
if it doesn't find any corrispondance it ask me to search in my contacts the right name. By the way, is what i want do possible? Thanks
Is it possible? Sure. I have an app I wrote that does something similar- it reads out a text, asks if you want to respond, then asks for the response (if yes), then reads it and asks for confirmation before sending. Besically you need to make a state machine so you know how to process a response when it comes in and what to speak out for the next input.

Categories