getExtra Interface with Intent - java

I want to move Interface array called DisplayItem
this is activity1 code:
package com.example.eranp.clientpage;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Main2Activity extends Activity implements Serializable{
private EditText pro_device_det;
private Button saveDataBase, btnViewAll ;
private DatabaseReference databaseCustomer, databaseDevice, databaseProblem, db;
private Spinner spinner;
private String option1, option2,option3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main3);
db = FirebaseDatabase.getInstance().getReference();
databaseCustomer = FirebaseDatabase.getInstance().getReference("customer");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
option1 = getResources().getString(R.string.option1u);
option2 = getResources().getString(R.string.option2u);
option3 = getResources().getString(R.string.option3u);
saveDataBase = (Button) findViewById(R.id.save_btn);
btnViewAll = (Button)findViewById(R.id.button_viewAll);
final List<String> list = new ArrayList<String>();
list.add(option1);
list.add(option2);
list.add(option3);
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
pro_device_det = (EditText) findViewById(R.id.pro_device_det);
final Intent intent = getIntent();
final String fName = intent.getStringExtra("fName");
final String lName = intent.getStringExtra("lName");
final String phone = intent.getStringExtra("phone");
final String email = intent.getStringExtra("email");
final String modelDevice = intent.getStringExtra("modelDevice");
final String nameDevice = intent.getStringExtra("nameDevice");
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String proDeviceDet = pro_device_det.getText().toString().trim();
String shortProDeviceDet = string3Words(proDeviceDet);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
if (!TextUtils.isEmpty(proDeviceDet)) {
String id = databaseCustomer.push().getKey();
Customer customer = new Customer(id, fName, lName, email, phone);
databaseCustomer.child(id).setValue(customer);
Device device = new Device(id, nameDevice, modelDevice);
databaseDevice.child(id).setValue(device);
int urgency = spinnerUrgency(spinner);
Problem problem = new Problem(id, date, proDeviceDet, urgency, shortProDeviceDet);
databaseProblem.child(id).setValue(problem);
DisplayItem[] displayItem= new DisplayItem[]{customer, problem};
final int REQ_CODE = 1;
Intent intent2 = new Intent(Main2Activity.this, CustomersPage.class);
intent2.putExtra("DisplayItem",displayItem);
startActivity(intent2);
Toast.makeText(Main2Activity.this , "Customer added", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Main2Activity.this, "Please write on an empty cell", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
}
The Interface code:
package com.example.eranp.clientpage;
import java.io.Serializable;
/**
* Created by Eran P on 15/04/2018.
*/
public interface DisplayItem extends Serializable {
}
this is the second activity that I want to move the interface code:
package com.example.eranp.clientpage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class CustomersPage extends Activity {
ListView listViewCustomers;
List<Customer> customers;
List<Problem> problems;
List<Device> devices;
DatabaseReference databaseCustomers, databaseProblem, databaseDevice,db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customers_page);
db = FirebaseDatabase.getInstance().getReference();
databaseCustomers = FirebaseDatabase.getInstance().getReference("customer");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
listViewCustomers = (ListView)findViewById(R.id.listViewCostumers);
customers = new ArrayList<>();
devices = new ArrayList<>();
problems = new ArrayList<>();
Intent intentl = getIntent();
listViewCustomers.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Customer customer = customers.get(i);
showUpdateDeleteDialog(customer.getCustomerId(), customer.getfName() + " " + customer.getlName());
return true;
}
});
listViewCustomers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Customer customer = customers.get(i);
Problem problem = problems.get(i);
Device device = devices.get(i);
Intent intent = new Intent(CustomersPage.this, ClientPageData.class);
intent.putExtra("fName", customer.getfName());
intent.putExtra("lName", customer.getlName());
intent.putExtra("phone", customer.getPhoneNum());
intent.putExtra("email", customer.geteMail());
intent.putExtra("problemShort", problem.getProDeviceDet());
intent.putExtra("nameDevice", device.getDeviceName());
intent.putExtra("modelDevice", device.getDeviceModel());
startActivity(intent);
}
});
}
private void showUpdateDeleteDialog(final String customerId, String customerName) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextFName = (EditText) dialogView.findViewById(R.id.ET_fName);
final EditText editTextLName = (EditText) dialogView.findViewById(R.id.ET_lName);
final EditText editTextPhone = (EditText) dialogView.findViewById(R.id.ET_phone);
final EditText editTextEmail = (EditText) dialogView.findViewById(R.id.ET_email);
final EditText editTextProDetDev = (EditText) dialogView.findViewById(R.id.ET_proDetDevice);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist);
dialogBuilder.setTitle(customerName);
final AlertDialog b = dialogBuilder.create();
b.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String fName = editTextFName.getText().toString().trim();
String lName = editTextLName.getText().toString().trim();
String phone = editTextPhone.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String proDetDevice = editTextProDetDev.getText().toString().trim();
if (!TextUtils.isEmpty(fName)) {
updateCustomer(customerId, fName, lName,phone,email, proDetDevice);
b.dismiss();
}
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteCustomer(customerId);
}
});
}
private boolean deleteCustomer(String id) {
//getting the specified Customer reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("customer").child(id);
DatabaseReference dRP = FirebaseDatabase.getInstance().getReference("device").child(id);
DatabaseReference dRD = FirebaseDatabase.getInstance().getReference("problem").child(id);
//removing Customer
dR.removeValue();
dRP.removeValue();
dRD.removeValue();
Toast.makeText(getApplicationContext(), "Customer Deleted", Toast.LENGTH_LONG).show();
return true;
}
private boolean updateCustomer(String id, String fName, String lName, String phone, String email, String proDetDevice) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("customer").child(id);
DatabaseReference dRp = FirebaseDatabase.getInstance().getReference("problem").child(id);
//updating artist
Customer customer= new Customer(id, fName, lName, email,phone);
dR.setValue(customer);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
String shortProDeviceDet = string3Words(proDetDevice);
Problem problem= new Problem(id, date,proDetDevice,0, shortProDeviceDet );
dRp.setValue(problem);
Toast.makeText(getApplicationContext(), "Customer Updated", Toast.LENGTH_LONG).show();
return true;
}
//attaching value event listener
databaseCustomers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
customers.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting customer
Customer customer = postSnapshot.getValue(Customer.class);
//adding customer to the list
customers.add(customer);
}
Intent intent2 = getIntent();
DisplayItem [] displayItem = (DisplayItem[]) intent2.getExtras().getSerializable("DisplayItem");
//creating adapter
CustomerAdapter customerAdapter = new CustomerAdapter(CustomersPage.this,displayItem );
//attaching adapter to the listview
listViewCustomers.setAdapter(customerAdapter);
}
}
when I tried to run the app this crashed and in the log file he says error in this line:
DisplayItem [] displayItem = (DisplayItem[])
intent2.getExtras().getSerializable("DisplayItem");
Thank you very much for helping!

Your code is not too clear but try use this format:
//When you want to pass an array as intent:
private ArrayList<String> arrayList = new ArrayList<String>();
Intent intent = new Intent();
intent.putStringArrayListExtra("data", arrayList);
startActivity(intent);
// To receive intent in the second activity
private ArrayList<String> newArrayList = new ArrayList<String>();
newArrayList = getIntent.getStringArrayListExtra("data");

Check if your classes Device and Customer implements serializable

Related

How to get data from a Dialog RecyclerView to its Hosted Activity?

Hi there I am having a trouble to get back text from the recycler View inside the dialog.
Somebody please help to get the data from dialog view to the same activity.
My data flow is:
MainActivity --> UserDetailsActivity --> dialog (RecyclerView)--->UserDetailsActivity ---> Updatebutton
what happening now is :
MainActivity --> UserDetailsActivity --> dialog (RecyclerView)--->App Crashes!!
what i want is to return the Tax include Money to the rent TextView
Below is my code to UserDetailsActivity.
UserDetailsActivity.Java
package com.ancorp.aplo.activity;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.telephony.SmsManager;
import android.widget.Toast;
import com.ancorp.aplo.R;
import com.ancorp.aplo.adapter.ChannelAdapter;
import com.ancorp.aplo.database.SqliteDatabase;
import com.ancorp.aplo.model.Contacts;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.time.Month;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class UserDetailsActivity extends AppCompatActivity {
private final static int SEND_SMS_PERMISSION_REQ=1;
public TextView textView ;
EditText name_edit;
EditText jacode_edit;
EditText phone_edit;
EditText balance_edit , paidDate_edit, paidAmount_edit, rent_edit, zone_edit;
SqliteDatabase myDB;
String header,data1,data2,timeStamp;
String month;
private Context context;
float amount;
Integer d1,d2;
Integer y;
TextView phone_text,btnRecharge, Activation, Deactivation , rent_text , zone_text,plan_text,name_text,jacode_text, Status_text, id_text;
TextView balance_text, LastPaidAmount,LastPaidDate;
int deactive = Color.RED;
int activeg = Color.GREEN;
Button btnEdit;
String id,balance, Lpdate, LpAmount,zone,rent;
String phoneNo,message;
String Status;
Button btndelete ;
ImageView editimgbtn,addimgbtn;
Spinner pkgname;
String SpinnerData;
String planAmount,chName,chId,chMoney;
private static int ACTIVE_CODE = 0;
private static int DEACTIVE_CODE = 0;
private SqliteDatabase mDatabase;
private ArrayList<Contacts> userData;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button recharges;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
mDatabase = new SqliteDatabase(this);
// getUserData(id);
ActionBar actionBar = getSupportActionBar();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
actionBar.setTitle("Customer Details");
name_edit = findViewById(R.id.user_name);
jacode_edit = findViewById(R.id.name_jacode);
phone_edit = findViewById(R.id.name_phone);
balance_edit = findViewById(R.id.name_balance);
paidAmount_edit = findViewById(R.id.LastPaidAmount_edit);
paidDate_edit = findViewById(R.id.lastPaidDate_edit);
rent_edit = findViewById(R.id.name_rent);
zone_edit =findViewById(R.id.name_zone);
pkgname= findViewById(R.id.name_package);
id_text = findViewById(R.id.id);
name_text= findViewById(R.id.user_name_text);
Status_text = findViewById(R.id.cid);
phone_text= findViewById(R.id.name_phone_text);
jacode_text= findViewById(R.id.name_jacode_text);
balance_text =findViewById(R.id.name_balance_text);
LastPaidAmount = findViewById(R.id.LastPaidAmount_text);
LastPaidDate = findViewById(R.id.lastPaidDate_text);
rent_text = findViewById(R.id.name_rent_text);
zone_text = findViewById(R.id.name_zone_text);
plan_text = findViewById(R.id.name_package_text);
Activation = findViewById(R.id.Activate);
Deactivation = findViewById(R.id.DeActivate);
//rent_edit = findViewById(R.id.name_rent);
//zone_edit = findViewById(R.id.name_zone);
addimgbtn = findViewById(R.id.addimgbtn);
btnEdit=findViewById(R.id.btnEdit);
btndelete = findViewById(R.id.btnDelete);
btnRecharge = findViewById(R.id.btnRecharge);
editimgbtn = findViewById(R.id.editbtnimg);
addimgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddChannel(UserDetailsActivity.this);
}
});
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTask();
}
});
btnRecharge.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View v) {
rechargeUser();
}
});
editimgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadSpinnerData();
name_edit.setVisibility(View.VISIBLE);
phone_edit.setVisibility(View.VISIBLE);
jacode_edit.setVisibility(View.VISIBLE);
balance_edit.setVisibility(View.VISIBLE);
paidAmount_edit.setVisibility(View.VISIBLE);
paidDate_edit.setVisibility(View.VISIBLE);
btndelete.setVisibility(View.VISIBLE);
btnEdit.setVisibility(View.VISIBLE);
rent_edit.setVisibility(View.VISIBLE);
zone_edit.setVisibility(View.VISIBLE);
pkgname.setVisibility(View.VISIBLE);
name_text.setVisibility(View.GONE);
phone_text.setVisibility(View.GONE);
jacode_text.setVisibility(View.GONE);
balance_text.setVisibility(View.GONE);
LastPaidAmount.setVisibility(View.GONE);
LastPaidDate.setVisibility(View.GONE);
btnRecharge.setVisibility(View.GONE);
rent_text.setVisibility(View.GONE);
zone_text.setVisibility(View.GONE);
plan_text.setVisibility(View.GONE);
// rechargebtn.setVisibility(View.GONE);
}
});
Intent intent =getIntent();
if (intent.getExtras() != null){
Contacts contacts = (Contacts) intent.getSerializableExtra("data");
id = getIntent().getStringExtra("id");
balance = getIntent().getStringExtra("balance");
Lpdate = getIntent().getStringExtra("LPDATE");
LpAmount = getIntent().getStringExtra("lpAmount");
zone = getIntent().getStringExtra("zone");
rent = getIntent().getStringExtra("rent");
Status_text.setText(contacts.getStatus());
Status = contacts.getStatus();
chId=getIntent().getStringExtra("channelID");
chName = getIntent().getStringExtra("channelName");
chMoney = getIntent().getStringExtra("channelMoney");
Toast.makeText(getApplicationContext(), chId , Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), chName , Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), chMoney , Toast.LENGTH_SHORT).show();
id_text.setText(id);
name_edit.setText(contacts.getName());
phone_edit.setText(contacts.getPhno());
jacode_edit.setText(contacts.getJacode());
balance_edit.setText(contacts.getBalance());
rent_edit.setText(rent);
zone_edit.setText(zone);
// plan_edit.setText(contacts.getCplan());
// balance_edit.setText(balance);
// paidDate_edit.setText(contacts.getPaidDate());
paidDate_edit.setText(Lpdate);
// paidAmount_edit.setText(contacts.getPaidAmount());
paidAmount_edit.setText(LpAmount);
// LastPaidDate.setText(contacts.getPaidDate());
LastPaidDate.setText(Lpdate);
//LastPaidAmount.setText(contacts.getPaidAmount());
LastPaidAmount.setText(LpAmount);
name_text.setText(contacts.getName());
phone_text.setText(contacts.getPhno());
jacode_text.setText(contacts.getJacode());
balance_text.setText(contacts.getBalance());
rent_text.setText(rent);
zone_text.setText(zone);
plan_text.setText(contacts.getCplan());
//balance_text.setText(balance);
header = name_edit.getText().toString();
}
pkgname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
SqliteDatabase mydb = new SqliteDatabase(UserDetailsActivity.this);
SpinnerData = (String) adapterView.getItemAtPosition(i).toString();
planAmount = mydb.getPlanAmount(SpinnerData);
// Toast.makeText(getApplicationContext(),planAmount,Toast.LENGTH_SHORT).show();
rent_edit.setText(planAmount);
rent_text.setText(planAmount);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
String active ="Active";
String deac = "Deactive";
if (Status.equals(active) == true){
Activation.setVisibility(View.GONE);
Deactivation.setVisibility(View.VISIBLE);
ACTIVE_CODE =1;
}
else {
ACTIVE_CODE =2;
Activation.setVisibility(View.VISIBLE);
Deactivation.setVisibility(View.GONE);
}
Activation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
String timeStamps = simpleDateFormat.format(new Date()) ;
String statu ="Active";
String stats = "Activated On ";
String name = name_text.getText().toString();
mDatabase.statusUpdate(id ,statu);
mDatabase.statusDetails(id , name,stats,timeStamps);
Status_text.setText(statu);
Activation.setVisibility(View.GONE);
Deactivation.setVisibility(View.VISIBLE);
}
});
Deactivation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String statu ="Deactive";
String stats = "DeActivated On ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
String timeStamps = simpleDateFormat.format(new Date()) ;
String name = name_text.getText().toString();
mDatabase.statusUpdate(id ,statu);
mDatabase.statusDetails(id , name,stats,timeStamps);
Status_text.setText(statu);
Activation.setVisibility(View.VISIBLE);
Deactivation.setVisibility(View.GONE);
}
});
}
private void AddChannel(UserDetailsActivity activity) {
dialog = new Dialog(activity);
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.channel_selection);
myDB = new SqliteDatabase(this);
// myDB.getChannel();
channel_id = new ArrayList<>();
channel_name = new ArrayList<>();
channel_ntMoney = new ArrayList<>();
channel_tMoney = new ArrayList<>();
Cursor cursor = myDB.getChannel();
if (cursor.getCount()==0){
Toast.makeText(this, "No Plans Have Added yet ", Toast.LENGTH_SHORT).show();
}else {
while (cursor.moveToNext()){
channel_id.add(cursor.getString(0));
channel_name.add(cursor.getString(1));
channel_ntMoney.add(cursor.getString(2));
channel_tMoney.add(cursor.getString(3));
}
}
RecyclerView recyclerView = dialog.findViewById(R.id.channelRecyclerView);
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney);
recyclerView.setAdapter(cAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
dialog.show();
}
private void editTask() {
final String name = name_edit.getText().toString();
final String id = id_text.getText().toString();
final String rent = rent_edit.getText().toString();
final String zone = zone_edit.getText().toString();
final String ph_no = phone_edit.getText().toString();
final String jacode = jacode_edit.getText().toString();
final String balance = balance_edit.getText().toString();
final String plan = SpinnerData;
if (TextUtils.isEmpty(name)) {
Toast.makeText(getApplicationContext(),"Something Went Wrong",Toast.LENGTH_SHORT).show();
} else {
// Contacts newContact = new Contacts(Objects.requireNonNull(contacts).getId(),name, ph_no,jacode,balance);
//mDatabase.updateContacts(newContact);
mDatabase.updateContacts(id,name, ph_no,jacode,balance,rent,zone,plan);
name_edit.setText(name);name_text.setText(name);
phone_edit.setText(ph_no);phone_text.setText(ph_no);
rent_text.setText(rent);rent_edit.setText(rent);
jacode_edit.setText(jacode);jacode_text.setText(jacode);
balance_edit.setText(balance);balance_text.setText(balance);
zone_text.setText(zone);zone_edit.setText(zone);
plan_text.setText(plan);//pkgname.set(plan);
name_edit.setVisibility(View.GONE);
phone_edit.setVisibility(View.GONE);
jacode_edit.setVisibility(View.GONE);
rent_edit.setVisibility(View.GONE);
balance_edit.setVisibility(View.GONE);
paidAmount_edit.setVisibility(View.GONE);
paidDate_edit.setVisibility(View.GONE);
btndelete.setVisibility(View.GONE);
btnEdit.setVisibility(View.GONE);
zone_edit.setVisibility(View.GONE);
pkgname.setVisibility(View.GONE);
name_text.setVisibility(View.VISIBLE);
rent_text.setVisibility(View.VISIBLE);
zone_text.setVisibility(View.VISIBLE);
phone_text.setVisibility(View.VISIBLE);
jacode_text.setVisibility(View.VISIBLE);
balance_text.setVisibility(View.VISIBLE);
LastPaidAmount.setVisibility(View.VISIBLE);
LastPaidDate.setVisibility(View.VISIBLE);
btnRecharge.setVisibility(View.VISIBLE);
plan_text.setVisibility(View.VISIBLE);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void rechargeUser() {
final AlertDialog builder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.recharge,null);
builder.setTitle("Recharge " + header);
final EditText rechargeField = (EditText) dialogView.findViewById(R.id.rechargeEditText);
final Button cancel = (Button) dialogView.findViewById(R.id.btnCancelRecharge);
recharges = (Button) dialogView.findViewById(R.id.btnRechargeSucess);
recharges.setEnabled(false);
if(checkPermission(Manifest.permission.SEND_SMS))
{
recharges.setEnabled(true);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQ);
}
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Cancelled Recharge !!",Toast.LENGTH_LONG).show();
builder.dismiss();
}
});
recharges.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d1 = Integer.valueOf(rechargeField.getText().toString().trim());
d2 = Integer.valueOf(balance_edit.getText().toString().trim());
amount= d2 - d1;
data1 = String.valueOf(amount);
data2 = String.valueOf(d1);
String name = String.valueOf(name_text.getText().toString().trim());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
timeStamp = simpleDateFormat.format(new Date()) ;
String cdate = date.format(new Date());
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH,Calendar.LONG, Locale.UK);
int year = Calendar.getInstance().get(Calendar.YEAR);
String due= balance_text.getText().toString().trim();
String paid = String.valueOf(d1);
//Toast.makeText(getApplicationContext(),month,Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),String.valueOf(year),Toast.LENGTH_SHORT).show();
mDatabase.rechargeUser(id, (int) amount,d1,timeStamp);
mDatabase.InsertPaymentDetails(id,month,year,timeStamp,paid,due);
mDatabase.collectionDetails(id,name,d1,cdate,month,year);
reloadData();
sendSms();
builder.dismiss();
}
});
builder.setView(dialogView);
builder.show();
}
private void sendSms() {
String names = name_text.getText().toString();
String s1=phone_text.getText().toString();
String s2=("Hi "+names+", You have Successfully recharged ₹ " +d1 +" to your SKY VISION Cable account on "+timeStamp+". Your current balance is ₹ "+amount+" . Kindly clear your balance on time without any due. \n - Thank you! \n SKY VISION KONGAD");
if(!TextUtils.isEmpty(s1)&&!TextUtils.isEmpty(s2))
{
if(checkPermission(Manifest.permission.SEND_SMS))
{
SmsManager smsManager= SmsManager.getDefault();
ArrayList<String> part = smsManager.divideMessage(s2);
smsManager.sendMultipartTextMessage(s1,null,part,null,null);
}
else {
Toast.makeText(UserDetailsActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(UserDetailsActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
private void reloadData() {
balance_text.setText(data1);
balance_edit.setText(data1);
LastPaidAmount.setText(data2);
LastPaidDate.setText(timeStamp);
paidAmount_edit.setText(data2);
paidDate_edit.setText(timeStamp);
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.user_details, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.payment_details:
Intent intent = new Intent(this,PaymentDetailsActivity.class);
intent.putExtra("ID",id);
startActivity(intent);
break;
case R.id.WriteOff:
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Write Off?");
builder.setMessage("Are you sure you want to Write off ?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
WriteOff();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
break;
case R.id.boxDetails:
Intent boxDetails = new Intent(this,BoxDetailsActivity.class);
boxDetails.putExtra("ID",id);
startActivity(boxDetails);
break;
}
return super.onOptionsItemSelected(item);
}
private void WriteOff() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
timeStamp = simpleDateFormat.format(new Date()) ;
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH,Calendar.LONG, Locale.UK);
int year = Calendar.getInstance().get(Calendar.YEAR);
String due= balance_text.getText().toString().trim();
String paid = "Write Off";
balance_text.setText("0");
balance_edit.setText("0");
String Writeofbalance ="0";
mDatabase.writeOff(id, month , year , timeStamp , paid , due, Writeofbalance);
}
private boolean checkPermission(String sendSms) {
int checkpermission= ContextCompat.checkSelfPermission(this,sendSms);
return checkpermission== PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case SEND_SMS_PERMISSION_REQ:
if(grantResults.length>0 &&(grantResults[0]== PackageManager.PERMISSION_GRANTED))
{
btnRecharge.setEnabled(true);
}
break;
}
}
private void loadSpinnerData() {
SqliteDatabase db = new SqliteDatabase(getApplicationContext());
List<String> labels = db.getAllPlansSpinner();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,labels);
arrayAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
pkgname.setAdapter(arrayAdapter);
}
ArrayList<String> channel_id,channel_name,channel_ntMoney,channel_tMoney;
ChannelAdapter cAdapter;
public static Dialog dialog;
}
here is my ChannelAdapterActivity
ChannelAdapterActivity.Java
package com.ancorp.aplo.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ancorp.aplo.R;
import com.ancorp.aplo.activity.UserDetailsActivity;
import com.ancorp.aplo.model.Contacts;
import java.util.ArrayList;
public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.MyViewHolder> {
private Context context;
private Activity activity;
private ArrayList<Contacts> allChannels;
String id,name,money;
private ArrayList channel_id,channel_name,channel_ntMoney,channel_tMoney;
public ChannelAdapter(Activity activity, Context context, ArrayList<String> channel_id, ArrayList<String> channel_name, ArrayList<String> channel_ntMoney, ArrayList<String> channel_tMoney) {
this.context = context;
this.activity = activity;
this.channel_id = channel_id;
this.channel_name=channel_name;
this.channel_ntMoney= channel_ntMoney;
this.channel_tMoney= channel_tMoney;
}
public ChannelAdapter(Context context, ArrayList<Contacts> allChannel) {
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater .inflate(R.layout.channel_list,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
holder.channelName.setText(String.valueOf(channel_name.get(i)));
holder.channelNt.setText(String.valueOf(channel_ntMoney.get(i)));
holder.channelT.setText(String.valueOf(channel_tMoney.get(i)));
id = String.valueOf(channel_id.get(i));
name=String.valueOf(channel_name.get(i));
money = String.valueOf(channel_tMoney.get(i));
}
#Override
public int getItemCount() {
return channel_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView channelName,channelNt,channelT;
LinearLayout channelLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
channelName = itemView.findViewById(R.id.channelName);
channelNt = itemView.findViewById(R.id.ntMoney);
channelT = itemView.findViewById(R.id.tMoney);
channelLayout = itemView.findViewById(R.id.channelMainLayout);
}
}
}
Somebody please help me I am Newbie to this.
This is another method of sending data from Adapter to Activity.
Follow these steps carefully:
Create an interface with a method
public interface InterfaceTax {
public void getTaxMoney(int amount);
}
the parameters of the method should contain the data you want to send back to the activity.
Create a variable for that interface in the Adapter and add the interface to the constructor of the Adapter.
private InterfaceTax interfaceT;
public ChannelAdapter(/* other parameters */, InterfaceTax interface) {
interfaceT = interface;
}
Then in onBindViewHolder (or wherever your data is) call the method of the interface and send the data
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
money = String.valueOf(channel_tMoney.get(i));
interface.getTaxMoney(money);
}
Then in your activity implement the interface and override the method to receive data
public class UserDetailsActivity extends AppCompatActivity implements InterfaceTax {}
#Override
public void getTaxMonney(int data) {
// receive data here
}
In your AddChannel method, replace this line
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney);
with this
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney, this);
This will automatically send the data from the adapter to the activity and you can receive it in the method overridden in the activity.

Firebase chat app not displaying messages like whatsapp does

I am trying to come up with a chat app using Firebase Recycler adapter. The problem is that the sender's and receiver's chats are not displayed as expected. All the chats are displayed on the right. Despite the text being "Morning", the text is displayed as "Hello".
Below is my code
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ultramodern.activity.besha.Adapter.MessageAdapter;
import ultramodern.activity.besha.Model.Chat;
import ultramodern.activity.besha.Model.Users;
public class Complete_new_Group extends AppCompatActivity implements View.OnClickListener{
Button fab,paybtn, depobtn, borrowbtn, borrowicon, depoicon, payicon;
CircleImageView sendtextbutton;
EditText text_send;
RecyclerView chatrecyclerView;
MessageAdapter messageAdapter;
public static final int MESSAGE_RIGHT=0;
public static final int MESSAGE_LEFT=1;
//private String user_id;
#Override
protected void onCreate(Bundle savedInstanceState) { ;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete_new__group);
Toast.makeText(this, "This area is still under development", Toast.LENGTH_LONG).show();
fab = findViewById(R.id.fab_complete_group);
paybtn = findViewById(R.id.button6);
depobtn = findViewById(R.id.button5);
borrowbtn = findViewById(R.id.button3);
borrowicon = findViewById(R.id.button8);
depoicon = findViewById(R.id.button9);
payicon = findViewById(R.id.button10);
sendtextbutton = findViewById(R.id.sendtextButton);
text_send = findViewById(R.id.text_send);
chatrecyclerView = findViewById(R.id.chatrecycler);
chatrecyclerView.setLayoutManager(new LinearLayoutManager(this));
fab.setOnClickListener(this);
paybtn.setOnClickListener(this);
depobtn.setOnClickListener(this);
borrowbtn.setOnClickListener(this);
borrowicon.setOnClickListener(this);
depoicon.setOnClickListener(this);
payicon.setOnClickListener(this);
sendtextbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = text_send.getText().toString();
if (!message.equals("")){
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String userId = getIntent().getStringExtra("userId");
sendmessage(message,userId,firebaseUser.getUid());
}
else {
Toast.makeText(Complete_new_Group.this, "You can't send an empty message", Toast.LENGTH_SHORT).show();
}
text_send.setText("");
}
});
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final String user_id;
Intent intent = getIntent();
user_id = intent.getStringExtra("userId");
assert user_id != null;
// Log.d("TRACK",user_id);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Users users = snapshot.getValue(Users.class);
readMessage(firebaseUser.getUid(),user_id,users.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onClick(View view) {
if (view==fab){
paybtn.setVisibility(View.VISIBLE);
depobtn.setVisibility(View.VISIBLE);
borrowbtn.setVisibility(View.VISIBLE);
borrowicon.setVisibility(View.VISIBLE);
depoicon.setVisibility(View.VISIBLE);
payicon.setVisibility(View.VISIBLE);
}
if (view==paybtn){
Intent intent = new Intent(getApplicationContext(),Group_pay.class);
startActivity(intent);
}
if (view==payicon){
Intent intent = new Intent(getApplicationContext(),Group_pay_icon_activity.class);
startActivity(intent);
}
if (view==depobtn){
Intent intent = new Intent(getApplicationContext(),Group_deposit_button_activity.class);
startActivity(intent);
}
if (view==depoicon){
Intent intent = new Intent(getApplicationContext(),Group_depo_icon_activity.class);
startActivity(intent);
}
if (view==borrowbtn){
Intent intent = new Intent(getApplicationContext(),Group_deposit_button_activity.class);
startActivity(intent);
}
if (view==borrowicon){
Intent intent = new Intent(getApplicationContext(),Group_borrow_icon_activity.class);
startActivity(intent);
}
if (view==sendtextbutton){
}
}
private void sendmessage(String message,String sender, String reciever){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("sender",sender);
hashMap.put("reciever",reciever);
hashMap.put("message",message);
reference.child("Chats").push().setValue(hashMap);
}
private void readMessage(final String myId, final String userId, String imageURL){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
FirebaseRecyclerOptions<Chat> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Chat>().setQuery(databaseReference, new SnapshotParser<Chat>() {
#NonNull
#Override
public Chat parseSnapshot(#NonNull DataSnapshot snapshot) {
String message = String.valueOf(snapshot.child("message").getValue());
String sender = String.valueOf(snapshot.child("sender").getValue());
String receiver = String.valueOf(snapshot.child("reciever").getValue());
return new Chat(message,sender,receiver);
}
}).build();
final FirebaseRecyclerAdapter<Chat,ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Chat,ViewHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull final ViewHolder viewHolder, int i, #NonNull Chat chat) {
if (chat.getReceiver().equals(userId) && chat.getSender().equals(myId) || chat.getReceiver()
.equals(myId) && chat.getSender().equals(userId)){
viewHolder.showMessage.setText(chat.getMessage());
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MESSAGE_RIGHT){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_right,parent,false);
return new ViewHolder(view);
}
else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item_left,parent,false);
return new ViewHolder(view);
}
}
#Override
public int getItemViewType(int position) {
Chat chat = getItem(position);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (chat.getSender().equals(firebaseUser.getUid())){
return MESSAGE_LEFT;
}
else {
return MESSAGE_RIGHT;
}
//return super.getItemViewType(position);
}
};
chatrecyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView showMessage;
public ImageView profilepic;
public ViewHolder(#NonNull View itemView) {
super(itemView);
showMessage=itemView.findViewById(R.id.showMessage);
profilepic=itemView.findViewById(R.id.profilepic);
}
public void setText(String paramString){
this.showMessage.setText(paramString);
}
}
}
This is the output on both the sender and the receiver
I need some assistance

Trying to write something in one activity and reading it in the next activity

Im currently creating a barber application and at the moment, on my landing page i have a button that when clicked it will bring up a popup window for the user to enter their name and contact number
Now what i want to do is when the user clicks view appointments it shows what appointments there are on the page name ContactUs.java
So here is my Landing.java page
package ie.app.barbershop;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.List;
public class Landing extends AppCompatActivity{
public Button buttonProducts;
public Button button4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_landing);
readRecords();
countRecords();
buttonProducts = findViewById(R.id.buttonProducts);
button4 = findViewById(R.id.button4);
Button buttonCreateAppointment = findViewById(R.id.buttonCreateAppointment);
buttonCreateAppointment.setOnClickListener(new OnClickListenerCreateAppointment());
buttonProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Landing.this, Products.class));
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Landing.this, ContactUs.class));
}
});
}
public void readRecords() {
LinearLayout linearLayoutRecords = findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<ObjectAppointment> appointments = new TableControllerAppointments(this).read();
if (appointments.size() > 0) {
for (ObjectAppointment obj : appointments) {
String fullName = obj.fullName;
int contactNumber = obj.contactNumber;
String textViewContents = fullName + " - " + contactNumber;
TextView textViewAppointmentItem= new TextView(this);
textViewAppointmentItem.setPadding(0, 10, 0, 10);
textViewAppointmentItem.setText(textViewContents);
textViewAppointmentItem.setTag(Integer.toString(contactNumber));
linearLayoutRecords.addView(textViewAppointmentItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
public void countRecords(){
int recordCount = new TableControllerAppointments(this).count();
TextView textViewRecordCount = findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
}
This is my ContactUs.Java page(This should be called ViewAppointments.java but it was originally meant to be a contact us page)
package ie.app.barbershop;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class ContactUs extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_us);
}
}
This is my onclicklistenerCreateAppointment.java page
package ie.app.barbershop;
import android.view.View;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class OnClickListenerCreateAppointment implements View.OnClickListener {
public ObjectAppointment objectAppointment;
#Override
public void onClick(View view){
final Context context = view.getRootView().getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.appointment_input_form, null, false);
final EditText editTextFullName = formElementsView.findViewById(R.id.editTextFullName);
final EditText editTextContactNumber = formElementsView.findViewById(R.id.editTextContactNumber);
ObjectAppointment objectAppointment = new ObjectAppointment();
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Create Appointment")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String fullname = editTextFullName.getText().toString();
String contactno = editTextContactNumber.getText().toString();
((Landing) context).countRecords();
((Landing) context).readRecords();
dialog.cancel();
}
}).show();
boolean createSuccessful = new TableControllerAppointments(context).create(objectAppointment);
if(createSuccessful){
Toast.makeText(context, "Appointment Information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save appointment information", Toast.LENGTH_SHORT).show();
}
}
}
And this is my TableControllerAppointments.java
package ie.app.barbershop;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class TableControllerAppointments extends DatabaseHandler {
public TableControllerAppointments(Context context) {
super(context);
}
public boolean create(ObjectAppointment objectAppointments) {
ContentValues values = new ContentValues();
values.put("fullname", objectAppointments.fullName);
values.put("contactno", objectAppointments.contactNumber);
SQLiteDatabase db = this.getWritableDatabase();
boolean createSuccessful = db.insert("appointments", null, values) > 0;
db.close();
return createSuccessful;
}
public List<ObjectAppointment> read() {
List<ObjectAppointment> recordsList = new ArrayList<>();
String sql = "SELECT * FROM Appointments ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
String fullName = cursor.getString(cursor.getColumnIndex("fullname"));
int contactNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex("contactno")));
ObjectAppointment objectAppointment = new ObjectAppointment();
objectAppointment.fullName = fullName;
objectAppointment.contactNumber = contactNumber;
recordsList.add(objectAppointment);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return recordsList;
}
public int count() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "SELECT * FROM appointments";
int recordCount = db.rawQuery(sql, null).getCount();
db.close();
return recordCount;
}
}
Any other info you need im more than happy to provide if i have forgotten something.
Im sorry if its something small and stupid im missing

Transfer List<String> to another activity ListView

MainActivity:
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.*;
import android.content.Intent;
public class MainActivity extends Activity {
private Spinner spinner1;
private Button btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get Value from EditText //Save value to a Variable
EditText person0 = findViewById(R.id.spot0); String saved_spot0 = person0.getText().toString();
EditText person1 = findViewById(R.id.spot1); String saved_spot1 = person1.getText().toString();
EditText person2 = findViewById(R.id.spot2); String saved_spot2 = person2.getText().toString();
EditText person3 = findViewById(R.id.spot3); String saved_spot3 = person3.getText().toString();
EditText person4 = findViewById(R.id.spot4); String saved_spot4 = person4.getText().toString();
EditText person5 = findViewById(R.id.spot5); String saved_spot5 = person5.getText().toString();
EditText person6 = findViewById(R.id.spot6); String saved_spot6 = person6.getText().toString();
EditText person7 = findViewById(R.id.spot7); String saved_spot7 = person7.getText().toString();
EditText person8 = findViewById(R.id.spot8); String saved_spot8 = person8.getText().toString();
EditText person9 = findViewById(R.id.spot9); String saved_spot9 = person9.getText().toString();
List<String> filled_spots = Arrays.asList(saved_spot0, saved_spot1, saved_spot2, saved_spot3, saved_spot4, saved_spot5, saved_spot6, saved_spot7, saved_spot8, saved_spot9);
Collections.shuffle(filled_spots); //Shuffle List
Collections.sort(filled_spots); //Sort List
Intent teams_Screen = new Intent (MainActivity.this, DisplayTeamsActivity.class);
teams_Screen.putStringArrayListExtra ("mylist", (ArrayList<String>) filled_spots);
startActivity(teams_Screen);
}
});
}
}
DisplayTeamsActivity:
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class DisplayTeamsActivity extends AppCompatActivity {
private ListView lv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_teams);
ArrayList<String> stringList = getIntent().getStringArrayListExtra("mylist");
}
}
I need to pass the List array from one activity to another and populate the listView I have from the shuffeld array, but something is crashing my app when i click on the button that takes me to the next activity. I dont know if this is correctly done and what is the problem causing it to entirely crash...
you can try this
in first acticity
Intent intent = new Intent(context, NewActivity.class);
intent.putExtra("mylist", yourlist_array);
context.startActivity(intent);
in second activity
Intent intent = getIntent();
List stringArray = intent.getStringArrayExtra("mylist");
Do this:
ArrayList<String> filled_spots = new ArrayList<>(Arrays.asList("nome1", "nome2"));
Collections.shuffle(filled_spots); //Shuffle List
Collections.sort(filled_spots); //Sort List
Intent teams_Screen = new Intent (MainActivity.this, DisplayTeamsActivity.class);
teams_Screen.putStringArrayListExtra("mylist", filled_spots);
At DisplayTeamsActivity you'll need do this:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> stringList = getIntent().getStringArrayListExtra("mylist");
}

Passing data from listview to edittext of another activity

package com.supdeco.oussamaniba.loginapp;
import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DisplayListView extends AppCompatActivity {
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
TextView lstv;
String username,email,password,name,last;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView) findViewById(R.id.list);
lstv = (TextView) findViewById(R.id.lstv);
contactAdapter = new ContactAdapter(this, R.layout.row_layout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
username = JO.getString("username");
email = JO.getString("email");
password = JO.getString("password");
name = JO.getString("name");
last = JO.getString("lastname");
Contacts contacts = new Contacts(username,email,password,name,last);
contactAdapter.add(contacts);
count++;
lstv.setText("Available: " + count + " members");
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
intent.putExtra("username", String.valueOf(listView.getSelectedItem()));
startActivity(intent);
}
});
}
}
I try to pass data from this ListView to another EditText in an other
activity but the result is always null, I want to pass all the text
string from the ListView to the EditText.
Do this way,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
intent.putExtra("username", YourModels.get(position).getUsername());//here first get position and than pass data you want to pass
intent.putExtra("fk_Code", "" + YourModels.get(position).getFk_Code());//take data from your model
startActivity(intent);
}
});
Check this link for more information.
It was too simple i found a simple solution i created a bunch of
string arrays that contains each of the data fetched from the DB and
stored in them, so now i can choose from those String arrays by
position, but thanks anyway
package com.supdeco.oussamaniba.loginapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DisplayListView extends AppCompatActivity {
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
TextView lstv;
String username,email,password,name,last;
List<String> susername = new ArrayList<String>();
List<String> sname = new ArrayList<String>();
List<String> slname = new ArrayList<String>();
List<String> spassword = new ArrayList<String>();
List<String> semail = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView) findViewById(R.id.list);
lstv = (TextView) findViewById(R.id.lstv);
contactAdapter = new ContactAdapter(this, R.layout.row_layout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
username = JO.getString("username");
email = JO.getString("email");
password = JO.getString("password");
name = JO.getString("name");
last = JO.getString("lastname");
Contacts contacts = new Contacts(username,email,password,name,last);
contactAdapter.add(contacts);
count++;
susername.add(username);
sname.add(name);
slname.add(last);
spassword.add(password);
semail.add(email);
lstv.setText("Available: " + count + " members");
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
String[] N = new String[sname.size()];
N = sname.toArray(N);
String[] L = new String[slname.size()];
L = slname.toArray(L);
String[] U = new String[susername.size()];
U = susername.toArray(U);
String[] P = new String[spassword.size()];
P = spassword.toArray(P);
String[] E = new String[semail.size()];
E = semail.toArray(E);
intent.putExtra("name", N[position]);
intent.putExtra("last", L[position]);
intent.putExtra("username", U[position]);
intent.putExtra("password", P[position]);
intent.putExtra("email", E[position]);
startActivity(intent);
}
});
}
}

Categories