2012-11-26 89 views
3

這是我的Java文件。我試圖發送阿拉伯文字不工作,而不是阿拉伯文字我得到???? ????? ?????從android到json到mysql阿拉伯語

我可以從MySQL讀取阿拉伯語,但我無法將阿拉伯語添加到MySQL。

public class NewSecret extends Activity { 

// Progress Dialog 
private ProgressDialog pDialog; 

JSONParser jsonParser = new JSONParser(); 
EditText inputName; 
EditText inputDesc; 

// url to create new product 
private static String url_create_product = "http://laylakaylif.com/android/add_secrets.php"; 

// JSON Node names 
private static final String TAG_SUCCESS = "success"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // fullScreen 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 

    setContentView(R.layout.add); 

    // Edit Text 
    inputName = (EditText) findViewById(R.id.inputName); 
    inputDesc = (EditText) findViewById(R.id.inputDesc); 

    LinearLayout ll = (LinearLayout) findViewById(R.id.Lina); 

    AdView ad2 = new AdView(NewSecret.this, AdSize.SMART_BANNER, 
      "a150b0de6e44a18"); 
    ll.addView(ad2); 
    ad2.loadAd(new AdRequest()); 

    // Create button 
    Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct); 

    if (inputName.getText().toString().length() <= 0) 
     inputName.setError("الرجاء اضافة عنوان!"); 

    if (inputDesc.getText().toString().length() <= 10) 
     inputDesc.setError("الرجاء اضافة نص السر .."); 

    // button click event 
    btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      // creating new product in background thread 
      new CreateNewProduct().execute(); 
     } 
    }); 
} 

/** 
* Background Async Task to Create new product 
* */ 
class CreateNewProduct extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(NewSecret.this); 
     pDialog.setMessage("إضافة سر جديد ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    /** 
    * Creating product 
    * */ 
    protected String doInBackground(String... args) { 
     String title = inputName.getText().toString(); 
     String description = inputDesc.getText().toString(); 

     String htmltitle; 
     String deshtml; 

     htmltitle = TextUtils.htmlEncode(title); 
     deshtml = TextUtils.htmlEncode(description); 

     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("title", htmltitle)); 
     params.add(new BasicNameValuePair("description", deshtml)); 

     // getting JSON Object 
     // Note that create product url accepts POST method 
     JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
       "POST", params); 

     // check log cat fro response 
     Log.d("Create Response", json.toString()); 

     // check for success tag 
     try { 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // successfully created product 
       Intent i = new Intent(getApplicationContext(), 
         AllSecrets.class); 
       startActivity(i); 

       // closing this screen 
       finish(); 
      } else { 
       // failed to create product 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog once done 
     pDialog.dismiss(); 
    } 

} 
} 

這是我的PHP JSON文件:

<?php 
header("Content-Type:application/json;charset=utf-8"); //global encoding since this is the config file -- for Arabic support 
/* 
* Following code will create a new product row 
* All product details are read from HTTP Post Request 
*/ 

// array for JSON response 
$response = array(); 

// check for required fields 
/*if (isset($_POST['title']) && isset($_POST['description'])) { 

    $title = json_encode($_POST['title'], JSON_UNESCAPED_UNICODE); 
    $description = json_encode($_POST['description'], JSON_UNESCAPED_UNICODE); 
*/ 

if (isset($_REQUEST['title']) && isset($_REQUEST['description'])) { 
    echo $_REQUEST['title'].'<br/>'; 
/* 
    $title = json_decode($__REQUEST['title']); 
    $description = json_decode($__REQUEST['description']); 
*/ 

    $title = $_REQUEST['title']; 
    $description = $_REQUEST['description']; 

    // include db connect class 
    require_once 'db_connect.php'; 

    // connecting to db 
    $db = new DB_CONNECT(); 

    //setting the connection charset 
    mysql_set_charset('utf8',$db); 
    mysql_query("SET NAMES 'utf8'"); 
    mysql_query("SET CHARACTER_SET utf8;"); 


    // mysql inserting a new row 
    mysql_query("SET NAMES 'UTF8'"); 
    $result = mysql_query("INSERT INTO secrets(title , description) VALUES('$title', '$description')"); 

    // check if row inserted or not 
    if ($result) { 
     // successfully inserted into database 
     $response["success"] = 1; 
     $response["message"] = "Secret successfully added."; 

     // echoing JSON response 
     echo json_encode($response); 
    } else { 
     // failed to insert row 
     $response["success"] = 0; 
     $response["message"] = "Oops! An error occurred."; 

     // echoing JSON response 
     echo json_encode($response); 
    } 
} else { 
    // required field is missing 
    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 

    // echoing JSON response 
    echo json_encode($response); 
} 
?> 

JSONParser代碼:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET method 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      }   

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 
+0

什麼是JSONParser? – njzk2

回答

2
JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params); 

我不知道JSONParser你使用的是什麼。它不是標準平臺的一部分;有幾十個不同類別的散落約與該名稱的網站,其中有許多包括如下一行:

httpPost.setEntity(new UrlEncodedFormEntity(params)); 

這是一個問題,因爲default編碼爲UrlEncodedFormEntity是ISO-8859-1和UTF-不8。如果你想通過UTF-8,include它作爲一個參數:

httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); 

如果這不是問題,建議張貼的JSONParser代碼。

+0

感謝您的幫助.. 我包括上面的JSONParser .. .. –

+0

我想我得到了什麼錯誤.. //我必須發送POST httpPost.setEntity(new UrlEncodedFormEntity(params,「UTF- 8" ));不只是httpPost.setEntity(新的UrlEncodedFormEntity(params)); –

+0

現在確定阿拉伯字符傳遞給MySQL,但我從 目錄下載這個錯誤 11-26 18:49:45.219:E/JSON解析器(28867):錯誤的數據進行解析org.json.JSONException:值I»I» - java.lang.String類型的字符串不能轉換爲JSONObject 並且應用程序崩潰。 –

2

如何尋找解決發佈非拉丁字符內的問題(阿拉伯語或其他),在你的PHP頁面使用此命令:

header('Content-Type: text/html; charset=utf-8'); 

mysql_query("SET NAMES 'utf8'"); 

mysql_query("CHARACTER SET utf8 COLLATE utf8_general_ci"); 

而且可以肯定,你必須在你的httpeEntity使用UTF,而且你MySQL的DATABSE必須使用UTF-8

我希望這個報價爲誰找同一問題的一些信息進行編碼

0

只是把整理utf8_general_ci