2014-06-25 34 views
1

我盡力搜索解決方案,但仍無法解決問題。請幫助。在這裏我的Java代碼: -JSONException:java.lang.String類型的值無法轉換爲JSONObject

public class MainActivity extends Activity { 

String project_id; 
String id; 
InputStream is=null; 
String result=null; 
String line=null; 
int code = 0; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final EditText e_id  =(EditText) findViewById(R.id.editText1); 
    final EditText e_prjId =(EditText) findViewById(R.id.editText2); 
    Button insert   =(Button) findViewById(R.id.button1); 

    id   = e_id.getText().toString(); 
    project_id = e_prjId.getText().toString(); 
    insert.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      insert(); 

     } 
    }); 
    } 

    public void insert() { 
    final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

    nameValuePairs.add(new BasicNameValuePair("id",id)); 
    nameValuePairs.add(new BasicNameValuePair("Project_Id",project_id)); 


    new Thread(new Runnable() { 
     public void run() { 
      try { 

       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost("http://192.168.0.111/insert.php"); 

       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       is = entity.getContent(); 
       Log.e("pass 1", "connection success "); 
      } 
      catch(Exception e){ 
       Log.e("Fail 1", e.toString()); 
       Toast.makeText(getApplicationContext(), "Invalid IP Address", 
       Toast.LENGTH_LONG).show(); 
      } 

      try { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
       StringBuilder sb = new StringBuilder(); 

       while ((line = reader.readLine()) != null){ 
        sb.append(line + "\n"); 
       } 

       is.close(); 
       result = sb.toString(); 
       Log.e("pass 2", "connection success "); 
      } 
      catch(Exception e){ 
       Log.e("Fail 2", e.toString()); 
      }  

      try { 
       Log.i("tagconvertstr", "["+result+"]"); 
       JSONObject json_data = new JSONObject(result); 
       code=(json_data.getInt("code")); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      }  

      if(code==1) 
      { 
       Toast.makeText(getBaseContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
       Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show(); 
      } 
     } 
    }).start(); 



} 

PHP: -

<?php 
$uname='root'; 
$pwd=''; 


$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd); 


$ID=$_REQUEST['ID']; 
$Project_Id=$_REQUEST['Project_Id']; 

$flag['code']=0; 

if($r= $con->query("insert into task(ID,Project_Id) values('$ID','$Project_Id')")) 
{ 
    $flag['code']=1; 
} 

echo(json_encode($flag)); 

?> 

我真的不知道什麼是我不斷收到來自JSON異常錯誤錯誤信息的原因。真的很感謝能幫助我。

感謝

+0

原因是:您試圖將一個html字符串轉換爲JSONObject。所以你的變量'result'最有可能是無效的json格式。 – dognose

+0

因此@ user3776060您是否在下面嘗試了我的答案? – meda

+0

Hi @ dognose,感謝您的評論,並且您正確。我可以知道如何讓結果返回有效的json格式值嗎? – user3776060

回答

0

小心,PHP關聯數組是區分大小寫的

您發送id

nameValuePairs.add(new BasicNameValuePair("id",id)); 

這不等於ID

除了這個錯誤,你不檢查你的PHP腳本中的數據,我爲你重寫了它:

$data = array(); 

if(isset($_POST['id'], $_POST['Project_Id']){ 
    $id=$_POST['id']; 
    $project_id=$_POST['Project_Id']; 

    $uname='root'; 
    $pwd=''; 
    $con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd); 
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $stmt = $con->prepare('INSERT INTO task (`ID`, `Project_Id`) values(:id, :project_id)')) 
    $success = $stmt->execute(array(':id'=>$id, ':project_id'=>$project_id)); 

    if($success){ 
     $data['code'] = 1; 
     $data['msg'] = 'INSERT successful'; 
    }else{ 
     $data['code'] = 0; 
     $data['msg'] = 'INSERT Failed'; 
    } 


}else{ 
    $data['code'] = 0; 
    $data['msg'] = 'values are not set'; 
} 

echo(json_encode($data)); 
+0

嗨@meda,你的代碼在我更改'$ success = $ con> execute(array(':id'=> $ id,':project_id'=> $ project_id))後很好地工作。 ('ID','Project_Id')values(:id,:project_id)'); \t \t $ success = $ st-> execute(array(':id'=> $ id,':project_id'=> $ project_id));'。 – user3776060

+0

嗨@meda,你的代碼在我改變了'$ success = $ con> execute(array(':id'=> $ id,':project_id'=> $ project_id))後很好地工作。 ('ID','Project_Id')values(:id,:project_id)'); $ success = $ st-> execute(array(':id'=> $ id,':project_id'=> $ project_id));'。當我設法得到返回結果** [{「code」:1,「msg」:「INSERT successful」}。但是我面臨一個新的問題,它聲明**不能在線程內創建沒有調用Looper.prepare()**的處理程序。有任何建議嗎? – user3776060

+0

@ user3776060這是因爲您試圖在正在運行的線程中顯示敬酒,它應該位於主線程(UI)上,但我建議您使用asyntask作爲高級解決方案 – meda

相關問題