2016-06-13 3 views
0

У меня есть активность, которая имеет четыре фрагмента. Я хочу получить доступ к переменной asyncTask из этого действия. Эта переменная создается в методе onPostExecute asyncTask.Невозможно получить доступ к переменной asyncTask

Я попытался создать метод в этом классе и получить к нему доступ в виде действия. но я получаю нулевой объект.

Нет идеи, что происходит не так.

AsyncTask

public class GetProfileAsyncTask extends AsyncTask<String, Void, JSONObject> { 
    String api; 
    JSONObject jsonParams; 
    private Context context; 
    public static JSONObject profile; 

    public GetProfileAsyncTask(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected JSONObject doInBackground(String... params) { 
     try { 
      api = context.getResources().getString(R.string.server_url) + "api/user/getprofile.php"; 

      jsonParams = new JSONObject(); 
      String username = params[0]; // params[0] is username 
      jsonParams.put("user", username); 

      ServerRequest request = new ServerRequest(api, jsonParams); 
      return request.sendRequest(); 
     } catch(JSONException je) { 
      return Excpetion2JSON.getJSON(je); 
     } 
    } //end of doInBackground 

    @Override 
    protected void onPostExecute(JSONObject response) { 
     super.onPostExecute(response); 
     Log.e("ServerResponse", response.toString()); 
     try { 
      int result = response.getInt("result"); 
      profile = response.getJSONObject("profile"); 

      String message = response.getString("message"); 
      if (result == 0) { 
       Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 
       //code after getting profile details goes here 
      } else { 
       Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 
       //code after failed getting profile details goes here 
      } 
     } catch(JSONException je) { 
      je.printStackTrace(); 
      Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show(); 
     } 
    } //end of onPostExecute 

    public static JSONObject getProfile() 
    { 
     return profile; 
    } 
} 

активность

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 

    toolbar.setTitle("Profile"); 

    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); 


    setSupportActionBar(toolbar); 

    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      finish(); 

     } 
    }); 

    profileAsyncTask = new GetProfileAsyncTask(this); 

    GetProfileAsyncTask task = new GetProfileAsyncTask(this); 

    profile = GetProfileAsyncTask.getProfile(); 

    task.execute("sid"); 

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),mTitles,mNumbOfTabs); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager)findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    mTabs = (SlidingTabLayout)findViewById(R.id.tabs); 
    mTabs.setDistributeEvenly(true); 
    mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { 
     @Override 
     public int getIndicatorColor(int position) { 
      return getResources().getColor(R.color.tab_scroll_color); 
     } 
    }); 

    mTabs.setViewPager(mViewPager); 
} 

EDIT: Пробовал это еще его нуль.

Как я могу получить доступ к параметрам из объекта JSON?

В AsyncTask:

public void onTaskCompleted(JSONObject response) { 
    profile = response; 
} 

активность:

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 

    toolbar.setTitle("Profile"); 

    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); 


    setSupportActionBar(toolbar); 

    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      finish(); 

     } 
    }); 

    profileAsyncTask = new GetProfileAsyncTask(this); 

    GetProfileAsyncTask task = new GetProfileAsyncTask(this); 
    task.execute("sid"); 

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),mTitles,mNumbOfTabs); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager)findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    mTabs = (SlidingTabLayout)findViewById(R.id.tabs); 
    mTabs.setDistributeEvenly(true); 
    mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { 
     @Override 
     public int getIndicatorColor(int position) { 
      return getResources().getColor(R.color.tab_scroll_color); 
     } 
    }); 

    mTabs.setViewPager(mViewPager); 
} 

@Override 
public void onTaskCompleted(JSONObject response) { 
    profile = response; 
} 

Получение объекта профиля нулевой. Пожалуйста помоги. Спасибо.

+1

Ваша асинтеза асинхронна. Вы можете использовать интерфейс в качестве обратного вызова для операции – Raghunandan

+0

как? @Raghunandan –

+0

просто Google вы найдете много ответов stackvoerflow. вот один https://xelsoft.wordpress.com/2014/11/28/asynctask-implementation-using-callback-interface/ – Raghunandan

ответ

0

Создайте поле вне задачи на уровне активности. Обновите его в onPostExecute.

+0

ok i follow this link: stackoverflow.com/questions/9963691/..., что делать в своей деятельности? как получить эту переменную в активности? @usajnf –

Смежные вопросы