2014-04-21 3 views
0

아래 클래스에서 내 안드로이드 앱에는 오류가 없습니다. 하지만 앱을 실행하고 등록을 클릭하면 아무 일도 일어나지 않습니다! JSON이 작동하지 않는 이유는 무엇입니까? 또한 내 PHP는 잘 작동합니다. 문제 없어!Android에서 JSON을 사용하여 PHP에서 데이터 가져 오기

나는 전체 PHP 스크립트를 보여 주지만, 웹 브라우저에서 찾아 볼 때 오류가 전혀없고, 완벽하게 작동한다는 것을 걱정하지 않습니다. 단일 데이터 행이있는 작은 json 배열이 있습니다. $ stringp는 할당 된 문자열 변수입니다.

Android의 아래 JSON 코드에 문제가 있습니다. 아래의 문제는 무엇입니까? 변경해야합니까?

PHP 코드 :

$a = array(
array('stringpval' => $stringp)); 
echo $json = json_encode($a); 

안드로이드 코드 :

public class MainActivity extends Activity { 

EditText etID; 
TextView result1; 
Button registerB; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.login); 
    registerB = (Button) findViewById(R.id.registerB); 
    etID = (EditText) findViewById(R.id.etID); 
    result1 = (TextView) findViewById(R.id.result); 


    registerB.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 

      // TODO Auto-generated method stub 

      Toast.makeText(getBaseContext(),"Please Wait...",Toast.LENGTH_SHORT).show(); 
      BEGIN_JSON();   
} 

     } 
    ); 

}

그리고 코드는 계속 ...

public void BEGIN_JSON(){ 

    Thread timer = new Thread(){ 

    public void run(){ 
    try{ 

     sleep(1000); 
    } 
    catch(InterruptedException e){ 
     e.printStackTrace(); 
    }finally{ 
     SEND_DATA(); 
    } 
    } 
    }; 
     timer.start(); 
} 

public void SEND_DATA(){ 
    String msg; 
    msg = etID.getText().toString(); 
    try{ 
     HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://myfile.php"); 

      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("tablenamep", msg)); 


      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

      httpclient.execute(httppost); 


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

public void CONNECT_JSON2(){ 


    HttpClient httpclient = new DefaultHttpClient(); 

    // Prepare a request object 
    HttpGet httpget = new HttpGet("http://myfile.php"); 

    // Execute the request 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httpget); 


     // Get hold of the response entity 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
      InputStream instream = entity.getContent(); 
      String result= convertStreamToString(instream); 

      JSONArray arr = new JSONArray(result); 
      JSONObject jObj = arr.getJSONObject(0); 
      String myoutput = jObj.getString("stringpval"); 
      result1.setText("myoutput");         
      instream.close(); 

     } 


    } catch (Exception e) { 
     Log.e("Error",e.toString()); 
    } 
} 

private static String convertStreamToString(InputStream is) { 
    /* 
    * To convert the InputStream to String we use the BufferedReader.readLine() 
    * method. We iterate until the BufferedReader return null which means 
    * there's no more data to read. Each line will appended to a StringBuilder 
    * and returned as String. 
    */ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 
+0

는'AsyncTask' –

+0

괜찮아 내 PHP 코드인가? 그리고 "jsonobject.getString ("stringpval ")"을 사용하여 $ stringp 값을 주시겠습니까 ??? – Ishak

답변

0

혹시 사용해 본 적이 비동기 작업에 웹 서비스 오페라 수행 배경 기 : 당신에 대해 읽어야

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 

public class AsyncExample extends Activity{ 


private String url="http://www.google.co.in"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    new AsyncCaller().execute(); 
} 


private class AsyncCaller extends AsyncTask<Void, Void, Void> 
{ 
    ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this); 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     //this method will be running on UI thread 
     pdLoading.setMessage("Loading..."); 
     pdLoading.show(); 
    } 
    @Override 
    protected Void doInBackground(Void... params) { 

     //this method will be running on background thread so don't update UI frome here 
     //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here 


     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 

     //this method will be running on UI thread 

     pdLoading.dismiss(); 
    } 

    } 
} 
+0

감사합니다. 나는 그것을 시도해라! – Ishak

+0

비동기 작업을 시도했습니다. 잘 작동합니다. On Post Execute 메서드의 UI 요소도 업데이트했습니다. 하지만 이제 JSON String을 얻었을 때 Text View에서 "result1"이 비어 있습니다. JSON에는 몇 가지 문제가 있다고 생각합니다. 위의 JSON 코드에 문제가 있는지 알려주세요. – Ishak

+0

@ user3522805, 프로그램을 디버그하거나 Log.i를 사용하여 어떤 응답을 얻으려고 시도하십시오. 감사 –

관련 문제