I have tried using the code below but it does not work. it just returns a null value when retrieved from the fragment.
MainActivity.java
setting the bundle:
public class MainActivity extends Activity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
int user_id;
int lala;
int test2;
String userIDD;
String user_fname;
String user_lname;
int dept_id;
String test;
String user_email;
String user_password;
String user_username;
Bundle profileBundle;
String userid;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userid = edtuserid.getText().toString();
password = edtpass.getText().toString();
int lala = Integer.parseInt(userid);
test2 = lala;
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
//DITO ANG REDIRECTION
Intent base = new Intent(MainActivity.this, OtherActivity.class);
startActivity(base);
finish();
}
}
#Override
public String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select user_id, user_fname, user_lname,department_id, user_email, user_password, user_username from users where user_id='" + userid + "' and user_password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
userIDD = rs.getString(1);
user_fname = rs.getString(2);
user_lname = rs.getString(3);
dept_id = rs.getInt(4);
user_email = rs.getString(5);
user_password = rs.getString(6);
user_username = rs.getString(7);
profileBundle = new Bundle();
profileBundle.putInt("userID", user_id);
profileBundle.putInt("deptID", dept_id);
profileBundle.putString("fname", user_fname);
profileBundle.putString("lname", user_lname);
profileBundle.putString("email", user_email);
profileBundle.putString("pass", user_password);
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
//Fragment fragobj = new PathfinderAdd();
//fragobj.setArguments(profileBundle);
z = "Logged In as: " + user_username;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
Log.e("MYAPP", "exception", ex);
z = "Error Somewhere";
}
}
return z;
}
}
public int getMyData() {
int wa = lala;
return wa;
}
}
PahtfinderAdd.java
getting the bundle in the fragment
public class PathfinderAdd extends Fragment {
ConnectionClass connectionClass;
EditText edtideaname, edtbenefit,edtobservation,edtquickwin,targetdate;
Button btnadd;
TextView targettv;
Spinner spinner1, spinner2;
ProgressBar pbbar;
String proid;
CalendarView calendar;
String realDate;
String DAY;
Date targ = null;
String finalDate;
SimpleDateFormat timeFormat;
java.sql.Date sql;
Date date2;
Integer userID;
int user;
public PathfinderAdd(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addpathfinder, container, false);
connectionClass = new ConnectionClass();
edtideaname = (EditText) rootView.findViewById(R.id.edtideaname);
edtbenefit = (EditText) rootView.findViewById(R.id.edtbenefit);
edtobservation = (EditText) rootView.findViewById(R.id.edyobservation);
edtquickwin = (EditText) rootView.findViewById(R.id.edtquickwin);
targetdate = (EditText) rootView.findViewById(R.id.target);
spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
btnadd = (Button) rootView.findViewById(R.id.btnadd);
pbbar = (ProgressBar) rootView.findViewById(R.id.pbbar);
targettv = (TextView) rootView.findViewById(R.id.tvtarget);
pbbar.setVisibility(View.GONE);
calendar = (CalendarView) rootView.findViewById(R.id.calendar1);
proid = "";
userID = getArguments().getInt("userID");
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
//String lol = new getMyData().
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPro addPro = new AddPro();
addPro.execute("");
}
});
calendar.setOnDateChangeListener(new OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year_date, int month_date,
int dayOfMonth) {
int day = dayOfMonth;
int month = month_date;
int year = year_date;
DAY=String.valueOf(year)+String.valueOf(month)+String.valueOf(day);
}
});
return rootView;
}
public class AddPro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String observation = edtobservation.getText().toString();
String quickwin = edtquickwin.getText().toString();
String ideaname = edtideaname.getText().toString();
String benefit = edtbenefit.getText().toString();
String target_date = targetdate.getText().toString();
String process = spinner1.getSelectedItem().toString();
String benefitType = spinner2.getSelectedItem().toString();
String lol = "2015-11-28";
Integer benefit_type = spinner2.getSelectedItemPosition();
Integer idea_type = spinner1.getSelectedItemPosition();
Integer idea_id;
Integer benefit_id;
Integer pathfinder_id = 1;
Integer pathfinder_status = 9;
Integer pathfinder_prog = 0;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(PathfinderAdd.this.getActivity(), r, Toast.LENGTH_SHORT).show();
if(isSuccess==true) {
edtideaname.setText(null);
edtbenefit.setText(null);
edtobservation.setText(null);
edtquickwin.setText(null);
targetdate.setText(null);
}
}
#Override
protected String doInBackground(String... params) {
if (ideaname.trim().equals("") || benefit.isEmpty() || observation.trim().equals("") || quickwin.trim().equals(""))
z = "Please fill all the fields";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
//timeFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
//finalDate = timeFormat.format(targ);
//sql = new java.sql.Date(targ.getTime());
int lol=1;
double benefitInt = Double.parseDouble(benefit);
date2 = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(DAY);
String newDateString = new SimpleDateFormat("yyyy/MM/dd",Locale.ENGLISH).format(date2);
DateFormat format2 = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date date3 = format2.parse(newDateString);
java.sql.Date finalDt = new java.sql.Date(date3.getTime());
String dates = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
.format(Calendar.getInstance().getTime());
//String date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
//.format(calendar.getDate());
switch (idea_type)
{
case 0:
idea_id = 1;
break;
case 1:
idea_id = 2;
break;
case 2:
idea_id = 3;
break;
case 3:
idea_id = 4;
break;
case 4:
idea_id = 5;
break;
default:
idea_id = 1;
break;
}
switch(benefit_type)
{
case 0:
benefit_id = 1;
break;
case 1:
benefit_id = 2;
break;
default:
benefit_id = 1;
break;
}
String query = "insert into pathfinder (pathfinder_id,pathfinder_name,idea_id,benefit_id,pathfinder_potential_eqv,pathfinder_observation,pathfinder_quickwin,pathfinder_target_closure,pathfinder_status,pathfinder_progress,patfinder_actual_closure,pathfinder_date_raised,user_id)" +
"values ('" +pathfinder_id+ "','" +ideaname+ "','" +idea_id+ "','" +benefit_id+ "','" +benefitInt+ "','" +observation+ "','" +quickwin+ "','" +dates+ "','" +pathfinder_status+ "','" +pathfinder_prog+ "','" +dates+ "','" +dates+ "','" + user+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = "Added Successfully";
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
}
You can add or replace Fragment by calling this in your activity
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
more Fragment information check this http://developer.android.com/guide/components/fragments.html
To get data from you activity you can create a method in your activity
public dataType getData() {
return data;
}
in your fragment, you can get data by calling
((YourActivityClass) getActivity()).getData();
Hope this help!!
You are setting the Bundle to the Fragment, but where are you replacing/adding the Fragment? I can't see any FragmentTransaction.
Here you have some examples: http://developer.android.com/reference/android/app/Fragment.html
"DetailsActivity" is what you need, if I'm not wrong.
Example:
When you want to start your Fragment from the Activity:
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
getFragmentManager().beginTransaction().add(android.R.id.content, fragobj).commit();
Where android.R.id.content is the container for your Fragments. When you do this your Fragment will be shown and the Bundle will be received.
In your Fragment "onCreate":
if (getArguments() != null) {
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
}
Related
I am trying to make something like a chat app but of course i need my app to refresh newly added messages
,but this time i am using sql and not sqlite or firebase ,only normal mssql where i use jtds library but every time i use the below code and i add myAppAdapter.notifyDataSetChanged(); it doesn't show any data into my recycleview any help?
This is my onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
emojiButton = (ImageView)findViewById(R.id.emoji_button);
submitButton = (ImageView)findViewById(R.id.submit_button);
emojiconEditText = (EmojiconEditText)findViewById(R.id.emojicon_edit_text);
emojIconActions = new EmojIconActions(getApplicationContext(),activity_chat,emojiButton,emojiconEditText);
SyncData syncData = new SyncData();
syncData.SyncoData("");
syncData.execute();
//emojIconActions.ShowEmojicon();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
String editTextData = emojiconEditText.getText().toString();
SyncData orderdata = new SyncData();
orderdata.SyncData(editTextData);
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
orderdata.SyncoData("Insert into CustomerSupportChat values('" + formattedDate + "','" + editTextData + "','Customer','3','" + getIntent().getStringExtra("nameid") + "','1','1') ");
orderdata.execute();
emojiconEditText.setText("");
emojiconEditText.requestFocus();
}
catch(Exception e) {
Log.e("ActivityName", "Exception caused by editText " + e.toString());
}
}
});
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListChat>();
listOfMessage = (RecyclerView) findViewById(R.id.list_of_message);
}
this is were i get the data from the table:
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
String editTextData;
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
public void SyncData(String editTextData) {
this.editTextData = editTextData;
}
String inquery = "Insert into CustomerSupportChat values('" + formattedDate + "','" + editTextData + "','Customer','3','" + getIntent().getStringExtra("nameid") + "','1','1') ";
public void SyncoData(String inquery) {
this.inquery = inquery;
}
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(ChatActivity.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
System.out.println("it isssssssssssssssssssssssssssssssssssssssssaaaaaaaaaaaaaaaaaaaa" + formattedDate);
String query = inquery +
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID Where SenderType = 'Customer' ORDER BY MessageID DESC";
String query2 =
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID Where SenderType = 'Store'";
Statement stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
itemArrayList.clear();
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListChat(rs.getString("MessageText"), rs.getString("SenderType"), ""));
System.out.println("THEY AREEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE " + rs.getString("MessageDate") + " " + rs.getString("MessageText") + " " + rs.getString("SenderType") + " " + rs2.getString("MessageText"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
if ( rs2 != null){
while (rs2.next()){
itemArrayList.add(new ClassListChat("","Store",rs2.getString("MessageText")));
}
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg != null) {
Toast.makeText(ChatActivity.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
Toast.makeText(ChatActivity.this,"ERROR " + msg,Toast.LENGTH_LONG).show();
} else {
try {
MyAppAdapter appAdapter = new MyAppAdapter(itemArrayList,ChatActivity.this);
listOfMessage.setAdapter(appAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
linearLayoutManager.setReverseLayout(true);
listOfMessage.setLayoutManager(linearLayoutManager);
} catch (Exception ex) {
}
}
}
}
and this is my app adapter:
public class MyAppAdapter extends RecyclerView.Adapter<MyAppAdapter.ViewHolder>//has a class viewholder which holds
{
private ArrayList<ClassListChat> mOriginalValues; // Original Values
private ArrayList<ClassListChat> mDisplayedValues;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView messageText;
TextView messageStore;
TextView messageUser;
TextView messageTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
messageText = itemView.findViewById(R.id.message_text);
messageUser = itemView.findViewById(R.id.message_user);
messageTime = itemView.findViewById(R.id.message_time);
messageStore = itemView.findViewById(R.id.message_text_store);
}
}
public List <ClassListChat> parkingList;
public Context context;
ArrayList<ClassListChat> arraylist;
private MyAppAdapter(List<ClassListChat> apps, Context context) {
this.parkingList = apps;
this.context = context;
this.notifyDataSetChanged();
arraylist = new ArrayList<ClassListChat>();
arraylist.addAll(parkingList);
myAppAdapter.notifyDataSetChanged();
}
#Override
public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listcontentstorechat,parent,false);
ViewHolder viewHolder = new ViewHolder(rowView);
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontentstorechat, parent, false);
// here setting up names and images
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.messageText.setText(parkingList.get(position).getMessageText());
holder.messageUser.setText(parkingList.get(position).getMessageUser());
holder.messageStore.setText(parkingList.get(position).getMessageOther());
holder.messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", parkingList.get(position).getMessageTime()));
if (holder.messageText.getText().toString().equals("")){
holder.messageText.setVisibility(View.GONE);
}
if (holder.messageStore.getText().toString().equals("")){
holder.messageStore.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
if (arraylist != null)
return arraylist.size();
else
return 0;
}
}
}
I would really appreciate any hard work!
Your Asynctask code is proper change adapter code like below
Adapter
public class ViewHolder extends RecyclerView.ViewHolder {
TextView messageText;
TextView messageStore;
TextView messageUser;
TextView messageTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
messageText = itemView.findViewById(R.id.message_text);
messageUser = itemView.findViewById(R.id.message_user);
messageTime = itemView.findViewById(R.id.message_time);
messageStore = itemView.findViewById(R.id.message_text_store);
}
public List <ClassListChat> parkingList;
public Context context;
ArrayList<ClassListChat> arraylist;
private MyAppAdapter(List<ClassListChat> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListChat>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return arraylist.size();
}
#Override
public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listcontentstorechat,parent,false);
ViewHolder viewHolder = new ViewHolder(rowView);
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontentstorechat, parent, false);
// here setting up names and images
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.messageText.setText(parkingList.get(position).getMessageText());
holder.messageUser.setText(parkingList.get(position).getMessageUser());
holder.messageStore.setText(parkingList.get(position).getMessageOther());
holder.messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", parkingList.get(position).getMessageTime()));
if (holder.messageText.getText().toString().equals("")){
holder.messageText.setVisibility(View.GONE);
}
if (holder.messageStore.getText().toString().equals("")){
holder.messageStore.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
if (arraylist != null)
return arraylist.size();
else
return 0;
}
}
}
I am using MySQL as a bank hosted on an AWS server
I use the AsyncTask class to login, doing the search with SELECT * from ... I check the search with ResultSet, the code executes quietly, but when I click the Login button, it goes into exception.
I use the same code to insert data into the database and it performs right
Only verification is not right
public class Tela_Login extends AppCompatActivity {
ConnectionClass connectionClass;
EditText editUsuario, editSenha;
Button btLogin;
TextView textCadastro;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela__login);
ConnectionClass connectionClass;
editUsuario = (EditText) findViewById(R.id.editUsuario);
editSenha = (EditText) findViewById(R.id.editSenha);
textCadastro = (TextView) findViewById(R.id.textCadastro);
btLogin = (Button) findViewById(R.id.btLogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
realizarLogin realizarLogin = new realizarLogin();
btLogin.setClickable(false);
realizarLogin.execute("");
}
});
}
public class realizarLogin extends AsyncTask<String,String,String>{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(Tela_Login.this, r, Toast.LENGTH_SHORT).show();
if (isSuccess) {
Toast.makeText(Tela_Login.this, r, Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
String usuario = editUsuario.getText().toString();
String senha = editSenha.getText().toString();
if (usuario.trim().equals("") || senha.trim().equals(""))
z = "Por favor os valores!";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Erro ao conectar no banco de dados";
} else {
String query = "select * from Salao where email='" +usuario+"' and senha='" +senha+"'";
Statement stmt = con.createStatement();
ResultSet rs;
rs = stmt.executeQuery(query);
if (rs.next()) {
z = "Login sucessful";
isSuccess = true;
} else {
z = "Invalid Credentials";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
}
}
btLogin.setClickable(true);
return z;
}
}
}
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.
I'm currently having trouble of updating a user profile after they have login. The table i have is different but is linked together, which mean i get the Username from another table and update the profile details on another table. Here is my php and java file. Additionally, i'm not really good at android and php coding, any guidance will be much appreciated!
UpdateProfile.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if( !empty( $_POST ) )
{
$connect = mysqli_connect("localhost", "root", "", "users");
$Username = $_POST['Username'];
$Dri_IC = $_POST["Dri_IC"];
$Dri_Name = $_POST["Dri_Name"];
$Date_of_Birth = $_POST["Date_of_Birth"];
$Carplate = $_POST["Carplate"];
$Dri_Street_Add = $_POST["Dri_Street_Add"];
$Dri_Postal_Code = $_POST["Dri_Postal_Code"];
$Dri_City = $_POST["Dri_City"];
$Dri_State = $_POST["Dri_State"];
$Dri_Country = $_POST["Dri_Country"];
$statement = mysqli_prepare($connect, "UPDATE dri_details SET Dri_IC='$Dri_IC', Dri_Name='$Dri_Name', Date_of_Birth='$Date_of_Birth',
Carplate='$Carplate', Dri_Street_Add='$Dri_Street_Add', Dri_Postal_Code='$Dri_Postal_Code', Dri_City='$Dri_City', Dri_State='$Dri_State', Dri_Country='$Dri_Country'
INNER JOIN account_details ON account_details.Acc_ID = dri_details.Dri_ID WHERE account_details.Username='$Username'");
mysqli_stmt_bind_param($statement, "sissssssss", $Username, $Dri_IC, $Dri_Name, $Date_of_Birth, $Carplate, $Dri_Street_Add, $Dri_Postal_Code, $Dri_City, $Dri_State, $Dri_Country);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
}
?>
ProfileUpdate.java
public class ProfileUpdate extends AppCompatActivity {
private EditText editTextDriIC, editTextDriName;
private Button buttonUpPro;
private TextView tvDisplay;
SessionManager session;
public static String global_Usernames;
public static String global_AccPass;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Session class instance
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// get name
String Username = user.get(SessionManager.KEY_USERNAME);
global_Usernames = Username;
// get password
String Acc_Pass = user.get(SessionManager.KEY_PASSWORD);
global_AccPass = Acc_Pass;
final EditText etIdentitycard = (EditText) findViewById(R.id.etIdentitycard);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etDOB = (EditText) findViewById(R.id.etDOB);
final EditText etCarplate = (EditText) findViewById(R.id.etCarplate);
final EditText etAddress = (EditText) findViewById(R.id.etAddress);
final EditText etPostal = (EditText) findViewById(R.id.etPostal);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etCity = (AutoCompleteTextView) findViewById(R.id.etCity);
// Get the string array
String[] cities = getResources().getStringArray(R.array.city_array);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cities);
etCity.setAdapter(adapter);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etState = (AutoCompleteTextView) findViewById(R.id.etState);
// Get the string array
String[] states = getResources().getStringArray(R.array.state_array);
// Create the adapter and set it to the AutoCompleteTextView
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, states);
etState.setAdapter(adapter);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etCountry = (AutoCompleteTextView) findViewById(R.id.etCountry);
// Get the string array
String[] country = getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, country);
etCountry.setAdapter(adapter);
final Button buttonUpPro = (Button) findViewById(R.id.bUpdate);
final Calendar myCalendar = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
private void updateLabel() {
//String myFormat = "YYYY/MM/DD"; //In which you need put here
//DateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
String myFormat = "yyyy/MM/dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
//DateFormat sdf = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
etDOB.setText(sdf.format(myCalendar.getTime()));
}
};
etDOB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(ProfileUpdate.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
buttonUpPro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Dri_IC = etIdentitycard.getText().toString().trim();
final String Dri_Name = etName.getText().toString().trim();
final String Date_of_Birth = etDOB.getText().toString();
final String Carplate = etCarplate.getText().toString().trim();
final String Dri_Street_Add = etAddress.getText().toString().trim();
final String Dri_Postal_Code = etPostal.getText().toString().trim();
final String Dri_City = etCity.getText().toString().trim();
final String Dri_State = etState.getText().toString().trim();
final String Dri_Country = etCountry.getText().toString().trim();
if (etIdentitycard.getText().toString().matches("") || etName.getText().toString().matches("") || etDOB.getText().toString().matches("") || etAddress.getText().toString().matches("")
|| etPostal.getText().toString().matches("") || etCity.getText().toString().matches("") || etState.getText().toString().matches("") || etCountry.getText().toString().matches("")) {
if (TextUtils.isEmpty(Dri_IC)) {
etIdentitycard.setError("You are required to enter your Identification Card Number");
}
if (TextUtils.isEmpty(Dri_Name)) {
etName.setError("You are required to enter your Full Name");
}
if (TextUtils.isEmpty(Date_of_Birth)) {
etDOB.setError("You are required to enter your Date of Birth");
}
if (TextUtils.isEmpty(Dri_Street_Add)) {
etAddress.setError("You are required to enter your House Address");
}
if (TextUtils.isEmpty(Dri_Postal_Code)) {
etPostal.setError("You are required to enter your Postal Code");
}
if (TextUtils.isEmpty(Dri_City)) {
etCity.setError("You are required to enter City name");
}
if (TextUtils.isEmpty(Dri_State)) {
etState.setError("You are required to enter State name");
}
if (TextUtils.isEmpty(Dri_Country)) {
etCountry.setError("You are required to enter Country name");
}
} else {
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
/*if (success){
Intent intent = new Intent(RegisterActivity2.this, LoginActivity.class);
RegisterActivity2.this.startActivity(intent);
}*/
if (!success){
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileUpdate.this);
builder.setMessage("Retry")
.setNegativeButton("Retry", null)
.create()
.show();
} else {
Toast.makeText(ProfileUpdate.this, getString(R.string.profile_update_success), Toast.LENGTH_LONG).show();
//Intent intent = new Intent(RegisterActivity2.this, LoginActivity.class);
//RegisterActivity2.this.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ProfileUpdateRequest profileUpdateRequest = new ProfileUpdateRequest(Dri_IC, Dri_Name, Date_of_Birth, Carplate, Dri_Street_Add, Dri_Postal_Code, Dri_City, Dri_State, Dri_Country, responeListener);
RequestQueue queue = Volley.newRequestQueue(ProfileUpdate.this);
queue.add(profileUpdateRequest);
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
ProfileUpdateRequest.java
public class ProfileUpdateRequest extends StringRequest {
private static final String PROFILEUPDATE_REQUEST = "http://192.168.1.5/UpdateProfile.php";
private Map<String, String> params;
public ProfileUpdateRequest(String Dri_IC, String Dri_Name, String Date_of_Birth, String Carplate, String Dri_Street_Add, String Dri_Postal_Code, String Dri_City, String Dri_State, String Dri_Country, Response.Listener<String> listener){
super (Method.POST, PROFILEUPDATE_REQUEST, listener, null);
Log.i("Getting url info",""+PROFILEUPDATE_REQUEST + " " + Dri_IC + " " + Dri_Name + " " + Date_of_Birth);
params = new HashMap<>();
params.put("Dri_IC", Dri_IC + "");
params.put("Dri_Name", Dri_Name);
params.put("Date_of_Birth", Date_of_Birth);
params.put("Carplate", Carplate);
params.put("Dri_Street_Add", Dri_Street_Add);
params.put("Dri_Postal_Code", Dri_Postal_Code);
params.put("Dri_City", Dri_City);
params.put("Dri_State", Dri_State);
params.put("Dri_Country", Dri_Country);
params.put("Username", MainActivity.global_Username);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
I'm not sure what went wrong, after i click update on my android, it did not show success or error, and the database did not update as well. Any help will be much appreciated!
I'm trying to do my first app, I'm self-taught in Java and I started 2 month ago so please forgive my errors.
I want to pass the CheckBoxes values to an email text but I think I need to refresh "something" before sending the email because the values are always false..and I don't know how can I do.
Here is the code:
public class Appuntamento extends Activity{
String paziente;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final boolean lun = lunedi.isSelected();
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final boolean mar = martedi.isSelected();
final CheckBox mercoledi = (CheckBox) findViewById(R.id.checkboxMercoledi);
final boolean mer = mercoledi.isSelected();
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final boolean giov = giovedi.isSelected();
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
final boolean ven = venerdi.isSelected();
StringBuilder testoMail = new StringBuilder();
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
final String giorni = testoMail.toString();
Button richiestaAppuntamento = (Button)findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}
two way you can do this one
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ven = venerdi.isChecked();
lun = lunedi.isChecked();
mar = martedi.isChecked();
mer = mercoledi.isChecked();
giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}
other way is
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
lunedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
lun=isChecked;
//either one above or below
//lun = lunedi.isChecked();
}
}
);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
martedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mar=isChecked;
//either one above or below
//mar = martedi.isChecked();
}
}
);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
mercoledi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mer=isChecked;
//either one above or below
// mer = mercoledi.isChecked();
}
}
);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
giovedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
giov=isChecked;
//either one above or below
// giov = giovedi.isChecked();
}
}
);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
venerdi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
ven=isChecked;
//either one above or below
//ven = venerdi.isChecked();
}
}
);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ven = venerdi.isChecked();
// lun = lunedi.isChecked();
// mar = martedi.isChecked();
// mer = mercoledi.isChecked();
// giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}