如何通过Async任务传递JSONObject

时间:2014-01-11 05:27:19

标签: java android android-asynctask

我很难将异步线程中的JSON对象传递给我的主线程,以便我可以在那里解析它。这是什么最好的做法?我尝试将onPostExecute的String更改为“JSONObject”但我收到can't be resolved to a type错误。

这是我的代码,我在我需要的JSONObject上放了一个箭头:

NewHomepage.java

public class NewHomepage extends Activity {

    public static String url = "http://www.somewebsite.com/android/SQL.php?username=";
    public static String usernamefromlogin;
    public static TextView errorchecking; 
    public static JSONArray user = null;

    //JSON Node Names 
    public String TAG_USER = "users";
    public String TAG_FIRST = "first";



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

          //get data from previous screen
          Intent intent = getIntent();
          getIntent().getExtras();

          //convert intent (intent) to string called "usernamefromlogin"         //error checking in log cat to see value of "usernamefromlogin"      
          usernamefromlogin = intent.getExtras().getString("username2");         Log.d("log usernamefromlogin", usernamefromlogin);

          //take the string "url" and add string "usernamefromlogin" after it    //error checking in log cat to see value of url5
          String url5 = url.concat(usernamefromlogin);                           Log.d("log url5", url5);



          //start asynch task
          class PostTask2 extends AsyncTask<String, String, String> {
               @Override
               protected void onPreExecute() {
               super.onPreExecute();



               }//end PreExecute

               @Override
               protected String doInBackground(String... params) {
               //pass url from outside class to inside this class   
               String url5 = params[0];

               //Creating new JSON Parser
               JSONParser jParser = new JSONParser();

               // Getting JSON from URL
--->           JSONObject json = jParser.getJSONFromUrl(url5);




               return null;

               }//end doInBackground



               protected void onProgressUpdate(String... values) {
               super.onProgressUpdate(values);


               }//end onProgressUpdate

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

               }//end onPostExecute
               }//end Async task

        //execute the Async task
        new PostTask2().execute(url5);












    }//end oncreate



    @Override
    public void onBackPressed() {
        // do nothing on back press
    }

}//end class

1 个答案:

答案 0 :(得分:0)

从你的doInBackgroung()中,你应该像这样返回 -

JSONObject json = jParser.getJSONFromUrl(url5);
return json.toString();

然后在你的onPostExecute()中,执行此操作 -

JSONObject newJson = new JSONObject(result);

我希望,这会对你有帮助。