Как получить смайлики из базы данных MySQL с помощью PHP в Android

Я могу отправить Unicode Emoji, но застрял для получения Unicode из PHP API.

Здесь я получил ответ в объекте JsonArray, так как сейчас я просто тестирую цель, я просто JsonArray, потому что мне это нужно и в будущем.

["\ud83dde00"]

Теперь в Android, как получить это не знаю и отображать в EmojiTextView. Я использую этот пример, чтобы использовать Emoji в TextView и EditText https://github.com/pepibumur/emojize

Вот мой Java-код, я создаю API для отправки юникода и получаю в качестве ответа, сохраняю в БД, работает отлично, просто немного застрял здесь.

new AsyncTask<Void, Void, Object>() {
ProgressDialog pDialog;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(MainActivity.this, "", "please wait");
}
@Override
protected Object doInBackground(Void... params) {
try {
String contents;

HttpPost request = new HttpPost("http://172.16.16.44/test/save_emoji.php");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("addEmoji", s+""));
request.setEntity(new UrlEncodedFormEntity(param,"UTF-8"));

DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
response.setHeader("Content-Type", "application/json; charset=utf-8");
InputStream is = response.getEntity().getContent();
InputStreamReader(is));

byte[] buffer = new byte[1024];
int nread;
while ((nread = is.read(buffer)) > 0) {
baos.write(buffer, 0, nread);
}
is.close();
response = null;
is = null;
client = null;
return parseJson();

}catch (JSONException e) {
e.printStackTrace();
try {
return new String(baos.toByteArray(), "UTF-16");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return e1.getMessage();
}
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}

@SuppressLint("NewApi")
private String parseJson() throws JSONException, UnsupportedEncodingException {
String jsonText = new String(baos.toByteArray());
Log.e("emoji", "resp "+jsonText);
JSONArray jarr = new JSONArray(jsonText);
for(int i=0;i<jarr.length();i++){
Log.e("emoji", new String(jarr.get(i).toString().getBytes(),"UTF-8"));
return jarr.getString(i);
}
return "";
}

protected void onPostExecute(final Object result) {
super.onPostExecute(result);
if(pDialog!=null)
pDialog.dismiss();

MainActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
try {
Log.e("emoji", "ss "+result);
mTxtEmojicon.setText(new String(result.toString().getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}

});}

}.execute();

Спасибо

2

Решение

У меня есть решение, оно просто идет за счет написания кода вместо использования кодировки Json.

Код PHP

$dbLink = mysql_connect(HOSTNAME, USERNAME, PASSWORD)or die(mysql_error());
mysql_select_db(DATABASE, $dbLink)or die(mysql_error());

mysql_query("SET character_set_client=utf8mb4", $dbLink);
mysql_query("SET character_set_connection=utf8mb4", $dbLink);
mysql_query("SET character_set_results=utf8mb4", $dbLink);

$sql_query = "SELECT * FROM emoji";
$dbResult = mysql_query( $sql_query, $dbLink)or die(mysql_error());
$jason = "[";
$addcoma  = "";
while($rw=mysql_fetch_array($dbResult))
{
$jason .= $addcoma . ' {"message" : "'.$rw["message"].'"}';
$addcoma = ",";
}

$jason .= "]";
echo $jason;

Подготовьте объект Json с помощью жесткого кода, и вы получите желаемый результат.

2

Другие решения

выберите данные и просто json_decode строки, вы получите смайлики как есть.

    json_decode($text) // $text contains the text with emoji
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector