سؤال

My code is as follows:

private class GetMovie extends AsyncTask<String, Void, String[]>{

    protected String[] doInBackground(String...arg0){
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();


        String url = getResources().getString(urlIds[randomNumber]);
        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

    if (jsonStr != null){



            try{        

                JSONObject json= (JSONObject) new JSONTokener(jsonStr).nextValue();
                String MovieTitle = json.getString(TAG_TITLE);
                String MovieYear = json.getString(TAG_YEAR);
                String MovieReleased = json.getString(TAG_RELEASE_DATE);
                String MovieDirector = json.getString(TAG_DIRECTOR);
                String MovieActors = json.getString(TAG_ACTORS);//will need to split actors
                String MovieAwards = json.getString(TAG_AWARDS);
                String MovieGenre = json.getString(TAG_GENRE);

                String[] movie = new String []   {MovieTitle,MovieYear,MovieReleased,MovieDirector,MovieActors,MovieAwards,MovieGenre};
                return movie;
            } catch (JSONException e){
                e.printStackTrace();
            } 

        } else {
            Log.e("ServiceHandler", "Couldnt get any data from the url");
        } 
        return null; 
    }

    protected void onPostExecute(String[] result) {

    super.onPostExecute(result);
    }



}

I am basically trying to populate the movie array in this background task. In my on create method I am then trying to access it using the following code:

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

//Calls task to get json and store in string array
   // new GetMovie().execute();

   GetMovie questionstring = new GetMovie();
   String[] movie = questionstring.doInBackground();
    String Title = movie[0];
    String Year = movie[1];
    String Released = movie[2];
    String Director = movie[3];
    String Actor = movie[4];
    String Awards = movie[5];
    String Genre = movie[6];

I am then trying to store each record in the array in Strings. This is all done in one activity. Hope someone can help.

هل كانت مفيدة؟

المحلول 3

replace this:

String[] movie = questionstring.doInBackground();
String Title = movie[0];
String Year = movie[1];
String Released = movie[2];
String Director = movie[3];
String Actor = movie[4];
String Awards = movie[5];
String Genre = movie[6];

with this:

questionstring.execute();
String[] movie = questionstring.get();

the .get method waits until the async thread is finished so ideally you should do some other actions if applicable before calling .get straight away


alternate method:

myActivity act;
 GetMovie(myActivity act){
this.act=act;
}
   protected void onPostExecute(String[] result) {
act.setMovies(result);
    super.onPostExecute(result);
    }

create relevant methods in myActivity class like so:

global variable

GetMovie questionstring=null; 
String[] movie;

on create:

questionstring = new GetMovie(this);
questionstring.execute();

on destroy:

onDestroy(){
if(questionstring!=null)questionstring.cancel(true);
super.onDestroy();
}

set movies:

public void setMovies(String[] mov){
movies=mov;
textView0.setText(mov[0]);
textView1.setText(mov[1]);
textView2.setText(mov[2]);
textView3.setText(mov[3]);
textView4.setText(mov[4]);
textView5.setText(mov[5]);
textView6.setText(mov[6]);
}

نصائح أخرى

questionstring.doInBackground();

You should never call AsyncTask's "lifecycle" methods; the system will call them for you. You can get the result returned from doInBackground() in onPostExecute().

You must rewrite your onCreate method (and perhaps other parts of your activity's initialization) to work without the data being available. The whole point of using an AsyncTask is to allow long-running operations to proceed without blocking the UI thread. If you force onCreate to wait until the data are available, the UI will block.

Move the logic that deals with the data (once they are available) to the task's onPostExecute method. Alternatively, move the logic into a method in your activity and call that method (with the results as an argument) from onPostExecute.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top