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'");
Related
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();
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.
i have to download a demo apk. I am inserting some values in database using php. but at some point of time it is throwing an error
org.json.JSONException: Value at validity_days of type java.lang.String cannot be converted to int
the code snippet in java:
private void upgradeVersion(String apkPath) {
System.out.println("SDCARD path checked5:-"+apkPath);
if(saveUserInfo()==true)
{
System.out.println("validity...."+validity);
if (apkPath != null) {
progressDialog.dismiss();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(apkPath)),
"application/vnd.android.package-archive");
intent.putExtra("validity_days", validity);
startActivityForResult(intent, 1);
Toast.makeText(getApplicationContext(),"NetVidya ebook app has been successfully installed.", Toast.LENGTH_LONG).show();
}
}
and the php response:
{"users":[{"status":"added","installeddate":"","active":"Y","validity_days":""}]}
which im getting null here thats y throwing error.
is it possible to handle that exception in android itself? or i have to make some changes in php.
please suggest
Without seeing your JSON parser I'm assuing the issue is becuase you need to use validity_days and that string, at least some of the time, may have no value.
try{
JSONObject fullString = new JSONObject(thatLongStringYouPosted);
JSONArray users = fullString.getJSONObject("users");
String validity_days = users.getJSONObject(0),getString("validity_days");
if(!validity_days.isEmpty() && validity_days != null)
//do whatever you want with it
}
} catch (JSONException e){
Log.e(TAG, e.toString());
}
When parsing JSON you will get back a null value only if what you are looking for does not exist - i.e. there is no "validity_days" string in the response. Otherwise you will just get an empty string. Simply checking for the null and/or the empty string should fix your problem.
Also the try catch block will handle this excpetion within the android code. You can modify your PHP if you want to ensure you always get back a specific value if empty (e.g. you may want to always reuturn a 0 instead of nothing when a field is blank).
According to the Exception you placed above, I think you are getting Exception at this line:
startActivityForResult(intent, 1);
Just replace this line with
startActivity(intent);
and get JSONString in other activity as
Intent i = getIntent();
String str = i.getStringExtra("validity_days");
Why don't you parse your variable validity_days to integer before it throws exception..
I am writing a php program to write a binary file (may be video or image files). I would like to make it as a web service and call it from another application like c#, mac etc.
My code is give below,
<?php
$fileChunk = $_POST["filechunk"];
$vodFolder = 'D:\\HYSA SVN\\Trunk\\workproducts\\source\\hysa_he\\web\\entertainment\\';
$vodFile = $vodFolder . "abcd.mov";
$fh = fopen($vodFile, 'ab');
flock ($fh, LOCK_EX);
$varsize = fwrite($fh, $fileChunk);
fclose($fh);
?>
But when I called the php web service from a c# code, the abcd.mov is creating in the location, but its size is only one kb. I suspects that, the writing in halted when a character ‘&’ found in the binary file. I read the php documentation and found that, fopen with binary mode ‘b’ will solve this issue? But it is not working. Can somebody help me ?
This is my c# code.
BinaryReader b = new BinaryReader(File.Open("d:\\image38kb.jpg", FileMode.Open));
int pos = 0;
int length = (int)b.BaseStream.Length;
byte[] bt = b.ReadBytes(length);
char[] ch = b.ReadChars(length);
HttpWebRequest request = null;
Uri uri = new Uri("http://d0327/streamtest.php");
request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential obj = new NetworkCredential("shihab.kb",
"India456*", "tvm");
request.Proxy.Credentials = obj;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bt.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes("filechunk=");
byte[] rv = new byte[bytes.Length + bt.Length];
System.Buffer.BlockCopy(bytes, 0, rv, 0, bytes.Length);
System.Buffer.BlockCopy(bt, 0, rv, bytes.Length, bt.Length);
writeStream.Write(rv, 0, bt.Length);
}
string result = string.Empty;
using (
HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
Well the problem is not in the fwrite part, that works fine.
However, POST requests in HTTP look like this:
POST /somepage.php HTTP/1.1
Content-Length: 34
variable1=blah&var2=something else
As you can see, variables are divided by ampersands (&) (as well as equal signs (=) for the key - value mapping)... So, even when using POST requests, ampersands are not safe characters.
To solve this, you could try another transfer method, for example, TCP/IP socket connection, or simply escape the ampersands with, say '\x26' (the ASCII value of ampersand) and escape all the backslashes (\) with '\x5C'... You'd have to edit the PHP code to parse these values.