JSON DATA
{
VerifiedMember: [{ user_id: "23", first_name: "karan", phone: "" }],
success: 1,
message: "success"
}
登录活动类
public class NewLogin extends AppCompatActivity {
private static final String PREFER_NAME = "Reg";
Button btnLogin;
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
SharedPreferences sharedPreferences;
// User Session Manager Class
UserSessionManager session;
String username;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
// User Session Manager
session = new UserSessionManager(getApplicationContext());
sharedPreferences = getApplication().getSharedPreferences("KEY", Context.MODE_PRIVATE);
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
private class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
@Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<>();
// Get username, password from EditText
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String url = "xxxx.xxx";
JSONObject json;
int successValue = 0;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "POST", params);
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains("username")) {
uName = sharedPreferences.getString("username", "");
}
if (sharedPreferences.contains("password")) {
uPassword = sharedPreferences.getString("password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession("username", "password");
} else {
}
}else{
}
Log.d("TESS :: ", json.toString());
successValue = json.getInt("success");
Log.d("Success Response :: ", String.valueOf(successValue));
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return String.valueOf(successValue);
}
protected void onPostExecute(String jsonstring) {
pDialog.dismiss();
if (jsonstring.equals("1")) {
Intent i = new Intent(NewLogin.this, Sample.class);
startActivity(i);
finish();
} else {
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
}
}
}
示例活动:
public class Sample extends AppCompatActivity {
private static final String URL_DATA = "xxx.xxx";
// User Session Manager Class
UserSessionManager session;
LinearLayout linearLayout;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private List<Data_SAerver> data_sAervers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
// Session class instance
session = new UserSessionManager(getApplicationContext());
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadRecyclerViewData();
swipeRefreshLayout.setRefreshing(false);
}
});
swipeRefreshLayout.setColorScheme(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
linearLayout = (LinearLayout) findViewById(R.id.linaralayout1);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Sample.this, Post_data_Activity.class);
startActivity(i);
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
data_sAervers = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DATA, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
progressDialog.dismiss();
String filename = "";
String filetype = "";
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray posts = jsonObject.getJSONArray("posts");
if (posts != null && posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject fileObj = posts.getJSONObject(i);
String fName = fileObj.getString("firstname");
String created_at = fileObj.getString("created_at");
String post_desc = fileObj.getString("post_desc");
Log.e("Details", fName + "" + created_at + "" + post_desc);
JSONArray files = fileObj.getJSONArray("files");
if (files != null && files.length() > 0) {
for (int j = 0; j < files.length(); j++) {
JSONObject Jsonfilename = files.getJSONObject(j);
filename = Jsonfilename.getString("file_name");
filetype = Jsonfilename.getString("file_type");
if (filetype.equalsIgnoreCase("2")) {
filename = "xxx.xxx" + filename;
} else if(filetype.equalsIgnoreCase("1")) {
filename = "xxx.xxx" + filename;
}
Log.e("Files", "" + filename);
}
} else {
filename = "";
filetype = "";
}
Data_SAerver item = new Data_SAerver(fName, created_at, post_desc, filename, filetype);
data_sAervers.add(item);
}
}
adapter = new MyAdapter(data_sAervers, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuLogout:
session.logoutUser();
/*startActivity(new Intent(this, NewLogin.class));
break;*/
}
return true;
}
}
MyAdapter类:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Data_SAerver> data_sAervers;
private Context context;
public MyAdapter(List<Data_SAerver> data_sAervers, Context context) {
this.data_sAervers = data_sAervers;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample, parent, false);
return new ViewHolder(v, context);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data_SAerver data_sAerver = data_sAervers.get(position);
holder.firstname.setText(data_sAerver.getFirstname());
holder.created_at.setText(data_sAerver.getCreated_at());
holder.post_desc.setText(data_sAerver.getPost_desc());
holder.filepathurl.setText(data_sAerver.getfilepath());
if (data_sAerver.getFiletype().equals("1")) {
holder.files.setVisibility(View.VISIBLE);
Picasso.with(context).load(data_sAerver.getfilepath()).resize(736, 1128).onlyScaleDown().into(holder.files);
holder.playvideo.setVisibility(View.GONE);
} else {
if (data_sAerver.getFiletype().equals("2")) {
holder.playvideo.setVisibility(View.VISIBLE);
holder.files.setVisibility(View.GONE);
holder.playvideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent play = new Intent(context, PlayVideo.class);
play.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
play.putExtra("url", data_sAerver.getfilepath());
context.startActivity(play);
}
});
}
}
}
@Override
public int getItemCount() {
return data_sAervers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// User Session Manager Class
UserSessionManager session;
public TextView firstname, commenttext;
public TextView created_at;
public TextView post_desc;
public ImageView files;
public LinearLayout comment_linear_layout;
public TextView comment_btn;
public TextView filepathurl;
public TextView playvideo;
// private TextView editTextUserName;
public TextView onlinefirstname;
Context con;
public ViewHolder(View itemView, Context context) {
super(itemView);
filepathurl = (TextView) itemView.findViewById(R.id.filepathurl);
filepathurl.setVisibility(View.GONE);
// editTextUserName = (TextView) itemView.findViewById(R.id.editTextUserrName);
playvideo = (TextView) itemView.findViewById(R.id.playvideo);
firstname = (TextView) itemView.findViewById(R.id.firstname);
created_at = (TextView) itemView.findViewById(R.id.created_at);
post_desc = (TextView) itemView.findViewById(R.id.post_desc);
files = (ImageView) itemView.findViewById(R.id.image_files);
con = context;
// onlinefirstname = (TextView)itemView.findViewById(R.id.online_user_firstname);
SparkButton sparkButton = (SparkButton) itemView.findViewById(R.id.star_button1);
sparkButton.setChecked(false);
comment_btn = (TextView) itemView.findViewById(R.id.comment_btn);
comment_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(con, Popup_layout.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
con.startActivity(i);
}
});
}
}
}
UserSessionManager:
public class UserSessionManager {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "username";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "firstname";
// password
public static final String KEY_PASSWORD = "password";
// Constructor
public UserSessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uName, String uPassord){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, uName);
// Storing email in pref
editor.putString(KEY_PASSWORD, uPassord);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Sample.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(_context, NewLogin.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
此处我无法使用共享偏好设置user_id
。请帮我解决问题。
答案 0 :(得分:0)
在onPostExecute尝试此操作,您将获得用户ID
try {
String userid;
JSONObject ob = new JSONObject(jsonstring);
JSONArray arr = ob.getJSONArray("VerifiedMember");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
userid=obj.getString("user_id");
}
} catch (Exception e) {
}
答案 1 :(得分:-1)
您可以使用此pojo生成器
http://www.jsonschema2pojo.org/
对于解析你可以使用google的gson库或jackson解析器也不错。 http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html