我创建了一个片段,该片段从Web服务获取数据。当从Web服务获取数据时,我通知片段更新数据。我的数据正确到了Fragment,但是Fragment释放了我之前初始化的所有变量和控件,并且在设置TextView文本时出现了NullPointerException。
片段类:
public class UserFragment extends Fragment implements Daten {
private String username, streamingService;
public TextView usernameTv, currentTv;
private ImageView serviceIv;
public UserFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_user, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
findViews(view);
//GetRequest.getRequest(getContext(), LinkHandler.databaseGetFriend, LinkHandler.paramHelper("username", "name"));
GetRequest.getStringRequest(getContext(), LinkHandler.databaseGetFriend, LinkHandler.paramHelper("username", "name"));
}
@Override
public void erhalteFreunde(String Abbo) {
}
@Override
public void erhalteUser(JSONObject user){
try {
JSONArray userData = UserData.getInstance().getFetchedData().getJSONArray("message");
username = userData.getJSONObject(0).getString("username");
streamingService = userData.getJSONObject(0).getString("streamingservice");
usernameTv.setText(username);
currentTv.setText(userData.getJSONObject(0).getString("latestsong"));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void findViews(View view){
usernameTv = (TextView) view.findViewById(R.id.usernameTvUser);
currentTv = (TextView) view.findViewById(R.id.currentTvUser);
serviceIv = (ImageView) view.findViewById(R.id.serviceIvUser);
}}
我的Web请求:
public static void getStringRequest(final Context context, String url, final Map<String, String> parameter) {
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Daten daten = new UserFragment();
try {
daten.erhalteUser(Helper.convertStringToJson(response));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
return parameter;
}
};
queue.add(strRequest);
}}
我的界面:
public interface Daten {
void erhalteFreunde(String Abbo);
void erhalteUser(JSONObject user);}
希望您能帮助我解决问题。
答案 0 :(得分:0)
首先,您不应该在WebService中这样做。
Daten daten = new UserFragment();
解决方案
1)在webservice请求本身中传递回叫侦听器,此处是修改后的方法签名。
public static void getStringRequest(final Context context, String url, final Map<String, String> parameter, Daten daten )
2)然后呼叫将变成这样。
GetRequest.getStringRequest(getContext(), LinkHandler.databaseGetFriend, LinkHandler.paramHelper("username", "name"),this);