2013-07-11 2 views
0

codeigniter에 PHP 서버에 연결하는 안드로이드 응용 프로그램 프로젝트가 있습니다.android에서 PHP 서버에 연결할 때 오류 발생

내 JSONparser는 다음 서버에 연결

package com.example.com.tourism; 

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; 

     } 
    } 

내 활동 자바 코드는

package com.example.com.tourism; 

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

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


import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 

public class SignUp extends Activity { 

    EditText first,last,birth ,pass; 
    private ProgressDialog pDialog; 
    private static String url_create_user = "http://10.0.2.2/tourism/index.php/site/register"; 
    JSONParser jsonParser = new JSONParser(); 
    private static final String TAG_SUCCESS = "success"; 
    @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.sign_up); 

      Button signUp=(Button)findViewById(R.id.sign_up); 

      first =(EditText) findViewById(R.id.edfname); 
      last =(EditText) findViewById(R.id.edlname); 
      pass =(EditText) findViewById(R.id.edpass); 
      signUp.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        new Createnewuser().execute(); 
       } 
      }); 

    } 

    class Createnewuser extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(SignUp.this); 
      pDialog.setMessage("Creating User.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Creating product 
     * */ 
     protected String doInBackground(String... args) { 
      String name = first.getText().toString(); 
      String price = last.getText().toString(); 
      String description = pass.getText().toString(); 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("first_name", name)); 
      params.add(new BasicNameValuePair("last_name", price)); 
      params.add(new BasicNameValuePair("password", description)); 

      // getting JSON Object 
      // Note that create product url accepts POST method 
      JSONObject json = jsonParser.makeHttpRequest(url_create_user, 
        "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(), MainActivity.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(); 
     } 


    } 

하고 로그 고양이에 오류가

07-07 11:30:44.159: E/JSON Parser(20514): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject 
07-07 11:30:44.189: W/dalvikvm(20514): threadid=11: thread exiting with uncaught exception (group=0x40a71930) 
07-07 11:30:44.229: E/AndroidRuntime(20514): FATAL EXCEPTION: AsyncTask #1 
07-07 11:30:44.229: E/AndroidRuntime(20514): java.lang.RuntimeException: An error occured while executing doInBackground() 
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$3.done(AsyncTask.java:299) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.lang.Thread.run(Thread.java:856) 
07-07 11:30:44.229: E/AndroidRuntime(20514): Caused by: java.lang.NullPointerException 
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:98) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:1) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$2.call(AsyncTask.java:287) 
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
07-07 11:30:44.229: E/AndroidRuntime(20514): ... 4 more 
07-07 11:30:44.429: I/Choreographer(20514): Skipped 49 frames! The application may be doing too much work on its main thread. 
07-07 11:30:44.779: I/Choreographer(20514): Skipped 222 frames! The application may be doing too much work on its main thread. 
07-07 11:30:45.069: I/Choreographer(20514): Skipped 149 frames! The application may be doing too much work on its main thread. 
07-07 11:30:45.369: I/Choreographer(20514): Skipped 194 frames! The application may be doing too much work on its main thread. 
07-07 11:30:45.459: I/Choreographer(20514): Skipped 50 frames! The application may be doing too much work on its main thread. 
07-07 11:30:46.019: E/WindowManager(20514): Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here 
07-07 11:30:46.019: E/WindowManager(20514): android.view.WindowLeaked: Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here 
07-07 11:30:46.019: E/WindowManager(20514):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.app.Dialog.show(Dialog.java:281) 
07-07 11:30:46.019: E/WindowManager(20514):  at com.example.com.tourism.SignUp$Createnewuser.onPreExecute(SignUp.java:75) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.os.AsyncTask.execute(AsyncTask.java:534) 
07-07 11:30:46.019: E/WindowManager(20514):  at com.example.com.tourism.SignUp$1.onClick(SignUp.java:57) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.view.View.performClick(View.java:4204) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.view.View$PerformClick.run(View.java:17355) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.os.Handler.handleCallback(Handler.java:725) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.os.Handler.dispatchMessage(Handler.java:92) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.os.Looper.loop(Looper.java:137) 
07-07 11:30:46.019: E/WindowManager(20514):  at android.app.ActivityThread.main(ActivityThread.java:5041) 
07-07 11:30:46.019: E/WindowManager(20514):  at java.lang.reflect.Method.invokeNative(Native Method) 
07-07 11:30:46.019: E/WindowManager(20514):  at java.lang.reflect.Method.invoke(Method.java:511) 
07-07 11:30:46.019: E/WindowManager(20514):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
07-07 11:30:46.019: E/WindowManager(20514):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
07-07 11:30:46.019: E/WindowManager(20514):  at dalvik.system.NativeStart.main(Native Method) 

내가 돈이다 ' 문제가있는 곳을 알지 못합니다. 제발 도와주세요 내 코드가 잘못되었습니다 ??? 중 하나가 올바른 코드 내가 PHP 용 CodeIgniter를 사용하고 내게주세요 있고이 나는 문제가 PHP에 있습니다

function register_get() 
    { 
     $json = array('status' => false); 
     if($this->input->post()==null){ 
      $this -> response($json, 200); 
      } 

     $firstname = $this->post("first_name"); 
     $lastname = $this->post("last_name"); 
     $password = $this->post("password"); 
     if(!$firstname || !$lastname || !$password){ 
      $json['status'] = "wrong insert"; 
      $this -> response($json, 200); 
     } 

     $this->load->model('Data_model'); 
     $result = $this->Data_model->search($firstname, $lastname); 

     if($result) 
     { 
      $this->Data_model->insert($firstname,$lastname,$password); 
      $json['status'] = true; 

     } 
     // here if false.. 
     $this -> response($json, 200); 
    } 

답변

0

위를 호출하는 코드 인 경우. JSON을 다시 전달하지 않습니다. 배열을 JSON으로 인코딩하려면 스크립트를 변경해야합니다. 도움이 될 것 실제 JSON을 반환

$result = json_encode($json)

. HTML을 반환하지 않았는지 확인하십시오. 귀하의 자바 JSON 응답을 구문 분석하려고하지만 <!DOCTYPE ...

+0

나는이 결과 $ result = json_encode ($ json); $ this -> response ($ result, 200); 여전히 작동하지 않고이 오류가 발생합니다. 데이터를 파싱하는 중 오류가 발생했습니다. org.json.JSONException : 값 user2026521

+0

여전히 HTML과 JSON을 반환해야합니다. 같은 것을 시도하십시오 'echo json_encode ($ json); exit;' – SteveEdson

+0

나는 REST_controller를 사용하기 때문에 json_encode를 쓸 필요가 없다. 다른 해결책이있다. – user2026521

관련 문제