在Android中按活动会话过滤从数据库中提取的数据

时间:2018-07-09 03:23:33

标签: android database listview session filtering

我有一个应用程序,它显示来自本地主机的数据库。 PHP文件将从'movies'表中获取'movie_name'的所有值。

从现在开始,该应用程序可以很好地运行,因为它显示了“ movie_name”的所有列表,并且还保留了“ username”登录的会话。

我正在尝试使用具有活动会话的'username'的值来过滤数据。我试图通过添加 user.getFullName()来修改doiInBackground()方法中MovieListingActivity.java中getString的值。但是没用。

protected String doInBackground(String... params) {
Session Handler session = new SessionHandler(getApplicationContext());
    User user = session.getUserDetails();
    HttpJsonParser httpJsonParser = new HttpJsonParser();
    JSONObject jsonObject = httpJsonParser.makeHttpRequest(
            BASE_URL + "fetch_all_movies.php", "GET", null);
    try {
        int success = jsonObject.getInt(KEY_SUCCESS);
        JSONArray movies;
        if (success == 1) {

            movieList = new ArrayList<>();
            movies = jsonObject.getJSONArray(KEY_DATA);
            //Iterate through the response and populate movies list
            for (int i = 0; i < movies.length(); i++) {
                JSONObject movie = movies.getJSONObject(i);
                Integer movieId = movie.getInt(KEY_MOVIE_ID);
                String movieName = movie.getString(KEY_MOVIE_NAME=user.getFullName());

                HashMap<String, String> map = new HashMap<>();
                map.put(KEY_MOVIE_ID, movieId.toString());
                map.put(KEY_MOVIE_NAME, movieName);
                movieList.add(map);}

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

protected void onPostExecute(String result) {
    pDialog.dismiss();
    runOnUiThread(new Runnable() {
        public void run() {
            populateMovieList();
        }
    });
}

这是我的MovieListingActivity.java:

    package com.bani.loginandregistration;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bani.loginandregistration.helper.CheckNetworkStatus;
import com.bani.loginandregistration.helper.HttpJsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MovieListingActivity extends AppCompatActivity {
private static final String KEY_SUCCESS = "success";
private static final String KEY_DATA = "data";
private static final String KEY_MOVIE_ID = "movie_id";
private static String KEY_MOVIE_NAME = "movie_name";
private static final String BASE_URL = "http://192.168.43.197/movies/";
private ArrayList<HashMap<String, String>> movieList;
private ListView movieListView;
private ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movie_listing);
    movieListView = (ListView) findViewById(R.id.movieList);

    new FetchMoviesAsyncTask().execute();

}

/**
 * Fetches the list of movies from the server
 */
private class FetchMoviesAsyncTask extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Display progress bar
        pDialog = new ProgressDialog(MovieListingActivity.this);
        pDialog.setMessage("Loading movies. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        HttpJsonParser httpJsonParser = new HttpJsonParser();
        JSONObject jsonObject = httpJsonParser.makeHttpRequest(
                BASE_URL + "fetch_all_movies.php", "GET", null);
        try {
            int success = jsonObject.getInt(KEY_SUCCESS);
            JSONArray movies;
            if (success == 1) {

                movieList = new ArrayList<>();
                movies = jsonObject.getJSONArray(KEY_DATA);
                //Iterate through the response and populate movies list
                for (int i = 0; i < movies.length(); i++) {
                    JSONObject movie = movies.getJSONObject(i);
                    Integer movieId = movie.getInt(KEY_MOVIE_ID);
                    String movieName = movie.getString(KEY_MOVIE_NAME);

                    HashMap<String, String> map = new HashMap<>();
                    map.put(KEY_MOVIE_ID, movieId.toString());
                    map.put(KEY_MOVIE_NAME, movieName);
                    movieList.add(map);}

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

    protected void onPostExecute(String result) {
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                populateMovieList();
            }
        });
    }

}

/**
 * Updating parsed JSON data into ListView
 * */
private void populateMovieList() {
    SessionHandler session;
    session = new SessionHandler(getApplicationContext());
    User user = session.getUserDetails();

    ListAdapter adapter = new SimpleAdapter(
            MovieListingActivity.this, movieList,
            R.layout.list_item, new String[]{KEY_MOVIE_ID,
            KEY_MOVIE_NAME},
            new int[]{R.id.movieId, R.id.movieName});
    // updating listview
    movieListView.setAdapter(adapter);
    //Call MovieUpdateDeleteActivity when a movie is clicked
    movieListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //Check for network connectivity
            if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
                String movieId = ((TextView) view.findViewById(R.id.movieId))
                        .getText().toString();
                Intent intent = new Intent(getApplicationContext(),
                        MovieUpdateDeleteActivity.class);
                intent.putExtra(KEY_MOVIE_ID, movieId);
                startActivityForResult(intent, 20);

            } else {
                Toast.makeText(MovieListingActivity.this,
                        "Unable to connect to internet",
                        Toast.LENGTH_LONG).show();

            }


        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 20) {
        // If the result code is 20 that means that
        // the user has deleted/updated the movie.
        // So refresh the movie listing
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}

 }

这是我的SessionHandler.java:

package com.bani.loginandregistration;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Date;

/**
 * Created by Abhi on 20 Jan 2018 020.
 */

public class SessionHandler {
private static final String PREF_NAME = "UserSession";
private static final String KEY_USERNAME = "username";
private static final String KEY_EXPIRES = "expires";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_EMPTY = "";
private Context mContext;
private SharedPreferences.Editor mEditor;
private SharedPreferences mPreferences;

public SessionHandler(Context mContext) {
    this.mContext = mContext;
    mPreferences = mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    this.mEditor = mPreferences.edit();
}

/**
 * Logs in the user by saving user details and setting session
 *
 * @param username
 * @param fullName
 */
public void loginUser(String username, String fullName) {
    mEditor.putString(KEY_USERNAME, username);
    mEditor.putString(KEY_FULL_NAME, fullName);
    Date date = new Date();

    //Set user session for next 7 days
    long millis = date.getTime() + (12 * 60 * 60 * 1000);
    mEditor.putLong(KEY_EXPIRES, millis);
    mEditor.commit();
}

/**
 * Checks whether user is logged in
 *
 * @return
 */
public boolean isLoggedIn() {
    Date currentDate = new Date();

    long millis = mPreferences.getLong(KEY_EXPIRES, 0);

    /* If shared preferences does not have a value
     then user is not logged in
     */
    if (millis == 0) {
        return false;
    }
    Date expiryDate = new Date(millis);

    /* Check if session is expired by comparing
    current date and Session expiry date
    */
    return currentDate.before(expiryDate);
}

/**
 * Fetches and returns user details
 *
 * @return user details
 */
public User getUserDetails() {
    //Check if user is logged in first
    if (!isLoggedIn()) {
        return null;
    }
    User user = new User();
    user.setUsername(mPreferences.getString(KEY_USERNAME, KEY_EMPTY));
    user.setFullName(mPreferences.getString(KEY_FULL_NAME, KEY_EMPTY));
    user.setSessionExpiryDate(new Date(mPreferences.getLong(KEY_EXPIRES, 0)));

    return user;
}

/**
 * Logs out user by clearing the session
 */
public void logoutUser(){
    mEditor.clear();
    mEditor.commit();
}

}

这是我的User.java:

package com.bani.loginandregistration;

import java.util.Date;

/**
 * Created by Abhi on 20 Jan 2018 020.
 */

public class User {
String username;
String fullName;
Date sessionExpiryDate;

public void setUsername(String username) {
    this.username = username;
}

public void setFullName(String fullName) {
    this.fullName = fullName;
}

public void setSessionExpiryDate(Date sessionExpiryDate) {
    this.sessionExpiryDate = sessionExpiryDate;
}

public String getUsername() {
    return username;
}

public String getFullName() {
    return fullName;
}

public Date getSessionExpiryDate() {
    return sessionExpiryDate;
}
}

0 个答案:

没有答案