I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.
Related
I am making a simple alarm app that holds alarm data in a databased generated with Room, and uses a viewmodel to update the RecyclerView adapter's list. However, when I check/uncheck the switch on one item in the RecyclerView it sometimes causes another item's switch to check/uncheck itself, and I'm not sure why. Any help on what is wrong with my code is appreciated. Here is the java code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private List<Alarms> mainAlarmsList;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private AlarmsAdapter alarmsAdapter;
private AlarmsAdapter.alarmedInterface coolInterface;
private ImageButton imageButton, clearButton;
private AlarmsViewModel alarmsViewModel;
private AlarmManager epicAlarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
epicAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
imageButton = (ImageButton) findViewById(R.id.alarm_button);
clearButton = (ImageButton) findViewById(R.id.clear_alarms_button);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createTimePicker(MainActivity.this);
}
});
alarmsViewModel = ViewModelProviders.of(this).get(AlarmsViewModel.class);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alarmsViewModel.deleteAllAlarms();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
alarmsAdapter = new AlarmsAdapter(this);
//alarmsAdapter.setAlarms(alarmsViewModel.getAllAlarms().getValue());
coolInterface = new AlarmsAdapter.alarmedInterface() {
#Override
public void onSwitch(int position, boolean isChecked, CompoundButton compoundButton) {
Alarms currentAlarm = mainAlarmsList.get(position);
String concatenatedString;
if(isChecked){
currentAlarm.setOffOn(1);
concatenatedString = currentAlarm.getId() + " is on " + currentAlarm.getOffOn();
compoundButton.setChecked(true);
}
else {
currentAlarm.setOffOn(0);
concatenatedString = currentAlarm.getId() + " is off " + currentAlarm.getOffOn();
compoundButton.setChecked(false);
}
Toast.makeText(MainActivity.this,concatenatedString,Toast.LENGTH_LONG).show();
new updateAsync(alarmsViewModel).execute(currentAlarm);
}
};
recyclerView.setAdapter(alarmsAdapter);
alarmsViewModel.getAllAlarms().observe(this, new Observer<List<Alarms>>() {
#Override
public void onChanged(List<Alarms> alarms) {
alarmsAdapter.setAlarms(alarms);
alarmsAdapter.setAlarmInterfaceInstance(coolInterface);
alarmsAdapter.notifyDataSetChanged();
mainAlarmsList = alarms;
}
});
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
public void createTimePicker(Context context){
final Calendar calendar = Calendar.getInstance();
final int hrDay = Calendar.HOUR_OF_DAY;
final int min = Calendar.MINUTE;
TimePickerDialog dialog = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Alarms myAlarm = new Alarms(hourOfDay,minute);
myAlarm.setOffOn(1);
alarmsViewModel.insertAlarms(myAlarm);
alarmsAdapter.notifyDataSetChanged();
calendar.set(Calendar.HOUR_OF_DAY, myAlarm.getHour());
calendar.set(Calendar.MINUTE, myAlarm.getMin());
alarmTime(myAlarm,calendar);
}
}, hrDay,min,true);
dialog.show();
}
public void alarmTime(Alarms alarms,Calendar calendar){
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,
alarms.getId(),intent,0);
long hrlong = alarms.getHour();
long minlong = alarms.getMin();
epicAlarmManager.setExact(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() ,pendingIntent);
}
class updateAsync extends AsyncTask<Alarms,Void,Void>{
private AlarmsViewModel viewModel;
updateAsync(AlarmsViewModel alarmsViewModel1){
viewModel = alarmsViewModel1;
}
#Override
protected Void doInBackground(Alarms... alarms) {
viewModel.updateAlarms(alarms[0]);
return null;
}
}
}
Alarms.java
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "Alarms")
public class Alarms {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "hour")
private int hour;
#ColumnInfo(name = "min")
private int min;
#ColumnInfo(name = "offOn")
private int offOn;
public Alarms(int hour, int min){
this.hour = hour;
this.min = min;
offOn = 1;
}
public void setId(int id) {
this.id = id;
}
public void setMin(int min) {
this.min = min;
}
public void setHour(int hour) {
this.hour = hour;
}
public void setOffOn(int offOn) {
this.offOn = offOn;
}
public int getMin() {
return min;
}
public int getHour() {
return hour;
}
public int getOffOn() {
return offOn;
}
public int getId(){
return id;
}
}
AlarmsAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class AlarmsAdapter extends RecyclerView.Adapter<AlarmsAdapter.AlarmsViewHolder> {
private Context context;
private List<Alarms> alarms;
private alarmedInterface alarmInterfaceInstance;
interface alarmedInterface{
public void onSwitch(int position, boolean checked, CompoundButton compoundButton);
}
public AlarmsAdapter(Context context){
this.context = context;
}
public void setAlarmInterfaceInstance(alarmedInterface alarmInterfaceInstance) {
this.alarmInterfaceInstance = alarmInterfaceInstance;
}
public void setAlarms(List<Alarms> alarms) {
this.alarms = alarms;
}
#NonNull
#Override
public AlarmsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item,parent,false);
return new AlarmsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AlarmsAdapter.AlarmsViewHolder holder, final int position) {
if(alarms.isEmpty()){
holder.textView.setText("No alarms");
return;
}
else{
Alarms myAlarm = alarms.get(position);
if(myAlarm.getOffOn() == 1){
holder.aSwitch.setChecked(true);
}
else if(myAlarm.getOffOn() == 0){
holder.aSwitch.setChecked(false);
}
String x = alarms.get(position).getHour() + ":" + alarms.get(position).getMin();
holder.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
alarmInterfaceInstance.onSwitch(position, isChecked,buttonView);
}
});
holder.textView.setText(x);
}
}
#Override
public int getItemCount() {
if(alarms != null) {
return alarms.size();
}
else {
return 0;
}
}
public class AlarmsViewHolder extends RecyclerView.ViewHolder{
TextView textView;
SwitchCompat aSwitch;
public AlarmsViewHolder(View view){
super(view);
textView = view.findViewById(R.id.textView);
aSwitch = view.findViewById(R.id.switch1);
}
}
}
AlarmsViewModel.java
import android.app.Application;
import android.content.Context;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class AlarmsViewModel extends AndroidViewModel {
private AlarmsRepository repository;
private LiveData<List<Alarms>> allAlarms;
public AlarmsViewModel(Application application){
super(application);
repository = new AlarmsRepository(application.getApplicationContext());
allAlarms = repository.getAlarmsList();
}
public void deleteAllAlarms(){
repository.deleteAllAlarms();
}
public void updateAlarms(Alarms alarms){
repository.updateAlarm(alarms);
}
public void insertAlarms(Alarms alarms){
repository.insertAlarm(alarms);
}
public LiveData<List<Alarms>> getAllAlarms() {
return allAlarms;
}
}
AlarmdDao.java
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
#Dao
public interface AlarmDao {
#Query("Select * From Alarms")
public LiveData<List<Alarms>> getAllAlarms();
#Insert
public void insertAlarm(Alarms alarms);
#Update
public void updateAlarm(Alarms alarms);
#Delete
public void deleteAlarm(Alarms alarms);
#Query("Delete From Alarms")
public void deleteAllAlarms();
}
AlarmsDatabase
import android.app.Application;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
#Database(entities = {Alarms.class},version = 1,exportSchema = false)
public abstract class AlarmsDatabase extends RoomDatabase {
private static AlarmsDatabase alarmsDatabase;
private Context context;
public abstract AlarmDao alarmDao();
public static AlarmsDatabase AlarmsDatabaseBuilder(Context context){
if(alarmsDatabase == null){
synchronized (AlarmsDatabase.class){
if (alarmsDatabase == null){
alarmsDatabase = Room.databaseBuilder(context.getApplicationContext(),
AlarmsDatabase.class,"AlarmsDatabase").build();
}
}
}
return alarmsDatabase;
}
}
AlarmReceiver.java
package com.pbaileyapps.android.chatpal;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"You just recieved a toast!",Toast.LENGTH_LONG).show();
}
}
I have had similar issue with JSON objects, in my case a set of data is copied into two different JSON lists that both display differently in a recycle view. One of them displays the original data and the second has modified the data. However the modification appeared on both becuase the copies still linked to the original data behind the scences. I fixed this by making a 'deep copy'. It is possible that your alarm objects are not being deep copied into the list so two or more list elements have the same origin.
In my file Reservation.java I have a function that loads LieuActivity.
So this is the function
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(getIntent().getStringExtra("mytext"));
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
}
In my LieuActivity.java I have this code
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
}
}
The problem is when I edit in my LieuActivity and go back to reservation it does not return the extra value until I click another time on the editText so I see the updated data for a second before re-going to LieuActivity and modify it another time .
Put these lines in onCreate() of Reservation activity
String text = getIntent().getStringExtra("mytext");
if (text != null) {
lieu.setText(text);
}
and make this change:
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
finish();
}
Do this in oncreate of Reservation
Bundle extras = getIntent().getExtras();
String string;
if (extras != null) {
string = extras.getString("mytext");
lieu.setText(string);
}
Make changes like this in LieuActivity :-
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
setResult(RESULT_OK, myIntent );
});
}
}
In Reservation put onActivityResult()
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
String mNewText="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(mNewText);
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == QUEUE_MSG) {
if (resultCode == RESULT_OK) {
Serializable myText= data.getSerializableExtra("mytext");
if (myText!= null)
mNewText= myText;
}
}
}
}
Hope this may help you
I have three classes one user list holds the list of user when each user is clicked it directs you to chat class which holds the chats activity. I also have the conversation list which holds a single conversation. The problem is the list view does not show previous chats stored in parse data base how can I load the previous chats to my list view.
package com.example.user.mycareerchat;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.example.user.mycareerchat.custom.CustomActivity;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseClassName;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
public class UserList extends CustomActivity {
private static final String EXTRADATA = null;
// Declare Variables
// the chat list
private ArrayList<ParseUser> uList =new ArrayList<ParseUser>();
// the parseruser
public static ParseUser user=new ParseUser();
/////////////
public static ArrayList names = new ArrayList<String>();
private String currentUserId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
updateUserStatus(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
updateUserStatus(false);
}
#Override
protected void onResume() {
super.onResume();
loadUserList();
}
private void loadUserList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
//don't include yourself
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, com.parse.ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
uList = new ArrayList<ParseUser>(userList);
}
final ListView list = (ListView)findViewById(R.id.list);
ArrayAdapter namesArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.chat_item, names);
list.setAdapter(namesArrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
// openConversation(names, i);
String name= names.get(i).toString();
startActivity(new Intent(UserList.this, Chat.class).putExtra(EXTRADATA, name));
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
private void updateUserStatus(boolean online) {
user.put("online", online);
user.saveEventually();
}
private class UserAdapter extends BaseAdapter {
#Override
public int getCount() {
return uList.size();
}
#Override
public ParseUser getItem(int arg0) {
return uList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View v, ViewGroup arg2) {
if(v!=null)
v=getLayoutInflater().inflate(R.layout.chat_item,null);
ParseUser c= getItem(pos);
TextView lbl = (TextView) v;
lbl.setText(c.getUsername());
lbl.setCompoundDrawablesWithIntrinsicBounds(c.getBoolean("online")? R.drawable.ic_online:
R.drawable.ic_offline,0,
R.drawable.arrow,0);
return v;
}
}
}
//Conversation Class
package com.example.user.mycareerchat.model;
import com.example.user.mycareerchat.UserList;
import java.util.Date;
/**
* Created by user on 26/Aug/2015.
*/
public class Conversation {
public static final int STATUS_SENDING =0;
public static final int STATUS_SENT =1;
public static final int STATUS_FAILED =2;
private int status = STATUS_SENT;
private Date date;
private String sender;
private String msg;
//instatiates new conversation
public Conversation(String msg,Date date,String sender) {
this.msg =msg;
this.date = date;
this.sender = sender;
}
//instatiates new conversation
// public Conversation() {
//
// }
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isSent(){
return UserList.user.getUsername().equals(sender);
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
//Chat class
package com.example.user.mycareerchat;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Telephony;
import android.text.InputType;
import android.text.format.DateUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.user.mycareerchat.custom.CustomActivity;
import com.example.user.mycareerchat.model.Conversation;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class represents single chat class message
*/
public class Chat extends CustomActivity {
private ArrayList<Conversation> convList;
private ChatAdapter adp;
private EditText txt;
private String buddy;
private Date lastMsgDate;
private boolean isRunning;
private static Handler handler;
private static final String EXTRA_DATA = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
convList = new ArrayList<Conversation>();
ListView list = (ListView) findViewById(R.id.listchat);
adp = new ChatAdapter();
list.setAdapter(adp);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
list.setStackFromBottom(true);
txt = (EditText) findViewById(R.id.txt);
txt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
setTouchNClick(R.id.btnSend);
buddy = getIntent().getStringExtra(EXTRA_DATA);
// getActionBar().setTitle(buddy);
loadConversationList();
handler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
isRunning =true;
loadConversationList();
}
#Override
protected void onPause() {
super.onPause();
isRunning = false;
}
#Override
public void onClick(View v) {
super.onClick(v);
if(v.getId()== R.id.btnSend){
sendMessage();
}
}
private void sendMessage() {
if(txt.length()==0)
return;
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txt.getWindowToken(),0);
String s =txt.getText().toString();
final Conversation c = new Conversation(s, new Date(),UserList.user.getUsername());
c.setStatus(Conversation.STATUS_SENDING);
convList.add(c);
adp.notifyDataSetChanged();
txt.setText(null);
ParseObject po = new ParseObject("Chat");
po.put("sender",UserList.user.getUsername());
po.put("receiver",buddy);
po.put("message",s);
po.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null)
c.setStatus(Conversation.STATUS_SENT);
else
c.setStatus(Conversation.STATUS_FAILED);
adp.notifyDataSetChanged();
}
});
}
/*load the conversation list from parse server and save the data of the last message that will
* be used to load only new received messages*/
private void loadConversationList() {
//load all messsages
ParseQuery<ParseObject> q =ParseQuery.getQuery("Chat");
if(convList.size()==0){
ArrayList<String> al = new ArrayList<String>();
al.add(buddy);
al.add(ParseUser.getCurrentUser().getUsername());
q.whereContainedIn("sender", al);
q.whereContainedIn("receiver",al);
}
else{
//load only new received messages....
if(lastMsgDate!=null){
q.whereLessThan("createdAt",lastMsgDate);
q.whereEqualTo("sender", ParseUser.getCurrentUser().getUsername());
q.whereEqualTo("receiver",buddy);
adp.notifyDataSetChanged();
}
//load messages in the most recent order
q.orderByDescending("createdAt");
q.setLimit(30);
q.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> li, ParseException e) {
if(li != null && li.size() >0){
for (int i =li.size()-1;i>=0;i--){
ParseObject po = li.get(i);
Conversation c =new Conversation(po.getString("message"),po.getCreatedAt(),po.getString("sender"));
convList.add(c);
if(lastMsgDate == null || lastMsgDate.before(c.getDate()))
lastMsgDate = c.getDate();
adp.notifyDataSetChanged();
}
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(isRunning)
loadConversationList();
}
},1000);
//
}
});
}
}
/*this class is the adapter class for chat listview. this adapter shows the sent and received messages
*in the list item*/
private class ChatAdapter extends BaseAdapter{
#Override
public int getCount() {
return convList.size();
}
#Override
public Conversation getItem(int arg0) {
return convList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View v, ViewGroup arg2) {
Conversation c = getItem(pos);
if(c.isSent())
v=getLayoutInflater().inflate(R.layout.chat_item_sent,null);
else
v=getLayoutInflater().inflate(R.layout.chat_item_rcv,null);
TextView lbl =(TextView) v.findViewById(R.id.lbl1);
lbl.setText(DateUtils.getRelativeDateTimeString(Chat.this,c.getDate().getTime (),DateUtils.SECOND_IN_MILLIS,DateUtils.DAY_IN_MILLIS,0));
lbl =(TextView) v.findViewById(R.id.lbl2);
lbl.setText(c.getMsg());
lbl =(TextView) v.findViewById(R.id.lbl3);
if (c.isSent()){
if (c.getStatus()==Conversation.STATUS_SENT)
lbl.setText("Delivered");
else if (c.getStatus()==Conversation.STATUS_SENDING)
lbl.setText("Sending...");
else
lbl.setText("Failed");
}
else
lbl.setText("");
return v;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
I am trying to implement and autocomplete function for an edittext in a fragment but having trouble passing the context of the fragment to the listener/textwatcher. In the constructor, it accepts the context as a parameter but brings an "inconvertable types" error when trying to link the context to the fragment.
`EmpAddFragment mainActivity = ((EmpAddFragment)context);`
Below is the code for the listener and the fragment where it is called.
CustomAutoCompleteTextChangedListener.java:
import android.content.Context;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
public class CustomAutoCompleteTextChangedListener implements TextWatcher {
public static final String TAG = "CustomAutoCompleteTextChangedListener.java";
Context context;
View view;
Fragment fragment;
public CustomAutoCompleteTextChangedListener(Context context){
this.context = context;
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence userInput, int start, int before, int count) {
EmpAddFragment mainActivity = ((EmpAddFragment)context);
// query the database based on the user input
mainActivity.item = mainActivity.getItemsFromDb(userInput.toString());
// update the adapater
mainActivity.myAdapter.notifyDataSetChanged();
mainActivity.myAdapter = new ArrayAdapter<String>(mainActivity.getActivity(), android.R.layout.simple_dropdown_item_1line, mainActivity.item);
mainActivity.myAutoComplete.setAdapter(mainActivity.myAdapter);
}
}
EmpAddFragment:
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
public class EmpAddFragment extends Fragment implements OnClickListener {
// UI references
private EditText empNameEtxt;
private Button addButton;
private Button resetButton;
/*
* Change to type CustomAutoCompleteView instead of AutoCompleteTextView
* since we are extending to customize the view and disable filter
* The same with the XML view, type will be CustomAutoCompleteView
*/
CustomAutoCompleteView myAutoComplete;
// adapter for auto-complete
ArrayAdapter<String> myAdapter;
// for database operations
DataBaseHelper databaseH;
// just to add some initial value
String[] item = new String[] {"Please search..."};
private static final SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd", Locale.ENGLISH);
DatePickerDialog datePickerDialog;
Calendar dateCalendar;
Employee employee = null;
private EmployeeDAO employeeDAO;
private AddEmpTask task;
public static final String ARG_ITEM_ID = "emp_add_fragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
employeeDAO = new EmployeeDAO(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_emp, container,
false);
findViewsById(rootView);
setListeners();
try{
// instantiate database handler
databaseH = new DataBaseHelper(getActivity());
// autocompletetextview is in activity_main.xml
myAutoComplete = (CustomAutoCompleteView) rootView.findViewById(R.id.myautocomplete);
// add the listener so it will tries to suggest while the user types
myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this.getActivity()));
// set our adapter
myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, item);
myAutoComplete.setAdapter(myAdapter);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//For orientation change.
if (savedInstanceState != null) {
dateCalendar = Calendar.getInstance();
if (savedInstanceState.getLong("dateCalendar") != 0)
dateCalendar.setTime(new Date(savedInstanceState
.getLong("dateCalendar")));
}
return rootView;
}
private void setListeners() {
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(getActivity(),
new OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
dateCalendar = Calendar.getInstance();
dateCalendar.set(year, monthOfYear, dayOfMonth);
}
}, newCalendar.get(Calendar.YEAR),
newCalendar.get(Calendar.MONTH),
newCalendar.get(Calendar.DAY_OF_MONTH));
addButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
}
protected void resetAllFields() {
empNameEtxt.setText("");
}
private void setEmployee() {
employee = new Employee();
employee.setName(empNameEtxt.getText().toString());
}
#Override
public void onResume() {
getActivity().setTitle(R.string.add_emp);
getActivity().getActionBar().setTitle(R.string.add_emp);
super.onResume();
}
#Override
public void onSaveInstanceState(Bundle outState) {
if (dateCalendar != null)
outState.putLong("dateCalendar", dateCalendar.getTime().getTime());
}
private void findViewsById(View rootView) {
empNameEtxt = (EditText) rootView.findViewById(R.id.etxt_name);
addButton = (Button) rootView.findViewById(R.id.button_add);
resetButton = (Button) rootView.findViewById(R.id.button_reset);
}
#Override
public void onClick(View view) {
if (view == null) {
} else if (view == addButton) {
setEmployee();
task = new AddEmpTask(getActivity());
task.execute((Void) null);
} else if (view == resetButton) {
resetAllFields();
}
}
public class AddEmpTask extends AsyncTask<Void, Void, Long> {
private final WeakReference<Activity> activityWeakRef;
public AddEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected Long doInBackground(Void... arg0) {
long result = employeeDAO.save(employee);
return result;
}
#Override
protected void onPostExecute(Long result) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
if (result != -1)
Toast.makeText(activityWeakRef.get(), "Employee Saved",
Toast.LENGTH_LONG).show();
}
}
}
// this function is used in CustomAutoCompleteTextChangedListener.java
public String[] getItemsFromDb(String searchTerm){
// add items on the array dynamically
List<MyObject> products = databaseH.read(searchTerm);
int rowCount = products.size();
String[] item = new String[rowCount];
int x = 0;
for (MyObject record : products) {
item[x] = record.objectName;
x++;
}
return item;
}
}
This is the logcat when i used
`EmpAddFragment mainActivity = new EmpAddFragment;
All other attempts output the inconvertable types error
LogCat:
07-23 06:49:17.828 2017-2017/com.example.autoFill E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.autoFill, PID: 2017
java.lang.NullPointerException
at com.example.autoFill.EmpAddFragment.getItemsFromDb(EmpAddFragment.java:209)
at com.example.autoFill.CustomAutoCompleteTextChangedListener.onTextChanged(CustomAutoCompleteTextChangedListener.java:42)
at android.widget.TextView.sendOnTextChanged(TextView.java:7408)
at android.widget.TextView.handleTextChanged(TextView.java:7467)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9187)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:212)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:30)
at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:243)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:382)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
UPDATE:
Changed my listener constructor to:
public CustomAutoCompleteTextChangedListener(EmpAddFragment frag){
frag = fragment;
context = fragment.getActivity();
}
and the call to:
myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this));
But register a NullPointerException in the logcat pointing to:
myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this));
AND:
context = fragment.getActivity();
Change the constructor of your listener class
public class CustomAutoCompleteTextChangedListener implements TextWatcher {
public static final String TAG = "CustomAutoCompleteTextChangedListener.java";
Context context;
View view;
Fragment fragment;
public CustomAutoCompleteTextChangedListener(EmpAddFragment fragment){
this.fragment = fragment;
this.context = fragment.getActivity();
}
//.... rest of your listener class implementation
}
Use the calling method as follows where you face "inconvertible types"
EmpAddFragment mainFragment = ((EmpAddFragment)fragment);
Hope it works!
myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this.getActivity()));
with the line above you are not passing the fragment but the activity from where it is called so when you call:
EmpAddFragment mainActivity = ((EmpAddFragment)context);
it can't work because you are casting to EmpAddFragment an Activity instance.
so if you want to have the fragment instance change the listener constructor and pass the fragment.
if you want to have the activity then cast the context to the activity
Everytime I tried to run these code the program crashed then I tried to get an Array of Objects from my LinkedList.
Product[] arr = (Product[])produktliste.toArray(); causes the crash
This is the source of the MainActivity:
package at.lamprechtdominik.myfirstlistapp;
import java.util.LinkedList;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
public static LinkedList<Product> produktliste = new LinkedList<Product>();
private Button benutzerAnlegen;
private Button listeAnzeigen;
private EditText nameProdukt;
private EditText preisProdukt;
private CheckBox istVorhanden;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
benutzerAnlegen = (Button) findViewById(R.id.btBenutzerAnlegen);
nameProdukt = (EditText) findViewById(R.id.etProduktname);
preisProdukt = (EditText) findViewById(R.id.etPreis);
istVorhanden = (CheckBox) findViewById(R.id.cbProduktVorhanden);
listeAnzeigen = (Button) findViewById(R.id.btZeigeListe);
benutzerAnlegen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
produktliste.add(neuesProduktAnlegen());
Toast.makeText(getBaseContext(), R.string.anlegen_erfolgreich, Toast.LENGTH_LONG).show();
}
});
listeAnzeigen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Intent i = new Intent(getBaseContext(), Produktauflistung.class);
//startActivity(i);
Product[] arr = (Product[])produktliste.toArray();
}
});
}
private Product neuesProduktAnlegen(){
String name = nameProdukt.toString();
Double preis = Double.parseDouble(preisProdukt.getText().toString());
boolean vorhanden;
if(istVorhanden.isChecked()){
vorhanden = true;
} else {
vorhanden = false;
}
Product neuesProdukt = new Product(name, preis , vorhanden);
return(neuesProdukt);
}
}
class file Product:
package at.lamprechtdominik.myfirstlistapp;
public class Product {
private String name;
private Double preis;
private boolean istVorhanden;
public Product(String name, Double preis, boolean istVorhanden){
this.name = name;
this.preis = preis;
this.istVorhanden = istVorhanden;
}
public String getName(){
return(name);
}
public Double getPreis(){
return(preis);
}
public boolean getIstVorhanden(){
return(istVorhanden);
}
}
Does anyone know how what i did wrong?
Thanks for your help.
You cannot simply cast the result of toArray() to a Product[] array.
Use this:
Product[] meineProdukte = new Product(produktliste.size());
meineProdukte = produktliste.toArray(meineProdukte);
Try to change to
Product[] arr = produktliste.toArray(new Product[produktliste.size()]);