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

在Android中使用JSON从PHP获取数据,php,android,json,Php,Android,Json,在下面的课程中,我的android应用程序中没有错误。但是当我运行应用程序并点击注册时,什么都没有发生!为什么JSON不起作用?此外,我的php工作良好。没问题 我还没有展示整个php脚本,但不用担心会出现任何错误,从web浏览器浏览时效果会很好。我有一个带有一行数据的小json数组$stringp是一个指定的字符串变量 Android中下面的JSON代码有问题。 下面的问题是什么?我需要做任何改变吗 PHP代码: $a = array( array('stringpval' => $st

在下面的课程中,我的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();
}
public void BEGIN_JSON(){
线程计时器=新线程(){
公开募捐{
试一试{
睡眠(1000);
}
捕捉(中断异常e){
e、 printStackTrace();
}最后{
发送_数据();
}
}
};
timer.start();
}
公共无效发送_数据(){
串味精;
msg=etID.getText().toString();
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://myfile.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“tablenamep”,msg));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}捕获(例外e){
e、 printStackTrace();
}最后{
CONNECT_JSON2();
}
}
公共void CONNECT_JSON2(){
HttpClient HttpClient=新的DefaultHttpClient();
//准备一个请求对象
HttpGet HttpGet=新的HttpGet(“http://myfile.php"); 
//执行请求
HttpResponse响应;
试一试{
response=httpclient.execute(httpget);
//获取响应实体
HttpEntity=response.getEntity();
如果(实体!=null){
InputStream instream=entity.getContent();
字符串结果=convertStreamToString(流内);
JSONArray arr=新JSONArray(结果);
JSONObject jObj=arr.getJSONObject(0);
字符串myoutput=jObj.getString(“stringpval”);
结果1.setText(“myoutput”);
流内关闭();
}
}捕获(例外e){
Log.e(“Error”,e.toString());
}
}
私有静态字符串convertStreamToString(InputStream为){
/*
*要将InputStream转换为字符串,我们使用BufferedReader.readLine()命令
*我们迭代直到BufferedReader返回null,这意味着
*没有更多的数据可读取。每行都将附加到StringBuilder
*并作为字符串返回。
*/
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}

您是否曾经使用异步任务在后台执行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();
    }

    }
}
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
公共类异步示例扩展活动{
专用字符串url=”http://www.google.co.in";
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
新建AsyncCaller().execute();
}
私有类AsyncCaller扩展了AsyncTask
{
ProgressDialog pdLoading=新建ProgressDialog(AsyncExample.this);
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//此方法将在UI线程上运行
setMessage(“正在加载…”);
pdLoading.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
//此方法将在后台线程上运行,因此不要在此处更新UI
//在这里执行长时间运行的http任务,您不想传递参数,您可以在这里访问父类的变量url
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
//此方法将在UI线程上运行
pdLoading.disclose();
}
}
}

您应该阅读关于
AsyncTask
我的PHP代码还好吗?使用“jsonobject.getString(“stringpval”)给我$stringp的值???谢谢!我要试试看!我尝试了异步任务。很好。我甚至更新了On-Post-Execute方法中的UI元素。但是现在,当我得到JSON字符串时,我的文本视图“result1”是空的。我认为JSON中存在一些问题。请告诉我上面的JSON代码是否有问题@用户3522805,请尝试调试程序或使用Log.i查看您得到的响应。谢谢