2016-09-23 113 views
5

我尝试开发一个Android应用程序,该应用程序可以使用JSON解析器向Web主机注册配置文件。我成功创建了登录功能。但是,我收到这条错误消息,指出数据库中的返回对象不是JSON对象。我认为我的PHP文件是问题。java.lang.String无法从Android转换为JSONObject

每当我尝试运行该应用程序,然后单击按钮,它将显示配置文件已存在。我试过与其他帖子比较,但它没有真正解决我的问题。

这是我的register.java。 package com.teradata.sb186103.cbet;

import android.content.Intent; 
import android.os.Bundle; 
import android.os.StrictMode; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.Toast; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.List; 

public class RegisterActivity extends AppCompatActivity { 

private JSONParser jsonParser; 
private static String KEY_SUCCESS = "success"; 
String id; 
private EditText consName; 
private EditText consEmail; 
private EditText password; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_register); 


    consName = (EditText) findViewById(R.id.ETusername); 
    consEmail = (EditText) findViewById(R.id.ETemail); 
    password = (EditText) findViewById(R.id.ETpassword); 

} 

public void Register(View v) { 
    try { 

     String username = consName.getText().toString(); 
     String email = consEmail.getText().toString(); 
     String pass = password.getText().toString(); 

     //CHECK IF PROFILE ALREADY EXIST 
     Boolean exist = CheckProfile(username, email, pass); 
     if(exist==true){ 
      Toast.makeText(getApplicationContext(), "PROFILE ALREADY EXIST!", Toast.LENGTH_SHORT).show(); 
      return; 
     } 

     Boolean register = RegisterProfile(id, username, email, pass); 
     if(register==true){ 
      Toast.makeText(getApplicationContext(), "PROFILE HAS BEEN UPDATED", Toast.LENGTH_SHORT).show(); 

      Intent intent = new Intent(v.getContext(), ViewProfileActivity.class); 
      startActivity(intent); 
     } 


    } catch (Exception e) { 
     e.printStackTrace(); 
    } 


} 

/* public void Cancel(View v) { 

    Intent intent = new Intent(v.getContext(), MenuActivity.class); 
    startActivity(intent); 

    }*/ 

    public boolean CheckProfile(String consEmail, String consName, String password) throws Exception{ 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

    String URL = JSONParser.serverURL; 
    String tag = "CheckProfile"; 

    jsonParser = new JSONParser(); 
    List<NameValuePair> params = new ArrayList<NameValuePair>(); 

    String value = consEmail + "<@>" + consName + "<@>" + password; 
    params.add(new BasicNameValuePair("tag", tag)); 
    params.add(new BasicNameValuePair("value", value)); 

    JSONObject json = jsonParser.getJSONFromUrl(URL, params); 

    if (json != null && json.getString(KEY_SUCCESS) != null){ 
     return true; 
    }else return false; 



} 

public boolean RegisterProfile(String id, String consName, String consEmail, String password) throws Exception{ 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

    String URL = JSONParser.serverURL; 
    String tag = "RegisterProfile"; 

    jsonParser = new JSONParser(); 
    List<NameValuePair> params = new ArrayList<NameValuePair>(); 

    String value = id + "<@>" + consName + "<@>" + consEmail + "<@>" + password; 
    params.add(new BasicNameValuePair("tag", tag)); 
    params.add(new BasicNameValuePair("value", value)); 

    JSONObject json = jsonParser.getJSONFromUrl(URL, params); 

    String res = json.getString(KEY_SUCCESS); 
    if (Integer.parseInt(res) == 1){ 
     return true; 
    } 
    else { 
     return false; 
    } 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
    } 
} 

这是我的index.php 用于register.java的部分是//检查档案,并//注册资料

<?php 

    require_once ('database.php'); 
    date_default_timezone_set('Asia/Kuala_Lumpur'); 

    if (isset($_POST['tag']) && $_POST['tag'] != '') { 

$tag = $_POST['tag']; 
$response = array("tag" => $tag, "success" => 0); 

//LOGIN 
if ($tag == 'consumerLogin') { 
    $value = $_POST['value']; 
    $array = explode("<@>", $value); 
    $consEmail = $array[0]; 
    $password = $array[1]; 

    $query = "select * from consumer where consEmail='$consEmail' and password='$password'";  
    $result = mysql_query($query); 
    $row = mysql_fetch_array($result); 
    if($row[0] != null) 
     $response["success"] = 1; 
    else 
     $response["success"] = 0; 
    echo json_encode($response); 
    return;   

} 

//GET ROW ID 
else if ($tag == 'getID') { 
    $value = $_POST['value']; 
    $array = explode("<@>", $value); 
    $table = $array[0]; 
    $column = $array[1]; 
    $val = $array[2];  

    $query = "select id from $table where $column = '$val'";  
    $result = mysql_query($query); 
    $row = mysql_fetch_array($result); 
    if($row[0] != null) { 
     $response["value"] = $row[0]; 
     $response["success"] = 1; 
    } 
    else { 
     $response["success"] = 0; 
    } 
    echo json_encode($response); 
    return;   

} 


//CHECK PROFILE 
else if ($tag == 'CheckProfile') { 
    $value = $_POST['value']; 
    $array = explode("<@>", $value); 
    $id= $array[0]; 
    $consName = $array[1]; 
    $consEmail = $array[2]; 
    $password = $array[3];     


    $query = "select * from consumer where consName=$consName and consEmail='$consEmail' and password=$password" and id <> $id"; 
    $result = mysql_query($query); 
    $row = mysql_fetch_array($result); 
    $found=false; 
    if($row[0]!=null) 
     $found=true; 

    if($found==true) {   
     $response["success"] = 1; 
    } 
    else { 
     $response["success"] = 0; 
    } 

    echo json_encode($response); 
    return;  

} 

//REGISTER PROFILE 
else if ($tag == 'RegisterProfile') { 
    $value = $_POST['value']; 
    $array = explode("<@>", $value); 
    $id= $array[0]; 
    $consName = $array[1]; 
    $consEmail = $array[2]; 
    $password = $array[3];     



    $query = "insert into consumer values(null,$consName,$consEmail,'$password')"; 
    $result = mysql_query($query); 

    $response["success"] = 1;      
    echo json_encode($response); 
    return;  

} 

else { 
    echo "Error Message: Invalid Request";  
    } 
} 
else { 
    echo "Error Message: Anynomous Access Denied"; 

} 



?> 

这是我JSONParser

package com.teradata.sb186103.cbet; 



    import java.io.IOException; 
    import android.util.Log; 
    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.HttpPost; 



    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.json.JSONException; 
    import org.json.JSONObject; 

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

    public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 
static String serverURL = "http://tdcbet.******/index.php"; 

public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { 


    try { 

     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(); 

    } 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(); 
     Log.e("JSON", json); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 


    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 


    return jObj; 



    } 
} 

logcat

09-23 07:32:04.923 4311-4311/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject 
    09-23 07:32:06.935 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4055100 
    09-23 07:32:08.580 4311-4311/com.teradata.sb186103.cbet E/JSON: <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><font face='Arial' size='1' color='#000000'> 
     <b>PHP Error Message</b></font></td></tr></table><br /><b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>/home/a6410240/public_html/index.php</b> on line 
     <b>65</b><br /><br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><div align='center'> 
     <a href='http://www.000webhost.com/'><font face='Arial' size='1' color='#000000'>Free Web Hosting</font></a></div></td></tr> 
    </table>{"tag":"CheckProfile","success":0}<!-- Hosting24 Analytics Code --> 
     <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script><!-- End Of Analytics Code --> 
    09-23 07:32:08.580 4311-4311/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject 
    09-23 07:32:10.586 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4055170 
    09-23 07:32:12.177 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa2d182a0 
    09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject 
    09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference 
09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:  at com.teradata.sb186103.cbet.RegisterActivity.RegisterProfile(RegisterActivity.java:120) 
09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:  at com.teradata.sb186103.cbet.RegisterActivity.Register(RegisterActivity.java:57) 
09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:  at java.lang.reflect.Method.invoke(Native Method) 
09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:  at android.view.View.performClick(View.java:5198) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at android.view.View$PerformClick.run(View.java:21147) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at android.os.Handler.handleCallback(Handler.java:739) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at android.os.Handler.dispatchMessage(Handler.java:95) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at android.os.Looper.loop(Looper.java:148) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at android.app.ActivityThread.main(ActivityThread.java:5417) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at java.lang.reflect.Method.invoke(Native Method) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet I/Choreographer: Skipped 71 frames! The application may be doing too much work on its main thread. 
09-26 01:37:11.337 2906-2912/com.teradata.sb186103.cbet W/art: Suspending all threads took: 13.723ms 

this is my database table

+0

什么是生成JSON? –

+0

显示你的JSON响应 – Aspicas

+0

我已经粘贴了我的JSON解析器文件@Aspicas – gpsrosak

回答

0

在你有以下几行你PHP代码,

else { 
    echo "Error Message: Invalid Request";  
    } 
} 
else { 
    echo "Error Message: Anynomous Access Denied"; 
} 
echo "masuk"; 

万一发生了一些错误的代码会被工作。

您正试图在您的Android代码中将此String解析为JSONObject

编辑

CheckProfile情况下,你必须在value变量3倍的值。

String value = consEmail + "<@>" + consName + "<@>" + password; 

在您的PHP中,您取4个值。在索引3处没有任何值。您还没有通过id变量。

$value = $_POST['value']; 
$array = explode("<@>", $value); 
$id= $array[0]; 
$consName = $array[1]; 
$consEmail = $array[2]; 
$password = $array[3];     

在PHP为CheckProfile试试这个,

$consEmail= $array[0]; 
$consName = $array[1]; 
$password = $array[2]; 

$query = "select * from consumer where consEmail='$consEmail'"; 
+0

是的,为什么会出现错误,似乎我的PHP和SQL查询注册前有问题,我不知道在哪里修复。 @ k-neeraj-lal – gpsrosak

+0

提出错误的条件是? –

+0

在我的php文件中(//检查配置文件&//注册配置文件@ k-neeraj-lal – gpsrosak

相关问题