I have an android application, that makes a connection to a PHP-script, which then fetches data from a database and returns the result. It all works fine and dandy, except for language-settings. I have set the language to dainsh and UTF-8, all the places I can think of, and when I send it to the database it is in danish, but the returnvalue is not in danish.
Here is my call to the PHP-script from android
URL url = new URL(selectUrl);
HttpURLConnection httpUrlConncetion = (HttpURLConnection) url.openConnection();
httpUrlConncetion.setRequestMethod("POST");
httpUrlConncetion.setDoInput(true);
httpUrlConncetion.setConnectTimeout(10000);
httpUrlConncetion.setRequestProperty("Accept-Language", "da_DK");
httpUrlConncetion.setRequestProperty("Content-type", "application/json");
httpUrlConncetion.connect();
String line = "";
StringBuilder sb = new StringBuilder();
int Httpresult = httpUrlConncetion.getResponseCode();
Log.d(TAG, httpUrlConncetion.getResponseMessage().toString());
if (Httpresult == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpUrlConncetion.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
while ((line = reader.readLine()) != null) {
sb.append(line);
list.add(line);
}
result=sb.toString();
for(int i=0;i<list.size();i++){
Log.d(TAG, "min nye list" + list.get(i) + "\n");
}
and the Logcat says
it is ,"minegen":"n\u00f8gler"} that is the problem. it should have been the danish "nøgler".
The php has been set like this in the connection-file to the database:
"mysqli_set_charset($con, "utf8");
and the mysqli-database has been set to danish language - like this
And I do get danish characters in the table when checking in the table
So what am I missing??
Any help would be highly appreciated :)
I once run into a issue like this it was about saving emojis like you i had all charset set correctly but no matter what i did it didn't work so finaly i end up using urlencode($content) when saving into my database and urldecode($content) when retrieving data
I had a problem like this for Persian characters and I solved it by bad way which worked for me. I just defined my own encoding and made two functions FAtoEN(s) and ENtoFA(s). FAtoEN changes each Persian char to an English char using keyboard keys. for example changes "ن" to "k" because I use k key on keyboard when the keyboard is persian and I want to write ن. and also the other function do this inverse.
Related
Good day,
I have a php code that has a $_POST['Query'] function, i want to add it with $_POST['Tags'] but how can I pass 2 variables in android using to php, I had pass the a value to a $_POST['Query'] with my code but how can I pass the second one ?
OutputStream os = con.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("Query", "UTF-8")+"="+URLEncoder.encode(query,"UTF-8");
bw.write(data);
bw.flush();
con.connect();
bw.close();
os.close();
Simply append another parameter with &
String data = URLEncoder.encode("Query", "UTF-8")+"="+URLEncoder.encode(query,"UTF-8");
data+= "&"+URLEncoder.encode("Tags", "UTF-8")+"="+URLEncoder.encode(yourTags,"UTF-8");
Note : For efficiency use StringBuilder
StringBuilder params = new StringBuilder();
params.append(URLEncoder.encode("Query", "UTF-8")+"="+URLEncoder.encode(query,"UTF-8"));
params.append("&");
params.append(URLEncoder.encode("Tags", "UTF-8")+"="+URLEncoder.encode(yourTagStr,"UTF-8"));
bw.write(params.toString());
// ... code
I am fetching a string from my MySql DB on and online server using webservice in JSON format.
I am able to see that Android Studio is fetching it correctly as I see it in debugging mode.
But when I go ahead and add it to a List list, I get nothing.
Here's some more info:
What I am getting:
{"products":[{"veg_name_eng":"Corn","veg_name_hindi":"मक्का"}],"success":1}
My concern is with: "veg_name_hindi":"मक्का"
When I go ahead and try to put it in a dataitem list, I get nothing:
public static List<DataItem> dataItemList;
dataItemList.add(jsonObject.getString(veg_name_eng),jsonObject.getString(veg_name_hindi))
veg_name_eng and veg_name_hindi are the column names at my table.
After the above code I get dataItemList = null, So nothing is adding to it.
In my server side MySql DB, I am using UTF-8 encoding.
I am using android studio.
UPDATE 1:
I am parsing the JSON as :
JSONObject jsonObject = new JSONObject(myJSONString);
veg_list = jsonObject.getJSONArray("products");
try {
while (TRACK < veg_list.length()) {
JSONObject jsonObject = veg_list.getJSONObject(TRACK);
addItem(new DataItem(jsonObject.getString(veg_name_eng), jsonObject.getString(veg_name_hindi)));
TRACK = TRACK + 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
// and the addItem function is as follows:
private static void addItem(DataItem item) {
dataItemList.add(item); //While Debugging, I can see that value of item is correct. (i.e., item: DataItem{veg_name_eng='Cork', veg_name_hindi='मक्का'} )
dataItemMap.put(item.getVeg_id(), item);
}
Firstly, Make a model of the your JSON String using
http://json2java.azurewebsites.net/
and then map your JSON String to your Model using Gson. It's much easy to use.
Another way to get your required String for this particular result is parse json string yourself.
For Example :
String vegNameEng,vegNameHindi;
vegNameEng = vegNameHindi = "";
try{
JSONObject obj = new JSONObject(yourJsonString);
JSONArray arr = obj.getJSONArray("products");
vegNameEng = arr.getJSONObject(0).getString("veg_name_eng");
vegNameHindi = arr.getJSONObject(0).getString("veg_name_hindi");
}catch(JSONException ex){
}
Now vegNameEng and vegNameHindi have the required data.
I figured out, It was a silly mistake, the variable I was using to put data into the database was overwritten by some other variable with the same name. Closing the thread for now. Thanks #Umer-Farooq.
my Android application uploads string data to a PHP webservice. This usually works if I restrict myself to one single datum. However, I'm in a situation where I need to identify different datasets in my PHP script.
This is what I try:
URL url = new URL("....script.php") // This is my webservice
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequest("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream outputStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputSteramWriter(outputStream, "UTF-8"));
writer.write("datum1=" datum1json.toString());
writer.newLine();
writer.write("datum2=" datum2json.toString());
writer.close();
outputStream.close();
...
My PHP script begins like that
if(isset($_POST['datum1']) && isset($_POST['datum2'])) {
$json1 = json_encode($_POST['datum1']);
$json2 = json_encode($_POST['datum2']);
echo $json1;
echo $json2; }
As long as I append one single datum to my writer (writer.write("datum1=....) and only test for one incoming variable in the php, everything works fine. In my case, I get an EOFException
java.io.EOFException
at libcore.io.Streams.readAsciiLine(Streams.java:203)
at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:560)
...
I do not suspect the PHP file, since it works with one set.
How do I attach two different datasets with identifiers to a writer?
I tried writer.write("datum1=" datum1json.toString() + "datum2=" datum2json.toString()); too, but no success.
I know about different methods of POST requests (HttpDefaultClient,..) but I'm not too familiar with them and my requirements and data sizes are actually quite low.
Thank you!
Try this,
String datum1 = URLEncoder.encode(datum1json.toString(), "UTF-8");
String datum2 = URLEncoder.encode(datum2json.toString(), "UTF-8");
String params = "datum1=" + datum1 + "&" + "datum2=" + datum2;
BufferedWriter writer = new BufferedWriter( new OutputSteramWriter(outputStream, "UTF-8"));
writer.write(params);
writer.close();
outputStream.close();
Below is the code. The code works perfectly fine. It displays the content when both the EditText is left blank or has some string value that is available in the mysql database . My problem is that i want to display an error message when the input from the editText does not match with the JSON object or the returnString that store the result of the Mysql query after decoding JSON.
for eg if input='abi' //input from edittext
khasi:abirt //khasi is column from the database with value abirt
output : khasi abirt will be displayed
but i want an error to be displayed when input does not match at all with any of the words from the khasi column of the database instead of a blank page activity.
for eg : input='kljfldskfsldhf'
khasi column does not consist the input word
outout : blank page activity
String result;
String returnString;// to store the result of MySQL query after decoding JSON
String input;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_meaning);
Intent intent = getIntent();
intent.setClass(DisplayMeaningActivity.this, MainActivity.class);
input =intent.getStringExtra(MainActivity.MEANING_INPUT);
tv = (TextView) findViewById(R.id.textView1);
// declare parameters that are passed to PHP script i.e. the name "meaning" and its value submitted by user
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://kffg.netii.net/konnect.php?name="+input, // your ip address if using localhost server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
//parse json data
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")+
", Khasi: "+json_data.getString("Khasi")+
", English: "+json_data.getString("English")
);
//Get an output to the screen
returnString += "\n\n" + "Kyntien : " + json_data.getString("Khasi") + "\n"+ "Meaning: " + "\n"+ "" + json_data.getString("English");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
need to use an if loop with stringValue.contains("editTextvalue") condition.
It'l be like:
if (inputString.contains(columnNames)) {
//yes
} else {
//no, then print error
}
Since you already have your "result" in String, that shouldn't be a problem (?) .
Did not exactly understand the columns of the database issue but for the khasi column of your database, you can make an arrayList of of names and compare the string with a for each loop.
for(String string: columnNames){
if(input.equals(name)){}
}
Maintain an arrayList where you add string for each time you get data for khasi like:
arrayList.add(json_data.getString("Khasi"));
I want to get some text from a PHP page into an Android application. As long as the characters are ASCII (up to 128) there's no problem but when I want to display special characters like 'Ţ', 'Â' (the so called Latin-1 Supplement and/or Latin Extended-A - see it at Unicode Chart)
I get weird symbols into my Android application (�).
The problem is that my Android application cannot handle characters from Latin-1 Supplement (which PHP can) but characters from the Latin Extended-A charset (which PHP cannot). I don't know what common charset for both languages to use because the one that Java is able to read PHP is not, and vice versa.
My Java function that gets the content of the PHP page is this:
public static String GetData() {
byte[] Bresult = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mypage.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("var", "val"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
Bresult = EntityUtils.toByteArray(response.getEntity());
Result = new String(Bresult, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
Log.w("MYAPP", "Unsupported Encoding Exception (" + e.getMessage() + ")");
} catch (Exception e) {
Log.w("MYAPP", "Exception (" + e.getMessage() + ") ocurred");
}
return Result;
}
So, this code gives me the content of the script.php page. If the characters of the text received are from 0 to 128 there is no problem. Elsewhere, I get weird characters.
Now, this is my PHP code:
<?php
header("Content-Type: text/plain;charset=utf-8");
echo "ÂŞÂĂĒ";
?>
I also have a C++ application and it does read the text correctly. I have been trying a lot of methods all the day and I just don't get it. Who, where, why?
Thanks.
where are you getting the data?, if is through a mysql database you must specify UTF8 like this
mysql_query("SET NAMES 'utf8'");