在Android中使用JSON从PHP获取数据

时间:2014-04-21 08:13:47

标签: php android json

在BELOW类中,我的Android应用程序中没有错误。但是,当我运行应用程序并单击注册时,没有任何反应!为什么JSON不工作?我的PHP工作正常。没问题!

我没有显示整个PHP脚本,但不要担心没有任何错误,并且从Web浏览器浏览时效果很好。我有一个带有单行数据的小型json数组。 $ stringp是一个分配的字符串变量。

Android中的以下JSON代码有问题。 问题如下?我需要做任何改变吗?

PHP代码:

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

Android代码:

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

1 个答案:

答案 0 :(得分:0)

您是否曾使用Async Task在后台执行Web服务操作:

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

    }
}