Android - 如何从java类传递另一个活动应用程序上下文将片段扩展到asynctask?

时间:2016-05-27 09:07:00

标签: java android android-fragments android-asynctask

您好我正在尝试制作具有视图寻呼机和tablayout的应用程序。因此,当我选择'friends'选项卡布局时,它将调用名为FragFriends.java的java类,

在这个类中,我想要使用类PHPapplist.java中使用asynctask方法检索的数据库中的数据来填充回收器视图适配器的布局

但是我的申请突然停止了

这是FragFriends.java

public class FragmentFriends extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup    container, @Nullable Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.activity_user_view,container,false);// The activity that contains recyclerview
    View dview = inflater.inflate(R.layout.activity_profile,container,false); //This is the activity that contains tablayout
    PHPUserList phpUserList = new PHPUserList(dview.getContext()); 
    phpUserList.execute();
    return rootview;
}

}

我已经有意图实现了这个回收站视图,它运行得很好。但是我需要将它用于片段 请帮助我

这是logcat

05-27 16:55:12.198 14031-14031/com.rumahdosen.www.rumahdosen E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.rumahdosen.www.rumahdosen, PID: 14031
        java.lang.NullPointerException
        at com.rumahdosen.www.rumahdosen.PHPUserList.onPreExecute(PHPUserList.java:82)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
        at android.os.AsyncTask.execute(AsyncTask.java:535)
        at com.rumahdosen.www.rumahdosen.FragmentFriends.onCreateView(FragmentFriends.java:20)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
        at android.view.View.measure(View.java:16834)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:824)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:500)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2252)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1315)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5292)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)

下面是PHPUserList.java

public class PHPUserList extends AsyncTask<Void,UserList,Void> {

private Context context;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<UserList> arrayList = new ArrayList<>();

PHPUserList(Context ctx){

    this.context = ctx;
    activity = (Activity)ctx;
}
@Override
protected Void doInBackground(Void... params) {
    try {
        URL url = new URL("http://njtwicomp.pe.hu/listuser.php");
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine())!=null)
        {
            stringBuilder.append(line+"\n");
        }

        httpURLConnection.disconnect();
        String json_string = stringBuilder.toString().trim();
        JSONObject jsonObject = new JSONObject(json_string);
        JSONArray jsonArray = jsonObject.getJSONArray("server_response");
        int count = 0;
        while(count<jsonArray.length()){
            JSONObject JO = jsonArray.getJSONObject(count);
            count++;
            UserList userList = new UserList(JO.getString("Name"),JO.getString("Username"));
            publishProgress(userList);
        }
        Log.d("JSON STRING", json_string);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPreExecute() {
    recyclerView = (RecyclerView) activity.findViewById(R.id.RVUserList);
    layoutManager = new LinearLayoutManager(context);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    adapter = new RecyclerAdapter(arrayList);
    recyclerView.setAdapter(adapter);
}

@Override
protected void onProgressUpdate(UserList... values) {
    arrayList.add(values[0]);
    adapter.notifyDataSetChanged();
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
}
}

我尝试在另一个活动中通过id找到recyclelerview,同时我将活动设置为传递的上下文的活动。但我不知道如何解决这个问题

那么如何获得不是我传入asynctask的上下文的活动?

3 个答案:

答案 0 :(得分:2)

改变这个:

PHPUserList phpUserList = new PHPUserList(dview.getContext()); 
phpUserList.execute();

到:

new PHPUserList(getActivity()).execute();

答案 1 :(得分:0)

在你的片段类中只需要放置getActivity(),需要Context就能完成这项任务!

答案 2 :(得分:0)

只需使用getContext();

这是有效的。 如果您需要使用活动上下文,则拥有ClassName.this

的静态上下文