我做了一个参数但是当我尝试打开应用程序时,它在第124行给了我错误 如何调用参数以便可以在代码中显示?
这是我的代码,以及我做过的事情
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link LoginFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link LoginFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class LoginFragment extends Fragment {
ProgressDialog pDialog;
Button btn_register, btn_login;
EditText txt_username, txt_password;
Intent intent;
int success;
ConnectivityManager conMgr;
private String url = Server.URL + "login.php";
private static final String TAG = LoginFragment.class.getSimpleName();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public final static String TAG_USERNAME = "username";
public final static String TAG_ID = "id";
String tag_json_obj = "json_obj_req";
SharedPreferences sharedpreferences;
Boolean session = false;
//String id, username;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//private static final String ARG_PARAM1 = "param1";
//private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String id;
private String username;
private OnFragmentInteractionListener mListener;
public LoginFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment LoginFragment.
*/
// TODO: Rename and change types and number of parameters
public static LoginFragment newInstance(String id, String username) {
LoginFragment fragment = new LoginFragment();
Bundle args = new Bundle();
args.putString(TAG_ID, id);
args.putString(TAG_USERNAME, username);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getContext(), "No Internet Connection",
Toast.LENGTH_LONG).show();
}
}
// Cek session login jika TRUE maka langsung buka MainActivity
sharedpreferences = getActivity().getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, id);
username = sharedpreferences.getString(TAG_USERNAME, username);
if (session) {
id = getActivity().getIntent().getExtras().getString(TAG_ID);
username = getActivity().getIntent().getExtras().getString(TAG_USERNAME);
getFragmentManager().beginTransaction().replace(R.id.content, new UserFragment()).commit();
//Intent intent = new Intent(getContext(), UserFragment.class);
//intent.putExtra(TAG_ID, id);
//intent.putExtra(TAG_USERNAME, username);
//getActivity().finish();
//startActivity(intent);
}
if (getArguments() != null) {
id = getArguments().getString(TAG_ID);
username = getArguments().getString(TAG_USERNAME);
}
}
private void checkLogin(final String username, final String password) {
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String id = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
// menyimpan login ke session
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();
// Memanggil main activity
id = getActivity().getIntent().getExtras().getString(TAG_ID);
username = getActivity().getIntent().getExtras().getString(TAG_USERNAME);
getFragmentManager().beginTransaction().replace(R.id.content, new UserFragment()).commit();
//Intent intent = new Intent(getContext(), MainActivity.class);
//intent.putExtra(TAG_ID, id);
//intent.putExtra(TAG_USERNAME, username);
//getActivity().finish();
//startActivity(intent);
} else {
Toast.makeText(getContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login, container, false);
btn_login = (Button) view.findViewById(R.id.btn_login);
btn_register = (Button) view.findViewById(R.id.btn_register);
txt_username = (EditText) view.findViewById(R.id.txt_username);
txt_password = (EditText) view.findViewById(R.id.txt_password);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
String username = txt_username.getText().toString();
String password = txt_password.getText().toString();
// mengecek kolom yang kosong
if (username.trim().length() > 0 && password.trim().length() > 0) {
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
checkLogin(username, password);
} else {
Toast.makeText(getContext() ,"No Internet Connection", Toast.LENGTH_LONG).show();
}
} else {
// Prompt user to enter credentials
Toast.makeText(getContext() ,"Kolom tidak boleh kosong", Toast.LENGTH_LONG).show();
}
}
});
btn_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
//intent = new Intent(getContext(), RegisterFragment.class);
//getActivity().finish();
//startActivity(intent);
getFragmentManager().beginTransaction().replace(R.id.content, new RegisterFragment()).commit();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String string) {
if (mListener != null) {
mListener.onLoginFragmentInteraction(string);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
//void onFragmentInteraction(Uri uri);
public void onLoginFragmentInteraction(String string);
}
}
我的错误
id = getActivity().getIntent().getExtras().getString(TAG_ID);
username = getActivity().getIntent().getExtras().getString(TAG_USERNAME);
如何从该片段中调用它们? 显示它的价值
感谢你的帮助
=============================================== ============================
确定代码已经登录,现在问题是代码在用户配置文件中显示为空
这是代码
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link UserFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link UserFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class UserFragment extends Fragment {
Button btn_logout;
TextView txt_id, txt_username;
//String id, username;
SharedPreferences sharedpreferences;
public static final String TAG_ID = "id";
public static final String TAG_USERNAME = "username";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//private static final String ARG_PARAM1 = "param1";
//private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String id;
private String username;
private OnFragmentInteractionListener mListener;
public UserFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment UserFragment.
*/
// TODO: Rename and change types and number of parameters
public static UserFragment newInstance(String id, String username) {
UserFragment fragment = new UserFragment();
Bundle args = new Bundle();
args.putString(TAG_ID, id);
args.putString(TAG_USERNAME, username);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedpreferences = getActivity().getSharedPreferences(LoginFragment.my_shared_preferences, Context.MODE_PRIVATE);
//id = getArguments().getString(TAG_ID);
id = getActivity().getIntent().getStringExtra(TAG_ID);
username = getActivity().getIntent().getStringExtra(TAG_USERNAME);
if (getArguments() != null) {
id = getArguments().getString(TAG_ID);
username = getArguments().getString(TAG_USERNAME);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user, container, false);
TextView txt_id = (TextView) view.findViewById(R.id.txt_id);
TextView txt_username = (TextView) view.findViewById(R.id.txt_username);
txt_id.setText("ID : " + id);
txt_username.setText("USERNAME : " + username);
btn_logout = (Button) view.findViewById(R.id.btn_logout);
btn_logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// update login session ke FALSE dan mengosongkan nilai id dan username
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(LoginFragment.session_status, false);
editor.putString(TAG_ID, null);
editor.putString(TAG_USERNAME, null);
editor.commit();
getFragmentManager().beginTransaction().replace(R.id.content, new LoginFragment()).commit();
//Intent intent = new Intent(getContext(), LoginFragment.class);
//getActivity().finish();
//startActivity(intent);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String string) {
if (mListener != null) {
mListener.onUserFragmentInteraction(string);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
//throw new RuntimeException(context.toString()
//+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onUserFragmentInteraction(String string);
}
}
答案 0 :(得分:3)
如果您不确定参数中是否包含数据,您可以通过
检查参数是否具有该值if (getArguments().containsKey(KEY_ID)) {
id = getArguments().getString(KEY_ID);
}
等等
答案 1 :(得分:0)
SELECT a.companyId 'companyId'
, i.orgDebtType 'orgDebtType'
, d.ratingTypeName 'ratingTypeName'
, c.currentRatingSymbol 'currentRatingSymbol'
, c.ratingStatusIndicator 'ratingStatusIndicator'
, g.qualifierValue 'qualifierValue'
, c.ratingdate 'ratingDate'
, h.value 'outlook'
FROM ciqRatingEntity a
JOIN ciqcompany com
on com.companyId = a.companyId
JOIN ciqratingobjectdetail b ON a.entitySymbolValue = b.objectSymbolValue
JOIN ciqRatingData c ON b.ratingObjectKey = c.ratingObjectKey
JOIN ciqRatingType d ON b.ratingTypeId = d.ratingTypeId
JOIN ciqRatingOrgDebtType i ON i.orgDebtTypeId=b.orgDebtTypeId
JOIN ciqRatingEntityData red ON red.entitySymbolValue=a.entitySymbolValue
AND red.ratingDataItemId='1' ---CoName
LEFT JOIN ciqRatingDataToQualifier f ON f.ratingDataId = c.ratingDataId
LEFT JOIN ciqRatingQualifiervalueType g ON g.qualifiervalueid = f.qualifierValueId
LEFT JOIN ciqRatingValueType h ON h.ratingValueId = c.outlookValueId
WHERE 1=1
AND b.ratingTypeId IN ( '130', '131', '126', '254' )
-- and a.companyId = @companyId
AND a.companyId IN
(SELECT distinct TOP 2000000
c.companyId
FROM ciqCompany c
inner join ciqCompanyStatusType cst on cst.companystatustypeid = c.companystatustypeid
inner join ciqCompanyType ct on ct.companyTypeId = c.companyTypeId
inner join refReportingTemplateType rep on rep.templateTypeId = c.reportingtemplateTypeId
inner join refCountryGeo rcg on c.countryId = rcg.countryId
inner join refState rs on rs.stateId = c.stateId
inner join ciqSimpleIndustry sc on sc.simpleIndustryId = c.simpleIndustryId
ORDER BY companyid desc)
ORDER BY companyId DESC, c.ratingdate, b.ratingTypeId, c.ratingStatusIndicator
返回null。
您可能没有在getActivity().getIntent().getExtras()
中添加任何内容,而您传递的参数可能是。您可以尝试使用intent.putExtra()