简体   繁体   中英

Get Data from PHP using JSON in Android

In the BELOW Class there are no errors in my android app. But when i run the app and click on Register, nothing happens! Why isn't JSON working? Also my php is working fine. No problem!

I havent shown the entire php script but dont worry there arent any errors and works perfectly when browsed from the web browser. I have a small json array with a single row of data. $stringp is a string variable assigned.

There's something wrong with the below JSON code in Android. Whats the problem below? Do i need to do any changes?

PHP CODE :

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

Android Code :

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

        }
    );

}

And the Code Continues...

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

Have you ever used Async Task to perform Web service operation in background:

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM