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!
Related
I am having this issue for some time now, when I retrieved data from a database using volley and then show it in a recycler view, if the items are 8 or less than 8 then it shows them without any problem, but if I retrieve more than 8 items from database then the activity closes/crashes and goes back to the main activity. I don't get any error in the run console in android studio. I am retrieving 3 things from database for a single item, 2 strings and an image. I don't think the error is in the php file which is used to get the data as that I have checked and it retrieves without any issue. I have searched android documentation of recycler view but couldn't find anything
NOTE: I am getting image as string and then converting to bitmap.
if there is anything else needed then I can provide them without any issue.
the code is below:
Method which is used to call the recycler view activity which has problems.
public void onViewAttendanceButtonClick(int position, String courseCode,
String courseName, String batchName) {
if (MainActivity.teacherData != null) {
seeAttendanceDetails(MainActivity.teacherData.getEmail(),courseCode,
batchName, courseName, getDateAndTime);
}
}
private void seeAttendanceDetails(final String email,final String
courseCode, final String batchName,final String courseName, final String
date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
seeAttendanceDetails, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
String fullName = data.getString("full_name");
String Email = data.getString("email");
String photo = data.getString("photo");
Toast.makeText(CoursesActivity.this, courseCode,
Toast.LENGTH_LONG).show();
Attendance attendance1 = new Attendance(fullName, Email, photo);
attendanceArrayList.add(attendance1);
}
if (!attendanceArrayList.isEmpty()) {
Intent intent = new Intent(CoursesActivity.this,
ShowAttendanceActivity.class);
Bundle bundle = new Bundle();
bundle.putString("attendanceCourseCode",
courseCode);
bundle.putString("attendanceCourseName",
courseName);
bundle.putString("attendanceBatchName", batchName);
bundle.putSerializable("attendanceList",
attendanceArrayList);
intent.putExtras(bundle);
startActivity(intent);
}
else if (RegistrationActivity.teacherData != null) {
//
seeAttendanceDetails(RegistrationActivity.teacherData.getEmail(),
batchName,courseName, getDateAndTime);
// Toast.makeText(CoursesActivity.this,"No Record
Found",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CoursesActivity.this,
error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("batch", batchName);
params.put("date", date);
params.put("courseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
<br/>
The recycler view activity code
public class ShowAttendanceActivity extends AppCompatActivity implements
ShowAttendanceActivityAdapter.RemoveAttendanceClickListener {
private RecyclerView recyclerView;
private String courseCode,courseName,batchName;
private ArrayList<Attendance> attendanceArrayList = new ArrayList<>();
private TextView
textViewCourseCode,textViewCourseName,textViewBatchName;
private String deleteStudentAttendance =
"https://asuiot.umargulzar.com/Teacher%20API%2
0Files/deleteStudentattendance.php";
int success;
private String TAG_SUCCESS = "success";
private String TAG_MESSAGE = "message";
private String getDateAndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_attendance);
recyclerView = findViewById(R.id.attendance_details_recyclerView);
textViewCourseCode = findViewById(R.id.SA_textView_course_code);
textViewCourseName = findViewById(R.id.SA_textView_course_name);
textViewBatchName = findViewById(R.id.SA_textView_Batch);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
Calendar calendar = Calendar.getInstance();
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyy hh:mm:ss a");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
String dateTime = simpleDateFormat.format(calendar.getTime());
this.getDateAndTime = dateTime;
courseCode = (String) getIntent().getStringExtra("attendanceCourseCode");
courseName = (String) getIntent().getStringExtra("attendanceCourseName");
batchName = (String) getIntent().getStringExtra("attendanceBatchName");
attendanceArrayList = (ArrayList<Attendance>) getIntent().getExtras().getSerializable("attendanceList");
textViewCourseCode.setText(courseCode);
textViewCourseName.setText(courseName);
textViewBatchName.setText(batchName);
recyclerView.setAdapter(new ShowAttendanceActivityAdapter(attendanceArrayList,this));
}
#Override
public void onRemoveAttendanceClick(int position,String email) {
// Toast.makeText(ShowAttendanceActivity.this,"The Email of Student:"+email,Toast.LENGTH_LONG).show();
if(MainActivity.teacherData !=null){
deleteStudentAttendance(email,getDateAndTime,courseCode);
}
}
private void deleteStudentAttendance(final String email, final String getDateAndTime,final String courseCode) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, deleteStudentAttendance, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE)+" Plz refresh the page.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", email);
params.put("Date",getDateAndTime);
params.put("CourseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
the recycler view activity adapter
public class ShowAttendanceActivityAdapter extends RecyclerView.Adapter<ShowAttendanceActivityAdapter.AttendanceView> {
private ArrayList<Attendance> attendanceData;
Bitmap bitmap;
private RemoveAttendanceClickListener removeAttendanceClickListener;
public ShowAttendanceActivityAdapter(ArrayList<Attendance> attendanceData,RemoveAttendanceClickListener removeAttendanceClickListener){
this.attendanceData = attendanceData;
this.removeAttendanceClickListener = removeAttendanceClickListener;
}
#NonNull
#Override
public AttendanceView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_attendance_data,parent,false);
return new AttendanceView(view,removeAttendanceClickListener);
}
#Override
public void onBindViewHolder(#NonNull AttendanceView holder, int position) {
Attendance attendance = attendanceData.get(position);
holder.textViewName.setText(attendance.getStudentName());
// holder.textViewEmail.setText(attendance.getStudentEmail());
holder.textViewEmail.setText(attendance.getStudentEmail());
decodeStringToImage(attendance.getStudentPhoto());
holder.imageViewPhoto.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return attendanceData.size();
}
public void decodeStringToImage(String photo) {
// Bitmap bitmap = photo.
byte[] bytes = Base64.decode(photo, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public class AttendanceView extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textViewName, textViewEmail;
ImageView imageViewPhoto;
Button buttonRemoveCourse;
RemoveAttendanceClickListener removeAttendanceClickListener;
public AttendanceView(#NonNull View itemView,RemoveAttendanceClickListener removeAttendanceClickListener) {
super(itemView);
textViewName = itemView.findViewById(R.id.textView_name);
textViewEmail = itemView.findViewById(R.id.textView_Email);
imageViewPhoto = itemView.findViewById(R.id.textView_SA_Photo);
this.removeAttendanceClickListener = removeAttendanceClickListener;
buttonRemoveCourse = itemView.findViewById(R.id.btn_remove_attendance);
buttonRemoveCourse.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_remove_attendance:
removeAttendanceClickListener.onRemoveAttendanceClick(getAdapterPosition(),textViewEmail.getText().toString());
break;
}
}
}
public interface RemoveAttendanceClickListener{
void onRemoveAttendanceClick(int position,String email);
}
}
You are probably getting OutOfMemory exception while converting bytes array in to bitmap if the image sizes are huge.
Add try catch in your decodeStringToImage method where you are converting bitmaps and check the log when you load more than 8 images.
I'm developing an Android app using Google Sheets as a database.
I have information about books in a Google Sheet (title, author, cover, date, etc). I want to retrieve this information and show it in a "Listview" in the "Spreadsheets" Activity. I created a "BookItem" object and an "BookAdapter" adapter. In the "Spreadsheets.java" I have the read method, called "getDataFromApi()". I know that this method works, but I don't know how to adapt it to my "BookAdapter" and show the information on the ListView.
This is mi code:
public class BookItem {
static String title_item;
static Drawable cover_item; //probar con String
public BookItem(String title, Drawable cover){
super();
this.title_item = title;
this.cover_item = cover;
}
public String getTitle() {
return title_item;
}
public void setTitle(String title){
this.title_item = title;
}
public static Drawable getCover() {
return cover_item;
}
public void setCover(Drawable cover) {
this.cover_item = cover;}
This is my BookAdapter:
public class BookAdapter extends BaseAdapter {
private ArrayList<BookItem> items;
List<BookItem> items;
private Context context;
public BookAdapter (Context context, List<BookItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public BookItem getItem(int position) {
return this.items.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
private static class ViewHolder {
public final ImageView cover_item;
public final TextView title_item;
public ViewHolder (ImageView cover_item, TextView title_item){
this.cover_item = cover_item;
this.title_item = title_item;
}
}
#Override
public View getView (int position, View view, ViewGroup viewGroup) {
ImageView cover_item;
TextView title_item;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.fila_lista_miestanteria, viewGroup, false); //se mete aqui en getView por ser baseAdapter
title_item = (TextView) view.findViewById(R.id.book_title_item);
cover_item = (ImageView) view.findViewById(R.id.book_cover_item);
view.setTag(R.id.book_title_item, title_item);
view.setTag(R.id.book_cover_item, cover_item);
}
else {
cover_item = (ImageView) view.getTag(R.id.book_cover_item);
title_item = (TextView)view.getTag(R.id.book_title_item);
}
BookItem bookItem = getItem(position);
cover_item.setImageDrawable(bookItem.getCover());
title_item.setText(bookItem.getTitle());
return view;
}
}
public class Spreadsheets extends Activity {
static String book_title, book_author, book_date, book_category, book_description, book_rating, book_cover;
static String read_only = "no";
static String book_favorite = "no";
static GoogleAccountCredential mCredential;
private ListView bookList;
private TextView mOutputText;
ProgressDialog mProgress;
Context context;
List<String> rst;
List<BookItem> resultados;
BookAdapter adapter;
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spread);
// mOutputText = (TextView) findViewById(R.id.outputText);
bookList = (ListView) findViewById(R.id.bookList);
// mOutputText.setText("");
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Google Sheets...");
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
System.out.print("read only es igual a "+ read_only);
new MakeRequestTask(mCredential).execute();
}
public void rellenar(){
System.out.println("VOY A HACER NEW BOOK ADAPTER ");
adapter = new BookAdapter(context, resultados);
bookList.setAdapter(adapter);
System.out.println("SETADAPTER");
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
}
#Override
protected List<String> doInBackground(Void... params) {
try {
if(read_only.equals("no")) {
setDataToApi();
return null;
}
else {
return getDataFromApi();
}
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private List<String> getDataFromApi() throws IOException {
String range = "Sheet1!A1:H";
List<String> results = new ArrayList<String>();
ValueRange response = CreateSpreadsheets.mService.spreadsheets().values()
.get(CreateSpreadsheets.spreadsheet_id, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
for (List row : values) {
results.add(row.get(0) + ", " + row.get(7));
}
}
//funcion();
return results;
}
private void setDataToApi() throws IOException {
String range = "Sheet1!A2:H";
List<List<Object>> values = new ArrayList<>();
List<Object> data1 = new ArrayList<>();
data1.add(book_title);
data1.add(book_author);
data1.add(book_date);
data1.add(book_category);
data1.add(book_description);
data1.add(book_rating);
data1.add(book_cover);
data1.add("a");
values.add(data1);
ValueRange valueRange = new ValueRange();
valueRange.setMajorDimension("ROWS");
valueRange.setRange(range);
valueRange.setValues(values);
ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse response =
CreateSpreadsheets.mService.spreadsheets().values().append(CreateSpreadsheets.spreadsheet_id, range, body)
.setValueInputOption("RAW")
.execute();
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
// mOutputText.setText("No results returned.");
} else {
if(read_only.equals("no")) {
Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
startActivity(intent);
// mOutputText.setText("Se ha añadido un libro a su lista");
}
else {
System.out.println("VOY A RELLENAR LA LISTA");
rellenar();
}
}
}
#Override
protected void onCancelled() {
}
}
}
The "spread.xml" is a list, and the "fila_list_miestanteria.xml" is a TextView&ImageView to show the book info.
Thank you so much!
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");
I have three classes, my adapter class, Voting class, and an acitivty where my JSONrequest is as shown below.The problem is as you can see that I call my JSONrequest in my activity which will get a list of views, inside that view I have a mVote textview. In my adapter you can also see I have a likeButton when someone presses that I would like mVotes to change from 0 to 1. I get all my data from a server so I am assuming I would need to make a new request, do I need to make a new adapter to? and JSON parseing method? How do I do this?!??!
public class AdapterQuestion extends RecyclerView.Adapter<AdapterQuestion.ViewQuestion>{
private LayoutInflater mLayoutInflater;
private ArrayList<QuestionData> data =new ArrayList<>();
public AdapterQuestion(Context context){
//get from context
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<QuestionData> data){
this.data =data;
notifyItemRangeChanged(0, this.data.size());
}
#Override
public ViewQuestion onCreateViewHolder(ViewGroup parent, int viewType){
ViewQuestion holder=new ViewQuestion(view);
return holder;
}
#Override
public void onBindViewHolder(ViewQuestion holder, int position) {
holder.answerText.setText(currentObj.getMtext());
holder.answerId.setText(currentObj.getId());
holder.mVotes.setText(currentObj.getVotes());
holder.mLikeButton.setTag(currentObj);
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewQuestion extends RecyclerView.ViewHolder{
private TextView answerText;
private TextView answerId;
private TextView mVotes;
private LikeButton mLikeButton;
public ViewQuestion (View itemView){
super(itemView);
answerText=(TextView)itemView.findViewById(R.id.answerText);
answerId=(TextView)itemView.findViewById(R.id.answerId);
mVotes=(TextView)itemView.findViewById(R.id.VoteTextView);
mLikeButton= (LikeButton)itemView.findViewById(R.id.heart_buttons);
mLikeButton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
Voting vote = new Voting();
vote.onUpVote(answerId());
System.out.print("Adapter Position"+getAdapterPosition());
}
#Override
public void unLiked(LikeButton likeButton) {
Voting onDown=new Voting();
onDown.onDownVote(answerId());
}
});
}
public String getVoteView(){
String voteView=mVotes.getText().toString();
return voteView;
}
public String answerId(){
String converted=answerId.getText().toString();
return converted;
}
public int convertToInt(){
String converted=answerId.getText().toString();
int ConvertedInt=Integer.parseInt(converted);
return ConvertedInt;
}
}
}
Voting
public class Voting {
private VolleySingleton mVolleySingleton;
private RequestQueue mRequestQueue;
private AdapterVoteUpdate mAdapterVotes;
private ArrayList<QuestionData> updateVotes = new ArrayList<>();
public void onUpVote(final String answerId) {
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "url" + answerId + "url\n";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mrequestQueue.add(PostVoteUp);
}
public void onDownVote(final String answerId) {
System.out.println("Voted Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_DOWN = "url" + answerId + "urul";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
}
JSON RequestClass
public void JsonRequestMethod(String Id) {
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
final String URL_ANSWER = "url" + Id + "url";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
mListblogs.clear();
mListblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(mListblogs);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
private ArrayList<QuestionData> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<QuestionData> questionDataArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
System.out.println(votes+" VOTES");
int voteInt=Integer.parseInt(votes);
System.out.println(voteInt);
String Answerid = currentQuestions.getString("id");
String selectedId = currentQuestions.getString("selected");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
QuestionData questionData = new QuestionData();
questionData.setMtext(text);
questionData.setVotes(votes);
questionData.setId(Answerid);
questionData.setSelected(selectedId);
mListblogs.add(questionData);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return mListblogs;
}
"I get all my data from a server so I am assuming I would need to make a new request."
-> Actually you don't need to re-request the data from your server again. You just need to update
private ArrayList<QuestionData> data =new ArrayList<>();
on your AdapterQuestion then call AdapterQuestion.notifyDataSetChanged(); after you get a success response from onUpVote or onDownVote
"Do I need to make a new adapter to? and JSON parseing method? How do I do this?!??!"
-> No need
To change a particular ItemView in your recyclerview use this below code.
notifyItemChanged(index);
If you want to change the particular Textview in onItemclick you have to get the item position.
#Override
public void onBindViewHolder(ViewQuestion holder, int position) {
holder.answerText.setText(currentObj.getMtext());
holder.answerId.setText(currentObj.getId());
holder.mVotes.setText(currentObj.getVotes());
holder.mVotes.setTag(currentObj);
holder.mLikeButton.setTag(holder);
}
In your like button click event change the code like the below
mLikeButton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
Voting vote = new Voting();
vote.onUpVote(answerId());
final ViewQuestion holder=(ViewQuestionholder)likeButton.getTag();
currentObj co=(currentObj)holder.mVotes.getTag();
holder.mVotes.setText("16");
System.out.print("Adapter Position"+getAdapterPosition());
}
#Override
public void unLiked(LikeButton likeButton) {
Voting onDown=new Voting();
onDown.onDownVote(answerId());
final ViewQuestion holder=(ViewQuestionholder)likeButton.getTag();
currentObj co=(currentObj)holder.mVotes.getTag();
holder.mVotes.setText("14");
}
});
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'];