2014-05-01 4 views
-2

Android 개발을 처음 사용합니다. 안드로이드에서 JSON 데이터를 PHP 서버로 보냅니다.JSON을 구문 분석하는 동안 오류가 발생했습니다.

MainActivity.java

public class MainActivity extends Activity implements OnClickListener { 
     FlyOutContainer root; 
     private static final String TAG_POSTS = "posts"; 

     String sideMenu[] = { "Place New Report", "My Reports", "Short By", 
       "Water", "Road", "Electricity", "Construstion", 
       "Waste Disposal and Electricity", "Nearby Reports", "Others", 
       "Settings" }; 
     FlyOutContainer fly; 
    int l; 
    JSONArray mComments = null; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        WindowManager.LayoutParams.FLAG_FULLSCREEN); 

      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 

      l=1; 
      final String READ_COMMENTS_URL = "http://sanoawaz.orgfree.com/comments2.php"; 
      JSONParser jParser = new JSONParser(); 
      Log.d("good", "tillhere2"); 
      JSONObject jsoni = jParser.getJSONFromUrl(READ_COMMENTS_URL); 
      Log.d("good", "tillhere3"); 
      try { 
       mComments = jsoni.getJSONArray(TAG_POSTS); 
       l = mComments.length(); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       l = 10; 
      } 

JSONParser.java

package com.sdmple.flybar; 
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() { 

    } 


    public JSONObject getJSONFromUrl(final String url) { 

     // Making HTTP request 
     try { 
      // Construct the client and the HTTP request. 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      // Execute the POST request and store the response locally. 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      // Extract data from the response. 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      // Open an inputStream with the data content. 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     try { 
      // Create a BufferedReader to parse through the inputStream. 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      // Declare a string builder to help with the parsing. 
      StringBuilder sb = new StringBuilder(); 
      // Declare a string to store the JSON object data in string form. 
      String line = null; 

      // Build the string until null. 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
       json = sb.toString().substring(0, sb.toString().length() - 1); 
      } 

      // Close the input stream. 
      is.close(); 
      // Convert the string builder data to an actual string. 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // Try to 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 the JSON Object. 
     return jObj; 

    } 


    // function get json from url 
    // by making HTTP POST or GET mehtod 
    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; 

    } 

    public JSONObject getJSONFromUrl2(final String url) { 

     // Making HTTP request 
     try { 
      // Construct the client and the HTTP request. 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      // Execute the POST request and store the response locally. 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      // Extract data from the response. 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      // Open an inputStream with the data content. 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     try { 
      // Create a BufferedReader to parse through the inputStream. 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      // Declare a string builder to help with the parsing. 
      StringBuilder sb = new StringBuilder(); 
      // Declare a string to store the JSON object data in string form. 
      String line = null; 

      // Build the string until null. 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 

      // Close the input stream. 
      is.close(); 
      // Convert the string builder data to an actual string. 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // Try to 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 the JSON Object. 
     return jObj; 

    } 


} 

임 점점 된 JSONObject jsoni = jParser.getJSONFromUrl (READ_COMMENTS_URL);

Comments2.php

<?php 


require("config2.inc.php"); 

//initial query 
$query = "Select * FROM posts"; 

//execute query 
try { 
    $stmt = $db->prepare($query); 
    $result = $stmt->execute(); 
} 
catch (PDOException $ex) { 
    $response["success"] = 0; 
    $response["message"] = "Database Error!"; 
    die(json_encode($response)); 
} 


$rows = $stmt->fetchAll(); 


if ($rows) { 
    $response["success"] = 1; 
    $response["message"] = "Post Available!"; 
    $response["posts"] = array(); 

    foreach ($rows as $row) { 
     $post    = array(); 
     $post["username"] = $row["username"]; 
     $post["location"] = $row["location"]; 
     $post["discreption"] = $row["discreption"]; 


     //update our repsonse JSON data 
     array_push($response["posts"], $post); 
    } 

    // echoing JSON response 
    echo json_encode($response); 


} else { 
    $response["success"] = 0; 
    $response["message"] = "No Post Available!"; 
    die(json_encode($response)); 
} 

?> 

로그 캣

05-01 07:15:01.859: D/Login Successful!(1531): {"message":"Login successful!","success":1} 
05-01 07:15:02.407: D/good(1531): tillhere2 
05-01 07:15:02.407: D/AndroidRuntime(1531): Shutting down VM 
05-01 07:15:02.407: W/dalvikvm(1531): threadid=1: thread exiting with uncaught exception (group=0xa4c46648) 
05-01 07:15:02.407: E/AndroidRuntime(1531): FATAL EXCEPTION: main 
05-01 07:15:02.407: E/AndroidRuntime(1531): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sdmple.flybar/com.sdmple.flybar.MainActivity}: android.os.NetworkOnMainThreadException 
응용 프로그램의 시도가 주 스레드에서 네트워킹 작업을 수행 할 때 주 thread.This 예외에서 네트워크 호출을 못할
+1

무엇이 문제입니까? – guptakvgaurav

+0

@ GauravGupta 방금 logcat을 추가했습니다. 한번 봐주세요. – user3258884

+0

가능한 중복 [android.os.NetworkOnMainThreadException] (http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – laalto

답변

1

가 발생합니다 . AsyncTask에서 코드를 실행하십시오.

+0

감사합니다 .. 나는 그것을 몰랐다. AsyncTask가 내 문제를 해결했습니다. – user3258884

관련 문제