简体   繁体   中英

how to fetch data from url in mainactivity in android

the code i am using is working very fine for me but the problem is i am not able to fetch that data in main activity

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    final String TAG = "AsyncTaskParseJson.java";

    // set your json string url here
    String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

    // contacts JSONArray
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @Override
    protected String doInBackground(String... arg0) {

        try {

            // instantiate our json parser
            JsonParser jParser = new JsonParser();

            // get json string from url
            JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

            // get the array of users
            dataJsonArr = json.getJSONArray("Users");

            // loop through all users
            for (int i = 0; i < dataJsonArr.length(); i++) {

                JSONObject c = dataJsonArr.getJSONObject(i);

                // Storing each json item in variable
                String firstname = c.getString("firstname");
                String lastname = c.getString("lastname");
                String username = c.getString("username");

                // show the values in our logcat
                Log.e(TAG, "firstname: " + firstname 
                        + ", lastname: " + lastname
                        + ", username: " + username);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String strFromDoInBg) {}
}

this is the code new AsyncTaskParseJson().execute(); to make this thing work

but i need to run

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // we will using AsyncTask during parsing 
    new AsyncTaskParseJson().execute();
}`

I want to get the data like firstname , lastname , username as variable in main activity .

Is it possible ??

this is my other class IncomingCall.java when i want to get the variables

           public class IncomingCall extends BroadcastReceiver {
private String firstname;
private String lastname;
private String username;




  public void onReceive (Context context, Intent intent) {
  // TODO Auto-generated method stub



    Toast.makeText(context, " Calling "+username, Toast.LENGTH_LONG).show();    

    try {

        if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                 TelephonyManager.EXTRA_STATE_IDLE)
                 || intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                         TelephonyManager.EXTRA_STATE_OFFHOOK)) {
            notifyuser=true;

        }

    } catch (Exception e) {
        // TODO: handle exception

        //Toast.makeText(context, "Error detected 1 "+e, Toast.LENGTH_LONG).show(); 

    }
  }


  public class AsyncTaskParseJson extends AsyncTask<String, String, String>      {

    final String TAG = "AsyncTaskParseJson.java";

    // set your json string url here
    String yourJsonStringUrl =     "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

    // contacts JSONArray
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @Override

    protected String doInBackground(String... arg0) {

        try {

            // instantiate our json parser
            JsonParser jParser = new JsonParser();

            // get json string from url
            JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

            // get the array of users
            dataJsonArr = json.getJSONArray("Users");

            // loop through all users
           // for (int i = 0; i < dataJsonArr.length(); i++) {

                JSONObject c = dataJsonArr.getJSONObject(0);

                // Storing each json item in variable
                firstname = c.getString("firstname");
                lastname = c.getString("lastname");
                username = c.getString("username");

                // show the values in our logcat
                Log.e(TAG, "firstname: " + firstname 
                        + ", lastname: " + lastname
                        + ", username: " + username);

           // }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Here you use your variables
            }
        });

        return null;
    }

    protected void onPostExecute(String strFromDoInBg) {


         Log.e("TAG1", "firstname: " + firstname 
                 + ", lastname: " + lastname
                 + ", username: " + username);


    }
}

this is my code

Put your code in your Main Activity class, and then use class variables to store what you want, eg:

public class MainActivity extends Activity {

    private String[] firstname;
    private String[] lastname;
    private String[] username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new AsyncTaskParseJson().execute();

    }

    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here
        String yourJsonStringUrl =     "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";

        // contacts JSONArray
        JSONArray dataJsonArr = null;

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {

                // instantiate our json parser
                JsonParser jParser = new JsonParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                // get the array of users
                dataJsonArr = json.getJSONArray("Users");


                firstname = new String[dataJsonArr.length()];
                lastname = new String[dataJsonArr.length()];
                username = new String[dataJsonArr.length()];

                // loop through all users
                for (int i = 0; i < dataJsonArr.length(); i++) {

                    JSONObject c = dataJsonArr.getJSONObject(i);

                    // Storing each json item in variable
                    firstname[i] = c.getString("firstname");
                    lastname[i] = c.getString("lastname");
                    username[i] = c.getString("username");

                    // show the values in our logcat
                    Log.e(TAG, "firstname: " + firstname 
                            + ", lastname: " + lastname
                            + ", username: " + username);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //Here you use your variables
                }
            });

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {}
    }
}

Something like this (it's without error checking, give it a try)

EDIT: be sure to have declared the internet permission in the android manifest:

<uses-permission android:name="android.permission.INTERNET" />

The method onPostExecute runs on the main thread, You need to use the data once the doInBackground finishes and control return to the main thread.

Better you use these data in the method

  protected void onPostExecute(String strFromDoInBg) {
   // use the firstname , lastname or username after this method call.
   }

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