Pass php var or string to java. Android Studio - java

I'm not really sure how to do go about passing a variable from PHP to Java. I'd like to do the business logic in Java. I'd like to pass a variable $result from the PHP script dupCreateAccount.php.
<?php
require "db.php";
if(mysqli_num_rows($resultName) > 0 || mysqli_num_rows($resultEmail) > 0)
{
$result = "ex";
}
else
{
$result = "b";
}
if( count_chars($password) < 6)
{
$result = "bP";
}
echo (string) $result;
?>
This the php code. When I echo the results I can see the strings when running the android emulator.
protected String doInBackground(String... voids) {
String type = voids[3];
String checkUsername_url = "http://localhost/dupCreateAccount.php";
if(type.equals("Validate"))
{
try {
String user = voids[0];
String email = voids[1];
String password = voids [2];
URL url = new URL(checkUsername_url);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream outputStream = httpConn.getOutputStream();
BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_date = URLEncoder.encode("user", "UTF-8") + "="+URLEncoder.encode(user,"UTF-8") + "&"
+ URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email, "UTF-8") + "&"
+ URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
buffWriter.write(post_date);
buffWriter.flush();
buffWriter.close();
outputStream.close();
InputStream is = httpConn.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
String result = "";
String line;
while((line = bf.readLine()) != null)
{
result += line;
}
bf.close();
is.close();
httpConn.disconnect();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
if(result.equals("b"))
result = "bad username or email";
if(result.equals("bP"))
result = "bad password";
alert.setMessage(result + " on Crack Execute here");
alert.show();
}
What I was thinking was that when I return the variable result in PHP it gets sent too the OnPostExecute method. But I don't that's right. I'm not sure what step I'm missing .
EDIT: So the php result gets passed to java. But the problem i'm having is messing with the String result after it's passed. In the OnPostExecute method the equals method doesn't do anything.

Related

Issue with Translation API in Java

i am trying to translate from english into Arabic using translate.googleapis.com.
it works well with all letters except one letter it always show letter 'ف' as '�?'
any suggestions ?
private static String callUrlAndParseResult(String langFrom, String langTo, String word) throws Exception {
String url =
"https://translate.googleapis.com/translate_a/single?" + "client=gtx&" + "sl=" + langFrom + "&tl=" +
langTo + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
URLConnection con = obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return parseResult(response.toString());
}
private static String parseResult(String inputJson) throws Exception {
/*
* inputJson for word 'hello' translated to language Hindi from English-
* [[["??????","hello",,,1]],,"en"]
* We have to get '?????? ' from this json.
*/
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
return jsonArray3.get(0).toString();
}
public static void main(String[] args) {
try {
String word = callUrlAndParseResult("en", "ar", "phone");
System.out.println(new String(word.getBytes(), Charset.forName("UTF-8")));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
i am using jdeveloper 12cR2
Please note that whenever you use Reader, there will be conversions between charsets. If you do not specify your charset, it will use the system default charset to encode the incoming byte stream, and you would get into trouble if the incoming byte stream is actually not in the same charset with your system.
Therefore, it is advised to specific the charset when using Reader.
So your code should like below.
private static String callUrlAndParseResult(String langFrom, String langTo, String word) throws Exception {
String url =
"https://translate.googleapis.com/translate_a/single?" + "client=gtx&" + "sl=" + langFrom + "&tl=" +
langTo + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
URLConnection con = obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return parseResult(response.toString());
}
private static String parseResult(String inputJson) throws Exception {
/*
* inputJson for word 'hello' translated to language Hindi from English-
* [[["??????","hello",,,1]],,"en"]
* We have to get '?????? ' from this json.
*/
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
return jsonArray3.get(0).toString();
}
public static void main(String[] args) {
try {
String word = callUrlAndParseResult("en", "ar", "phone");
System.out.println(word);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

Read any Language String from Google Translator in Android

I am creating a translator app where I am getting the input text from android supported voice Recognizer. Example : Hindi, Chinese, etc. Now I want to build the query like this -
public JSONObject getTranslatedText() {
StringBuilder sb = new StringBuilder();
String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
JSONObject response = null;
String json = "";
HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
String line1 = "{\n" + " 'q': '" + inputString + "',\n" + " 'target': '" + targetcodeString + "'\n" + "}";
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(line1);
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
json = sb.toString();
response = new JSONObject(json);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (JSONException e) {
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return response;
}
The problem is it is not encoding properly and I am getting output like this -
Example: For a word "How are you" in Hindi i.e "क्या हाल" as 9 & HG 08 * E
Can I get some help please. Thanks in advance.
Try using Html.fromHtml(yourTranslatedStr).toString().
I tried that with Hindi and it worked.

Google Distance Matrix not getting distance

I have roughly tried to parse the JSON from Google Distance Matrix API, but it is not showing the distance.
My GPS location is not 0,0 that I'm sure of.
String distance = getMatrix(latitude,longitude);
My code for the function is:
private String getMatrix(double lat , double lang){
JSONObject jObj;
String getdistance = "";
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
String data = "";
InputStream reader = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
urlConnection.disconnect();
} catch(Exception e) {
} finally {
}
try {
jObj = new JSONObject(data);
JSONArray rowsArray = jObj.getJSONArray("rows");
JSONObject rows = rowsArray.getJSONObject(0);
JSONArray elementsArray = rows.getJSONArray("elements");
JSONObject newDisTimeOb = elementsArray.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
getdistance = distOb.optString("text").toString();
} catch (JSONException e) {
e.printStackTrace();
}
return getdistance;
}
First, check if you've correctly build the url string in the code:
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
// Line to check if url code is right
Log.d("APP", "strUrl = " + strUrl);
Then check your following code, whether it really produce the data:
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
My suggestion is to use BufferedReader instead reading the response byte per byte.
Then change:
getdistance = distOb.optString("text").toString();
to
getdistance = distOb.getString("text");
Because you don't need to convert to string again here.
I've search Client Libraries for Google Maps Web Services and found DistanceMatrixApi.java. Maybe we can use it, but I can't assure of it.

Can't POST data to site using HttpURLConnection on Android

I'm essentially trying to mimic what's been done here through the Android app but for some reason data doesn't get returned as soon as it attempts to post data (it returns fine when I delete the writer.write(finalResult) line).
All I want right now is to be able to search for a user's data once I've sent the username.
Here's my code below:
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-length", "0");
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setDoInput(true);
c.setDoOutput(true);
//Attempting to send data!
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", paramValue));
OutputStream os = c.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String finalResult = getQuery(params);
Log.d("params", finalResult);
writer.write(finalResult);
writer.close();
os.close();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
result = sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("log_tag", "Error converting result ");
} catch (IOException ex) {
Log.e("log_tag", "Error in http connection ");
}
//json code!
//parse json data
try{
JSONArray jArray = new JSONArray(result);
//for each object in our json array
for(int i =0; i < jArray.length(); i++){
JSONObject json_data =jArray.getJSONObject(i);
String address = "";
//Checks for missing data in address - Need a class for all fields
if (json_data.isNull("address")){
address = "N/A";
}
else
{
address = json_data.getString("address");;
}
//read one line of the response
myListView.setText("Username: "+json_data.getString("username")
+" / " + "Name: " + json_data.getString("name")
+" / " + "E-mail: " + json_data.getString("email")
+" / " + "Address: " + address);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data"+e.toString());
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
And here is my php script:
<?php
$searchuser = $_GET["username"];
$databasehost = databasehost;
$databasename = database;
$databaseusername = username;
$databasepassword = password;
$con = mysql_connect($databasehost, $databaseusername, $databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT * FROM testusers";
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query."\n";
echo mysql_error();
}
else
{
$rows = array();
while ($r = mysql_fetch_assoc($sth)){
$rows[] = $r;
}
print json_encode($rows);
}
?>
Since you set the header Content-Length to be 0, the server doesn't even read your content... So anything you send isn't received. You should set Content-Length to finalResult.length().
remove this,
c.setRequestProperty("Content-length", "0");

android api call return simple array

i am calling an api which should return an array of length between 0 to 9. Now i am not understanding how to get that array. for getting simple string other api's
My code is:are working fine according to this code.
private String test(String url)
{
String str = null;
int c;
try
{
URL hp = new URL(url); //The String hp1 is passed in URL
URLConnection hpCon = hp.openConnection();
hpCon.setUseCaches(false);
hpCon.setConnectTimeout(10000);
System.out.println("*url content for: " + url);
InputStream input=hpCon.getInputStream();
StringBuffer sb = new StringBuffer();
while(((c=input.read())!= -1))
{
sb.append((char)c);
}
str=sb.toString();
sb = null;
//System.out.print(str);
input.close();
input = null;
hpCon = null;
hp = null;
}
catch(Exception e)
{
}
return str;
}

Categories

Resources