retrieving json data on android based on the username - java

I am new to android programming and right now I am having trouble trying to retrieve data from mysql phpmyadmin based on the username that is logged into the app. I have a table called booking that has details of all the user. now I want to retrieve all the details of one particular user from the database. how do I do that?
bookinglist.java
public class bookinglist extends ArrayAdapter<String> {
private String[] sportcenter_name;
private static String[] facility_name;
private static String[] date;
private static String[] start_time;
private static String[] end_time;
private Activity context;
public bookinglist(Activity context, String[] sportcenter_name, String[] facility_name, String[] date, String[] start_time, String[] end_time) {
super(context, R.layout.list_item, sportcenter_name);
this.context = context;
this.sportcenter_name = sportcenter_name;
this.facility_name = facility_name;
this.date = date;
this.start_time = start_time;
this.end_time = end_time;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_booking, null, true);
TextView textViewspname = (TextView) listViewItem.findViewById(R.id.textViewspname);
TextView textViewFacility = (TextView) listViewItem.findViewById(R.id.textViewFacility);
TextView textViewdate = (TextView) listViewItem.findViewById(R.id.textViewdate);
TextView textViewstarttime = (TextView) listViewItem.findViewById(R.id.textViewstarttime);
TextView textViewendtime = (TextView) listViewItem.findViewById(R.id.textViewendtime);
textViewspname.setText(sportcenter_name[position]);
textViewFacility.setText(facility_name[position]);
textViewdate.setText(date[position]);
textViewstarttime.setText(start_time[position]);
textViewendtime.setText(end_time[position]);
return listViewItem;
}
}
bookiglistJSON.java
public class bookinglistJSON {
public static String[] sportcenter_name;
public static String[] facility_name;
public static String[] date;
public static String[] start_time;
public static String[] end_time;
public static final String JSON_ARRAY = "result";
public static final String KEY_Sportcenter = "sportcenter_name";
public static final String KEY_Facility = "facility_name";
public static final String KEY_Date = "date";
public static final String KEY_Starttime = "start_time";
public static final String KEY_Endtime = "end_time";
private JSONArray booking = null;
private String json;
public bookinglistJSON(String json){
this.json = json;
}
protected void bookinglistJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
booking = jsonObject.getJSONArray(JSON_ARRAY);
sportcenter_name = new String[booking.length()];
facility_name = new String[booking.length()];
date = new String[booking.length()];
start_time = new String[booking.length()];
end_time = new String[booking.length()];
for(int i=0;i<booking.length();i++){
JSONObject jo = booking.getJSONObject(i);
sportcenter_name[i] = jo.getString(KEY_Sportcenter);
facility_name[i] = jo.getString(KEY_Facility);
date[i] = jo.getString(KEY_Date);
start_time[i] = jo.getString(KEY_Starttime);
end_time[i] = jo.getString(KEY_Endtime);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ViewBookings.java
public class ViewBookings extends AppCompatActivity {
public static final String JSON_URL = "http://www.khaledz.com/projects/project/viewbooking.php?username=";
public static final String KEY_USERNAME="username";
private TextView textView;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_booking);
textView = (TextView) findViewById(R.id.textViewUserName);
//Fetching email from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String username = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
//Showing the current logged in email to textview
textView.setText("Current User: " + username);
listView = (ListView) findViewById(R.id.listViewBooking);
sendRequest();
}
private void sendRequest(){
final String username = textView.getText().toString().trim();
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ViewBookings.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
bookinglistJSON pj = new bookinglistJSON(json);
pj.bookinglistJSON();
bookinglist nl = new bookinglist(ViewBookings.this, bookinglistJSON.sportcenter_name,bookinglistJSON.facility_name,bookinglistJSON.date,bookinglistJSON.start_time,bookinglistJSON.end_time);
listView.setAdapter(nl);
}
}
php script.
<?php
define('HOST','alahlitimercom.ipagemysql.com');
define('USER','book_play_123');
define('PASS','book_play_123');
define('DB','book_play_123');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_GET['username'];
$sql = "select * from booking WHERE username='$username'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>$row[0],
'sportcenter_name'=>$row[1],
'facility_name'=>$row[2],
'username'=>$row[3],
'created_at'=>$row[4],
'date'=>$row[5],
'start_time'=>$row[6],
'end_time'=>$row[7],
'court'=>$row[8],
'price'=>$row[9]
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>

http://afzaln.com/volley/com/android/volley/toolbox/StringRequest.html
Specifies the default request is GET
However in your php code you write
$username = $_POST['username'];
You should add the username as URL paramater to make it a GET parameter like this:
http://www.khaledz.com/projects/project/viewbooking.php?username=Harry
In PHP you write:
$username = $_GET['username'];

Related

Unable to start activity because of NullPointerException: Attempt to invoke virtual method HashMap on a null object reference

I am trying to start an activity checkin1. I am using volley and requesting info from mySQL db to display in four edit text fields.
I am using the same strategy I have used in other activities (sessionmanager) of my app and my code is identical as I keep crossreferencing and wondering why the error is occurring on line 47:
line 47 of checkin1HashMap<String, String> user= sessionManager.GetCheckInInfo();getId = user.get(sessionManager.ID);
I believe it could be a problem in my session manager(line130 of SessionManager - GetCheckInInfo();), but I am not sure because it is virtually identical to my other classes that I've been crossreferencing and work fine. Any help would be appreciated!
Sessionmanager.java
public class SessionManager {
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int Private_Mode = 0;
private static final String PREF_NAME= "LOGIN";
private static final String LOGIN = "IS_LOGIN";
public static final String USERNAME= "USERNAME";
public static final String EMAIL= "EMAIL";
public static final String ID = "ID";
public static final String PHONE = "PHONE_NUMBER";
private static final String ADDSM= "ADDITIONAL_SOCIAL_MEDIA";
private static final String HCNAME = "HOME_COUNTRY_EMERGENCY_CONTACT_NAME";
public static final String HCPHONE = "HOME_COUNTRY_EMERGENCY_PHONE_NUMBER";
public static final String HCEMAIL= "HOME_COUNTRY_EMERGENCY_CONTACT_EMAIL";
public static final String USANAME = "USA_EMERGENCY_CONTACT_NAME";
public static final String USAPHONE= "USA_EMERGENCY_PHONE_NUMBER";
public static final String USAEMAIL= "USA_EMERGENCY_CONTACT_EMAIL";
public static final String WHATSAPP = "WHATSAPP";
public static final String ADDRESS= "ADDRESS";
public static final String START_DATE= "START_DATE";
public static final String END_DATE= "END_DATE";
public SessionManager(Context context){
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, Private_Mode);
editor = sharedPreferences.edit();
}
public void createSession(String username, String email, String id){
editor.putBoolean(LOGIN, true);
editor.putString(USERNAME, username);
editor.putString(EMAIL, email);
editor.putString(ID, id);
editor.apply();
}
public boolean isLoggin(){
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checkLogin(){
if (!this.isLoggin()){
Intent i = new Intent(context, Register.class);
context.startActivity(i);
((MainActivity)context).finish();
}
}
public HashMap<String, String> getUserDetail(){
HashMap<String, String> user = new HashMap<>();
user.put(USERNAME, sharedPreferences.getString(USERNAME, null));
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
user.put(ID, sharedPreferences.getString(ID, null));
return user;
}
public void logout(){
editor.clear();
editor.commit();
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity)context).finish();
}
public void createSession2(String username, String id, String phone_number, String additional_social_media,
String home_country_emergency_contact_name, String address,
String home_country_emergency_phone_number, String home_country_emergency_contact_email,
String usa_emergency_contact_name, String usa_emergency_phone_number,
String usa_emergency_contact_email, String whatsapp){
editor.putBoolean(LOGIN, true);
editor.putString(USERNAME, username);
editor.putString(ID, id);
editor.putString(PHONE, phone_number);
editor.putString(ADDRESS, address);
editor.putString(HCPHONE, home_country_emergency_phone_number);
editor.putString(HCNAME, home_country_emergency_contact_name);
editor.putString(HCEMAIL, home_country_emergency_contact_email);
editor.putString(USAPHONE, usa_emergency_phone_number);
editor.putString(USANAME, usa_emergency_contact_name);
editor.putString(USAEMAIL, usa_emergency_contact_email);
editor.putString(WHATSAPP, whatsapp);
editor.putString(ADDSM, additional_social_media);
editor.apply();
}
public void createSessionMCI(String username, String id, String phone_number, String email, String address){
editor.putBoolean(LOGIN, true);
editor.putString(USERNAME, username);
editor.putString(ID, id);
editor.putString(PHONE, phone_number);
editor.putString(ADDRESS, address);
editor.putString(EMAIL, email);
editor.apply();
}
public HashMap<String, String> getUserDetail2(){
HashMap<String, String> user = new HashMap<>();
user.put(USERNAME, sharedPreferences.getString(USERNAME, null));
user.put(ID, sharedPreferences.getString(ID, null));
user.put(ADDRESS, sharedPreferences.getString(ADDRESS, null));
user.put(WHATSAPP, sharedPreferences.getString(WHATSAPP, null));
user.put(PHONE, sharedPreferences.getString(PHONE, null));
user.put(ADDSM, sharedPreferences.getString(ADDSM, null));
user.put(HCNAME, sharedPreferences.getString(HCNAME, null));
user.put(HCPHONE, sharedPreferences.getString(HCPHONE, null));
user.put(HCEMAIL, sharedPreferences.getString(HCEMAIL, null));
user.put(USANAME, sharedPreferences.getString(USANAME, null));
user.put(USAPHONE, sharedPreferences.getString(USAPHONE, null));
user.put(USAEMAIL, sharedPreferences.getString(USAEMAIL, null));
return user;
}
public HashMap<String, String> getUserDates() {
HashMap<String, String> user = new HashMap<>();
user.put(START_DATE, sharedPreferences.getString(START_DATE, null));
user.put(END_DATE, sharedPreferences.getString(END_DATE, null));
user.put(ID, sharedPreferences.getString(ID, null));
return user;
}
public HashMap<String, String> GetCheckInInfo() {
HashMap<String, String> user = new HashMap<>();
user.put(USERNAME, sharedPreferences.getString(USERNAME, null));
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
user.put(PHONE, sharedPreferences.getString(PHONE, null));
user.put(ADDRESS, sharedPreferences.getString(ADDRESS, null));
user.put(ID, sharedPreferences.getString(ID, null));
return user;
}
}
checkin1.java
private static final String TAG = checkin1.class.getSimpleName();
EditText phone_number, address, email, username;
SessionManager sessionManager;
private static String URL_ReadCheckin= "http://192.168.0.86:80/ReadCheckIns.php";
private static String URL_EDITCheckIN = "http://192.168.0.86:80/edit_detailcheckin.php";
String getId;
Button GoToJournal, GoToMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkin1);
HashMap<String, String> user= sessionManager.GetCheckInInfo();
getId = user.get(sessionManager.ID);
phone_number = findViewById(R.id.updatePhone);
email = findViewById(R.id.updateEmail);
address = findViewById(R.id.updateAddress);
username = findViewById(R.id.updateUsername);
GoToJournal = findViewById(R.id.myjournalbtn);
GoToMain = findViewById(R.id.mainmenubtn);
GoToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(checkin1.this, MainActivity.class));
SaveEditDetail();
}
});
GoToJournal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(checkin1.this, myJournal.class));
SaveEditDetail();
}
});
}
// get info
private void getCheckInDetails(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ReadCheckin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1")){
for (int i =0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
String strUserName = object.getString("username").trim();
String strEmail = object.getString("email").trim();
String strAddress = object.getString("address").trim();
String strPhone = object.getString("phone_number").trim();
phone_number.setText(strPhone);
address.setText(strAddress);
username.setText(strUserName);
email.setText(strEmail);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(checkin1.this, "Error Reading Details " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(checkin1.this, "Error Reading Details " + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("id", getId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
protected void onResume(){
super.onResume();
getCheckInDetails();
}```
NullPointerException is thrown when program attempts to use an object
reference that has the null value.
sessionManager = new SessionManager(checkin1.this);
HashMap<String, String> user= sessionManager.GetCheckInInfo();
getId = user.get(sessionManager.ID);

Fetch details of specific data item in recyclerview from mysql using php

I have a recyclerview with card layout. Populated view from MySQL database using PHP. Now, what I have to do is upon clicking any particular card it should open new activity showing image, name, price and description of that selected item. I have a second PHP file for fetching data item but cannot figure out a way to send data to PHP which would take data from android app and return information of only desired item in JSON.
I am using custom OnClickListener to open new activity. Can successfully pass itemname of selected data item to new activity. Need a way to pass that name to PHP so that it would return information from database for that particular itemname.
I'm using Volley library.
ExampleItem.java
public class ExampleItem {
private String mImgUrl;
private String mItemname,mItemprice;
public ExampleItem(String imgUrl, String itemname, String itemprice){
mImgUrl = imgUrl;
mItemname = itemname;
mItemprice = itemprice;
}
public String getmImgUrl(){
return mImgUrl;
}
public String getmItemname(){
return mItemname;
}
public String getmItemprice(){
return mItemprice;
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public MyAdapter(Context context, ArrayList<ExampleItem> exampleList){
mContext = context;
mExampleList = exampleList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.cardview_layout
, viewGroup, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
ExampleItem currentItem = mExampleList.get(i);
String imageUrl = currentItem.getmImgUrl();
String itemName = currentItem.getmItemname();
String itemPrice = currentItem.getmItemprice();
Picasso.get().load(imageUrl).fit().into(myViewHolder.mImageView);
myViewHolder.mItemName.setText(itemName);
myViewHolder.mItemPrice.setText(itemPrice);
Log.d("URL is", imageUrl);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mItemName;
public TextView mItemPrice;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
mItemName = itemView.findViewById(R.id.itemName);
mItemPrice = itemView.findViewById(R.id.itemPrice);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
});
}
}
}
ViewAllProds.java
public class ViewAllProds extends AppCompatActivity implements MyAdapter.OnItemClickListener {
Toolbar mToolbar;
private RecyclerView recyclerView;
GridLayoutManager gridLayoutManager;
private MyAdapter mMyAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyler_view_layout);
mToolbar = findViewById(R.id.viewallprod_toolbar);
mToolbar.setTitle(R.string.app_name);
recyclerView = findViewById(R.id.recyclerView);
gridLayoutManager = new GridLayoutManager(ViewAllProds.this, 2);
recyclerView.setLayoutManager(gridLayoutManager);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
String url = "http://192.168.43.241/android_connect/get_all_products.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url
, "", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Json String: ", response.toString().replace("\\",""));
try {
JSONArray jsonArray = response.getJSONArray("products");
for (int i = 0; i<jsonArray.length(); i++){
JSONObject prod = jsonArray.getJSONObject(i);
String imgUrl = prod.getString("image_url");
String prodname = prod.getString("name");
String prodprice = prod.getString("price");
mExampleList.add(new ExampleItem(imgUrl, prodname, prodprice));
}
mMyAdapter = new MyAdapter(ViewAllProds.this, mExampleList);
recyclerView.setAdapter(mMyAdapter);
mMyAdapter.setOnItemClickListener(ViewAllProds.this);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, ProductDetail.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra("name", clickedItem.getmItemname());
startActivityForResult(detailIntent, 100);
}
}
get_product_details.php
<?php
// array for JSON response
$response = array();
require 'db_config.php';
// connecting to db
$connect = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE) or die("Could not connect");
if (isset($_GET["name"])) {
$name = $_GET['name'];
$command = "SELECT * FROM products WHERE name = $name";
// get a product from products table
$result = mysqli_query($connect, $command);
if (!empty($result)) {
// check for empty result
if (mysqli_num_rows($result) > 0) {
$result = mysqli_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["name"] = $result["name"];
$product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
$product["image_url"] = $row["image_url"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_SLASHES);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Android convert int number from mysql database into time format

How do i able to convert from an integer number that is get from mysql database into time format? Here are my java files
parking_records.java with arrayAdapter
public class parking_records extends ArrayAdapter<String> {
private String[] Parking_Start_Time;
private String[] Parking_End_Time;
private String[] Duration;
private Activity context;
public parking_records(Activity context, String[] Parking_Start_Time, String[] Parking_End_Time, String[] Duration) {
super(context, R.layout.fragment_parking_record, Parking_Start_Time);
this.context = context;
this.Parking_Start_Time = Parking_Start_Time;
this.Parking_End_Time = Parking_End_Time;
this.Duration = Duration;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.fragment_parking_record, null, true);
TextView textViewPRd = (TextView) listViewItem.findViewById(R.id.textViewPRd);
TextView textViewPRd1 = (TextView) listViewItem.findViewById(R.id.textViewPRd1);
TextView textViewPRr = (TextView) listViewItem.findViewById(R.id.textViewPRr);
textViewPRd.setText(Parking_Start_Time[position]);
textViewPRd1.setText(Parking_End_Time[position]);
textViewPRr.setText(Duration[position]);
return listViewItem;
}
}
Parking_Records.java
public class Parking_Records {
public static String[] Parking_Start_Time;
public static String[] Parking_End_Time;
public static String[] Duration;
public static final String JSON_ARRAY = "result";
public static final String KEY_ParkStartTime = "Parking_Start_Time";
public static final String KEY_ParkEndTime = "Parking_End_Time";
public static final String KEY_ParkDuration = "Duration";
private JSONArray users = null;
private String json;
public Parking_Records(String json){
this.json = json;
}
public void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
Parking_Start_Time = new String[users.length()];
Parking_End_Time = new String[users.length()];
Duration = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
Parking_Start_Time[i] = jo.getString(KEY_ParkStartTime);
Parking_End_Time[i] = jo.getString(KEY_ParkEndTime);
Duration[i] = jo.getString(KEY_ParkDuration);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Parking_Records_Fragment.java
public class ParkingRecordFragment extends Fragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
ProgressDialog dialog;
String url;
SessionManager session;
private String Username;
private String Acc_Pass;
SharedPreferences shared;
private SwipeRefreshLayout mSwipeRefreshLayout;
public ParkingRecordFragment() {
// Required empty public constructor
}
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Parking Record");
// Session class instance
session = new SessionManager(getActivity().getApplicationContext());
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading....");
dialog.show();
View rootView = inflater.inflate(R.layout.activity_listview_parking_records, container, false);
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setEmptyView(rootView.findViewById(R.id.empty_list_item));
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
sendRequest(Username, Acc_Pass);
}
}, 1000);
sendRequest(Username, Acc_Pass);
shared= getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
return rootView;
}
#Override
public void onRefresh() {
sendRequest(Username, Acc_Pass);
}
private void sendRequest(String Username, String Acc_Pass){
HashMap<String, String> user = session.getUserDetails();
Username = user.get(SessionManager.KEY_USERNAME);
Acc_Pass = user.get(SessionManager.KEY_PASSWORD);
RequestQueue requestQueue = VolleyController.getInstance(getActivity().getApplicationContext()).getRequestQueue();
String url = "http://192.168.1.5/json_parking_records2.php?Username="+Username+"&Acc_Pass="+Acc_Pass+"";
url = url.replaceAll(" ", "%20");
try {
URL sourceUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Log.i("Getting url info",""+url);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
dialog.dismiss();
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
requestQueue.add(stringRequest);
}
private void showJSON(String json){
Parking_Records pj = new Parking_Records(json);
pj.parseJSON();
parking_records cl = new parking_records(getActivity(), Parking_Records.Parking_Start_Time, Parking_Records.Parking_End_Time, Parking_Records.Duration);
listView.setAdapter(cl);
}
#Override
public void onClick(View v) {
sendRequest(Username, Acc_Pass);
}
}
Android screenshot
So right now i've been struggling of how do i able to convert from an integer number to a time format. Please guide me. Thanks
I have solved my question on my own successfully. Here is the code.
textViewPRr.setText(String.format("%d:%02d:%02d", (Duration[position]/3600), (Duration[position]%3600)/60, (Duration[position]%60)));
I set that in parking_records.java with arrayAdapter
Hope that this answer can help others!

Want to Implements View.OnItemClickListener

i want to implements this method into my coding,but i dont know how to do it,can someone give me some suggestion on how to do it?
Below is the screenshot the coding that i want to use.
View.ONItemClickListener
this is my coding.
ViewOrder.java
public class ViewOrder extends AppCompatActivity implements ListView.OnItemClickListener {
public static final String JSON_URL = "http://dashberry.com/strack/mobile/viewOrder.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_order);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
}
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL, new Response.Listener<String>() {
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ViewOrder.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.itemName,ParseJSON.origin,ParseJSON.destination);
listView.setAdapter(cl);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ItemDetail.class);
//ParseJSON<String> map = (ParseJSON)parent.getItemAtPosition(position);
//HashMap<String,String> map = (HashMap)parent.getItemAtPosition(position);
// String empId = map.get(ParseJSON.itemName).toString();
// intent.putExtra("item_id", empId);
startActivity(intent);
}
}
ParseJSON.java
public class ParseJSON {
public static String[] itemName;
public static String[] origin;
public static String[] destination;
public static final String JSON_ARRAY = "result";
public static final String KEY_NAME = "itemName";
public static final String KEY_ORIGIN = "origin";
public static final String KEY_DESTINATION = "destination";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
itemName = new String[users.length()];
origin = new String[users.length()];
destination = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
itemName[i] = jo.getString(KEY_NAME);
origin[i] = jo.getString(KEY_ORIGIN);
destination[i] = jo.getString(KEY_DESTINATION);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So basically what i want is when user click the item in the list,it will take the user to the next activity with some data(itemName).
implement onItemClick like
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, ItemDetail.class);
//you can putExtra only position or id
intent.putExtra("position", position);
intent.putExtra("id", id);
startActivity(intent);
}
You Should Create Anther Activity called ItemDetail you can get id and position by add this code in onCreate() to know which item was clicked
Intent intent = getIntent();
String position = intent.getStringExtra("position");
String id = intent.getStringExtra("id");

Filter list view from ListAdapter in Android

Below is the code which will display the list of name in the list view.
I want to filter the list view based on the input of search textbox.
I have added the addTextChangedListener method for the edittext. But I am facing an error in getFilter() method as "can't resolve". As per the google I found the getFilter() method work on ArrayAdapter. I want to know how can I make getFilter() method work with ListAdapter.
Please can anyone let me know.
package com.smoothbalance.smothbalance;
public class AddedClientList extends CommonDrawer {
EditText searchTextBox;
ListAdapter adapter;
ListView addedlistofclient;
// JSON Nodes
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_FULL_NAME = "full_name";
private static final String TAG_EMAIL = "email";
//JSON array
JSONArray json_data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.activity_added_client_list, null, false);
mDrawerLayout.addView(view, 0);
addedlistofclient = (ListView) findViewById(R.id.listView_Added_Client);
searchTextBox = (EditText) findViewById(R.id.Search_added_clients);
dataList = new ArrayList<HashMap<String, String>>();
if (CommonFunctions.isNetworkAvailable(getBaseContext())) {
params.add(new BasicNameValuePair("", user_id));
new Added_client_list().execute();
} else {
Toast.makeText(getApplicationContext(), "Network Not Available... \n Please check Your Wifi Connection or Mobile Network", Toast.LENGTH_LONG).show();
}
searchTextBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
AddedClientList.this.adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private class Added_client_list extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... param) {
String network_error = null;
String url = getString(R.string.getClientlist) + user_id + "/Clients";
ServiceHandler serviceHandler = new ServiceHandler();
String jsonStr = serviceHandler.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
network_error = jsonStr;
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
// getting json array node
json_data = jsonObject.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < json_data.length(); i++) {
JSONObject c = json_data.getJSONObject(i);
String id = c.getString(TAG_ID);
String full_name = c.getString(TAG_FULL_NAME);
String email = c.getString(TAG_EMAIL);
// tmp hashmap for single data
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_FULL_NAME, full_name);
data.put(TAG_EMAIL, email);
// adding contact to contact list
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return network_error;
}
#Override
protected void onPostExecute(String aVoid) {
adapter = new SimpleAdapter(AddedClientList.this, dataList, R.layout.customelistview, new String[]
{TAG_FULL_NAME, TAG_EMAIL,}, new int[]{R.id.details, R.id.serviceData});
addedlistofclient.setAdapter(adapter);
}
}
As Luksprog mentioned in the comment, ListAdapter is not filterable, you would have either have to create a customAdapter by extending the listadapter and implementing filterable in that object, or use an adapter provided by the sdk that implementals filterable

Categories