How to show Video Ad (AdColony) - java

I have an application in which I want to integrate VIDEO AD from AdColony.
When the user clicks on the button, the loadAd() method is triggered, and after that onRequestFilled.
But after calling show() nothing happens.
Here's class with all methods that i have for AdColony.
public class AdColonyAds {
private final String ZONE_ID = "vzac61b40e83e8436c9e";
private final String APP_ID_ADCOLONY = "appa567471ee29646b5b5";
private AdColonyInterstitial ad;
private AdColonyInterstitialListener listener;
private AdColonyAdOptions ad_options;
private String uniqueID;
private Activity activity;
public AdColonyAds(Activity activity) {
this.activity = activity;
uniqueID = UUID.randomUUID().toString();
}
public void initAdColony(){
AdColonyAppOptions app_options = new AdColonyAppOptions()
.setUserID(uniqueID);
AdColony.configure( activity, app_options, APP_ID_ADCOLONY, ZONE_ID );
AdColonyUserMetadata metadata = new AdColonyUserMetadata()
.setUserAge( 26 )
.setUserEducation( AdColonyUserMetadata.USER_EDUCATION_BACHELORS_DEGREE )
.setUserGender( AdColonyUserMetadata.USER_MALE );
ad_options = new AdColonyAdOptions()
.enableConfirmationDialog( true )
.enableResultsDialog( true )
.setUserMetadata( metadata );
AdColony.setRewardListener( new AdColonyRewardListener()
{
#Override
public void onReward( AdColonyReward reward )
{
reward.getRewardAmount();
}
} );
listener = new AdColonyInterstitialListener() {
#Override
public void onRequestFilled(AdColonyInterstitial adColonyInterstitial) {
Toast.makeText(activity,"Ready",Toast.LENGTH_SHORT).show();
adColonyInterstitial.show();
}
};
}
public void showAdColony(){
ad.show();
}
public void loadAd(){
AdColony.requestInterstitial( ZONE_ID, listener, ad_options );
}
}

You may need to set ad instance variable at onRequestFilled listener to use after from showAdColony method.
listener = new AdColonyInterstitialListener() {
#Override
public void onRequestFilled(AdColonyInterstitial adColonyInterstitial) {
ad = adColonyInterstitial;
}
};

Related

Android Studio Get String From All Activities

I'm generating a random string in MainActivity. When i'm using intent method, I can calling and put this string in SecondActivity. But i can't call this string from all activities. How can i do this
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
Several options are available to you - in this case, because it wont introduce any extra dependencies (RxJava, EventBus, etc.), I'd recommend you write it to SharedPreferences, and have your other activities register a listener on SharedPreferences for changes to your value:
public class SaltStringPreference {
private static final String KEY = "a_key";
private final SharedPreferences prefs;
private Listener listener;
private SaltStringPreference(SharedPreferences prefs) {
this.prefs = prefs;
}
public static SaltStringPreference from(Context context) {
return new SaltStringPreference(PreferenceManager.getDefaultSharedPreferences(context));
}
public void set(String saltString) {
prefs.edit().putString(KEY, saltString).apply();
}
public String get() {
return prefs.getString(KEY, "<no_value>");
}
/*
Note we need to keep a reference to the listener somewhere,
otherwise it could be garbage collected, see
https://stackoverflow.com/a/3104265/1219389
*/
public void setListener(Listener listener) {
this.listener = listener;
prefs.registerOnSharedPreferenceChangeListener(listener);
}
public void removeListener() {
prefs.unregisterOnSharedPreferenceChangeListener(listener);
this.listener = null;
}
public static abstract class Listener implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(KEY.equals(key)) {
onSaltStringChanged(sharedPreferences.getString(KEY, "<no_value>"));
}
}
/**
* Called when the 'salt string' value changes in SharedPreferences
* #param saltString The new 'salt string' value
*/
protected abstract void onSaltStringChanged(String saltString);
}
}
class ActivityOne extends AppCompatActivity {
//...
SaltStringPreference.from(this).set(generatedSaltString);
}
class AnotherActivity extends AppCompatActivity {
private final SaltStringPreference.Listener listener = new SaltStringPreference.Listener() {
#Override
protected void onSaltStringChanged(String saltString) {
//Do something with new String...
}
});
private SaltStringPreference pref;
//onCreate...
pref = SaltStringPreference.create(this);
pref.setListener(listener);
//onDestroy...
pref.removeListener();
}
Use static Method, You can call the method to all activities.
public Class UtilClass{
public static String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
}

How can I save user messages and history to room database

I am developing a chat app and I want to save user chat history and messages using room database. By this, when the users start the app they can see their previous history and messages.
Below my User.java model class where implemented user model properties.
#Entity
public class User implements IChatUser {
#PrimaryKey(autoGenerate = true)
private Integer id;
#ColumnInfo(name = "name")
String name;
#Ignore
Bitmap icon;
public User() {
}
public User(int id, String name, Bitmap icon) {
this.id = id;
this.name = name;
this.icon = icon;
}
#Override
public String getId() {
return this.id.toString();
}
#Override
public String getName() {
return this.name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
#Override
public Bitmap getIcon() {
return this.icon;
}
#Override
public void setIcon(Bitmap icon) {
this.icon = icon;
}
}
UserDao.java
#Dao
public interface UserDao {
#Query("SELECT * FROM user")
List<User> getUsers();
#Insert
void insert(User user);
#Delete
void delete(User user);
#Update
void update(User user);
}
UserRoomDatabase.java
#Database(entities = {User.class}, version = 1)
public abstract class UserRoomDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
MessengerActivity.java
public class MessengerActivity extends Activity{
#VisibleForTesting
protected static final int RIGHT_BUBBLE_COLOR = R.color.colorPrimaryDark;
#VisibleForTesting
protected static final int LEFT_BUBBLE_COLOR = R.color.gray300;
#VisibleForTesting
protected static final int BACKGROUND_COLOR = R.color.blueGray400;
#VisibleForTesting
protected static final int SEND_BUTTON_COLOR = R.color.blueGray500;
#VisibleForTesting
protected static final int SEND_ICON = R.drawable.ic_action_send;
#VisibleForTesting
protected static final int OPTION_BUTTON_COLOR = R.color.teal500;
#VisibleForTesting
protected static final int RIGHT_MESSAGE_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int LEFT_MESSAGE_TEXT_COLOR = Color.BLACK;
#VisibleForTesting
protected static final int USERNAME_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int SEND_TIME_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int DATA_SEPARATOR_COLOR = Color.WHITE;
#VisibleForTesting
protected static final int MESSAGE_STATUS_TEXT_COLOR = Color.WHITE;
#VisibleForTesting
protected static final String INPUT_TEXT_HINT = "New message..";
#VisibleForTesting
protected static final int MESSAGE_MARGIN = 5;
private ChatView mChatView;
private MessageList mMessageList;
private ArrayList<User> mUsers;
private int mReplyDelay = -1;
Realm realm;
private static final int READ_REQUEST_CODE = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messenger);
initUsers();
mChatView = findViewById(R.id.chat_view);
//Load saved messages
loadMessages(realm);
//Set UI parameters if you need
mChatView.setRightBubbleColor(ContextCompat.getColor(this,RIGHT_BUBBLE_COLOR));
mChatView.setLeftBubbleColor(ContextCompat.getColor(this, LEFT_BUBBLE_COLOR));
mChatView.setBackgroundColor(ContextCompat.getColor(this, BACKGROUND_COLOR));
mChatView.setSendButtonColor(ContextCompat.getColor(this, SEND_BUTTON_COLOR));
mChatView.setSendIcon(SEND_ICON);
mChatView.setOptionIcon(R.drawable.ic_account_circle);
mChatView.setOptionButtonColor(OPTION_BUTTON_COLOR);
mChatView.setRightMessageTextColor(RIGHT_MESSAGE_TEXT_COLOR);
mChatView.setLeftMessageTextColor(LEFT_MESSAGE_TEXT_COLOR);
mChatView.setUsernameTextColor(USERNAME_TEXT_COLOR);
mChatView.setSendTimeTextColor(SEND_TIME_TEXT_COLOR);
mChatView.setDateSeparatorColor(DATA_SEPARATOR_COLOR);
mChatView.setMessageStatusTextColor(MESSAGE_STATUS_TEXT_COLOR);
mChatView.setInputTextHint(INPUT_TEXT_HINT);
mChatView.setMessageMarginTop(MESSAGE_MARGIN);
mChatView.setMessageMarginBottom(MESSAGE_MARGIN);
mChatView.setMaxInputLine(5);
mChatView.setUsernameFontSize(getResources().getDimension(R.dimen.font_small));
mChatView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
mChatView.setInputTextColor(ContextCompat.getColor(this, R.color.red500));
mChatView.setInputTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
mChatView.setOnBubbleClickListener(new Message.OnBubbleClickListener() {
#Override
public void onClick(Message message) {
mChatView.updateMessageStatus(message, MyMessageStatusFormatter.STATUS_SEEN);
Toast.makeText(
MessengerActivity.this,
"click : " + message.getUser().getName() + " - " + message.getText(),
Toast.LENGTH_SHORT
).show();
}
});
mChatView.setOnIconClickListener(new Message.OnIconClickListener() {
#Override
public void onIconClick(Message message) {
Toast.makeText(
MessengerActivity.this,
"click : icon " + message.getUser().getName(),
Toast.LENGTH_SHORT
).show();
}
});
mChatView.setOnIconLongClickListener(new Message.OnIconLongClickListener() {
#Override
public void onIconLongClick(Message message) {
Toast.makeText(
MessengerActivity.this,
"Removed this message \n" + message.getText(),
Toast.LENGTH_SHORT
).show();
mChatView.getMessageView().remove(message);
}
});
//Click Send Button
mChatView.setOnClickSendButtonListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initUsers();
//new message
Message message = new Message.Builder()
.setUser(mUsers.get(0))
.setRight(true)
.setText(mChatView.getInputText())
.hideIcon(true)
.setStatusIconFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusTextFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusStyle(Message.Companion.getSTATUS_ICON())
.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED)
.build();
//Set to chat view
mChatView.send(message);
//Add message list
mMessageList.add(message);
//Reset edit text
mChatView.setInputText("");
receiveMessage(message.getText());
}
});
//Click option button
mChatView.setOnClickOptionButtonListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
}
private void openGallery() {
Intent intent;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
private void receiveMessage(String sendText) {
//Ignore hey
if (!sendText.contains("hey")) {
//Receive message
final Message receivedMessage = new Message.Builder()
.setUser(mUsers.get(1))
.setRight(false)
.setText(ChatBot.INSTANCE.talk(mUsers.get(0).getName(), sendText))
.setStatusIconFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusTextFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusStyle(Message.Companion.getSTATUS_ICON())
.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED)
.build();
if (sendText.equals( Message.Type.PICTURE.name())) {
receivedMessage.setText("Nice!");
}
// This is a demo bot
// Return within 3 seconds
if (mReplyDelay < 0) {
mReplyDelay = (new Random().nextInt(4) + 1) * 1000;
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mChatView.receive(receivedMessage);
//Add message list
mMessageList.add(receivedMessage);
}
}, mReplyDelay);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != READ_REQUEST_CODE || resultCode != RESULT_OK || data == null) {
return;
}
Uri uri = data.getData();
try {
Bitmap picture = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Message message = new Message.Builder()
.setRight(true)
.setText(Message.Type.PICTURE.name())
.setUser(mUsers.get(0))
.hideIcon(true)
.setPicture(picture)
.setType(Message.Type.PICTURE)
.setStatusIconFormatter(new MyMessageStatusFormatter(MessengerActivity.this))
.setStatusStyle(Message.Companion.getSTATUS_ICON())
.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED)
.build();
mChatView.send(message);
//Add message list
mMessageList.add(message);
receiveMessage(Message.Type.PICTURE.name());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.error), Toast.LENGTH_SHORT).show();
}
}
private void initUsers() {
mUsers = new ArrayList<>();
//User id
int myId = 0;
//User icon
Bitmap myIcon = BitmapFactory.decodeResource(getResources(), R.drawable.face_2);
//User name
String myName = "Michael";
int yourId = 1;
Bitmap yourIcon = BitmapFactory.decodeResource(getResources(), R.drawable.face_1);
String yourName = "Emily";
final User me = new User(myId, myName, myIcon);
final User you = new User(yourId, yourName, yourIcon);
mUsers.add(me);
mUsers.add(you);
}
/**
* Load saved messages
* #param realm
*/
private void loadMessages(Realm realm) {
List<Message> messages = new ArrayList<>();
mMessageList = AppData.getMessageList(this);
if (mMessageList == null) {
mMessageList = new MessageList();
} else {
for (int i = 0; i < mMessageList.size(); i++) {
Message message = mMessageList.get(i);
//Set extra info because they were removed before save messages.
for (IChatUser user : mUsers) {
if (message.getUser().getId().equals(user.getId())) {
message.getUser().setIcon(user.getIcon());
}
}
if (!message.isDateCell() && message.isRight()) {
message.hideIcon(true);
}
message.setStatusStyle(Message.Companion.getSTATUS_ICON_RIGHT_ONLY());
message.setStatusIconFormatter(new MyMessageStatusFormatter(this));
message.setStatus(MyMessageStatusFormatter.STATUS_DELIVERED);
messages.add(message);
}
}
MessageView messageView = mChatView.getMessageView();
messageView.init(messages);
messageView.setSelection(messageView.getCount() - 1);
}
#Override
public void onResume() {
super.onResume();
initUsers();
}
#Override
public void onPause() {
super.onPause();
//Save message
mMessageList = new MessageList();
mMessageList.setMessages(mChatView.getMessageView().getMessageList());
AppData.putMessageList(this, mMessageList);
}
#VisibleForTesting
public ArrayList<User> getUsers() {
return mUsers;
}
public void setReplyDelay(int replyDelay) {
mReplyDelay = replyDelay;
}
private void showDialog() {
final String[] items = {
getString(R.string.send_picture),
getString(R.string.clear_messages)
};
new AlertDialog.Builder(this)
.setTitle(getString(R.string.options))
.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position) {
switch (position) {
case 0 :
openGallery();
break;
case 1:
mChatView.getMessageView().removeAll();
break;
}
}
})
.show();
}
}
You should create a new room database to store your messages. It's table should look like this:
id
message
sendingUser
receivingUser
0
Hello how are you?
John
David
1
Thanks, im good.
David
John
2
good to hear that!
John
David
First create a new Message class. This class should look like this:
#Entity(tableName = "message_table")
data class Message(
#PrimaryKey(autoGenerate = true)
var id: Int,
#ColumnInfo(name= "message")
var message: String,
#ColumnInfo(name = "sendingUser")
var sendingUser: String,
#ColumnInfo(name = "receivingUser")
var receivingUser: String
)
Then create your MessageDatabase, like this:
#Database(entities = [Message::class], version = 1)
abstract class MessageDatabase: RoomDatabase() {
abstract fun messageDao(): MessageDao
}
Next create your MessageDao
#Dao
interface MessageDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(message: Message)
#Query("SELECT ALL * FROM message_table WHERE sendingUser= :sendingUser")
suspend fun getMessageListFromSender(sendingUser: String): MutableList<Message>
#Query("SELECT ALL * FROM message_table")
suspend fun getMessageList(): MutableList<Message>
#Delete
suspend fun delete(message: Message)
#Update
suspend fun update(message: Message)
}
At last you can initialize your room database like this:
private val roomDb = Room.databaseBuilder(
getApplication(),
MessageDatabase::class.java, "message_database"
).build()
private val messageDao = roomDb.messageDao()
Use messageDao, to make operations with the database, this example shows you how to get message list from a certain sender:
suspend fun getMessageListFromSender(sendingUser: String): MutableList<Message> {
var list : MutableList<Message>
with (messageDao) {
list = this.getMessageListFromSender(sendingUser)
}
return list
}
viewModelScope.launch {
getMessageListFromSender("John")
}

Errors when trying to save strings, ints and spinner values to room persistence database in Android Studio

I'm trying to create a database within my step counting program that is able to save a user's details: Name, Age, Gender, Average Stride Length, Weight and Height in Android Studio. However I keep encountering errors that I am unable to locate or solve. Apologies if it is a rookie mistake; I am not in possession of a great deal of experience for Android Studio or the Room Persistence Library. Here is the code in question:
UserDetails.java:
#Entity(tableName = "user details")
public class UserDetails extends AppCompatActivity {
#NonNull
//each value for the primary key will be assigned a unique,
// automatically generated UserID
#PrimaryKey (autoGenerate = true)
#ColumnInfo(name = "ID")
public int UserID;
#ColumnInfo(name = "Name")
public String UserName;
#ColumnInfo(name = "Age")
public int UserAge;
#ColumnInfo(name = "Gender")
public String UserGender;
#ColumnInfo(name = "Average Stride Length")
public int UserAveStride;
#ColumnInfo(name = "Weight")
public int UserWeight;
#ColumnInfo(name = "Height")
public int UserHeight;
public UserDetails() {
}
#Ignore
public UserDetails(String userName, int userAge, String userGender, int
userAveStride, int userWeight, int userHeight) {
UserName = userName;
UserAge = userAge;
UserGender = userGender;
UserAveStride = userAveStride;
UserWeight = userWeight;
UserHeight = userHeight;
}
public int getUserID() {
return UserID;
}
public void setUserID(int userID) {
UserID = userID;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public int getUserAge() {
return UserAge;
}
public void setUserAge(int userAge) {
UserAge = userAge;
}
public String getUserGender() {
return UserGender;
}
public void setUserGender(String userGender) {
UserGender = userGender;
}
public int getUserAveStride() {
return UserAveStride;
}
public void setUserAveStride(int userAveStride) {
UserAveStride = userAveStride;
}
public int getUserWeight() {
return UserWeight;
}
public void setUserWeight(int userWeight) {
UserWeight = userWeight;
}
public int getUserHeight() {
return UserHeight;
}
public void setUserHeight(int userHeight) {
UserHeight = userHeight;
}
#Override
public String toString(){
return new
StringBuilder(UserName).append("\n").append(UserAge).append("\n")
.append(UserGender).append("\n").append(UserAveStride).append("\n")
.append(UserWeight).append("\n").append(UserHeight).toString();
}
DbContent.java
public class DbContent extends AppCompatActivity {
private ListView lstUser;
private FloatingActionButton fab;
//array adapter
List<UserDetails> userList;
ArrayAdapter adapter;
//database
private CompositeDisposable compositeDisposable;
private UserRepository userRepository;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db_content);
//init
compositeDisposable = new CompositeDisposable();
//init view
lstUser = findViewById(R.id.lstUsers);
fab = findViewById(R.id.fab);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
userList);
registerForContextMenu(lstUser);
lstUser.setAdapter(adapter);
//creating database
Database database = Database.getmInstance(this);
userRepository =
UserRepository.getmInstance(UserDataSource.getmInstance(database.userDao()));
//load all data from database
loadData();
//getting values from user inputs
final EditText name = findViewById(R.id.nameInput);
final EditText age = findViewById(R.id.ageInput);
final Spinner gender = findViewById(R.id.genderDropDown);
final EditText aveStride = findViewById(R.id.strideInput);
final EditText weight = findViewById(R.id.weightInput);
final EditText height = findViewById(R.id.heightInput);
//converting to strings
final String nameStr = name.getText().toString();
final String ageStr = age.getText().toString();
final String genderStr = gender.getSelectedItem().toString();
final String aveStrideStr = aveStride.getText().toString();
final String weightStr = weight.getText().toString();
final String heightStr = height.getText().toString();
//converting string to int where needed
final int ageInt = Integer.parseInt(ageStr);
final int aveStrideInt = Integer.parseInt(aveStrideStr);
final int weightInt = Integer.parseInt(weightStr);
final int heightInt = Integer.parseInt(heightStr);
//Event
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Add new
Disposable disposable = (Disposable) io.reactivex
.Observable.create(new ObservableOnSubscribe<Object>() {
#Override
public void subscribe(ObservableEmitter<Object> e) throws
Exception {
UserDetails userDetails = new UserDetails(nameStr,
ageInt,
genderStr, aveStrideInt, weightInt, heightInt);
userRepository.insertUser(userDetails);
e.onComplete();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer() {
#Override
public void accept(Object o) throws Exception {
Toast.makeText(DbContent.this,
"Data added", Toast.LENGTH_SHORT).show();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(DbContent.this,
"" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
//Refreshing data
}, new Action() {
#Override
public void run() throws Exception {
loadData();
}
}
);
}
});
}
private void loadData() {
//Using RXJava
Disposable disposable = userRepository.getAllDetails()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<List<UserDetails>>() {
#Override
public void accept(List<UserDetails> userDetails) throws Exception {
OnGetAllDetailsSuccess(userDetails);
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(DbContent.this, ""+throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
compositeDisposable.add(disposable);
}
private void OnGetAllDetailsSuccess(List<UserDetails> userDetails) {
userList.clear();
userList.addAll(userDetails);
adapter.notifyDataSetChanged();
}
}
Database.java
#android.arch.persistence.room.Database(entities = {UserDetails.class},
version = DATABASE_VERSION)
public abstract class Database extends RoomDatabase {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME ="Database-Room";
public abstract UserDao userDao();
private static Database mInstance;
public static Database getmInstance(Context context)
{
if (mInstance == null){
mInstance = Room.databaseBuilder(context,Database.class,DATABASE_NAME)
.fallbackToDestructiveMigration()
.build();
}
return mInstance;
}
}
UserDataSource.java
public class UserDataSource implements IUserDataSource {
private UserDao userDao;
private static UserDataSource mInstance;
public UserDataSource(UserDao userDao) {
this.userDao = userDao;
}
public static UserDataSource getmInstance(UserDao userDao) {
if(mInstance == null){
mInstance = new UserDataSource(userDao);
}
return mInstance;
}
#Override
public Flowable<UserDetails> getUserById(int userId) {
return userDao.getUserById(userId);
}
#Override
public Flowable<List<UserDetails>> getAllDetails() {
return userDao.getAllDetails();
}
#Override
public void insertUser(UserDetails... userDetails) {
userDao.insertUser(userDetails);
}
#Override
public void updateUser(UserDetails... userDetails) {
userDao.updateUser(userDetails);
}
#Override
public void deleteUser(UserDetails userDetails) {
userDao.deleteUser(userDetails);
}
}
UserRepository.java
public class UserRepository implements IUserDataSource {
private IUserDataSource mLocalDataSource;
private static UserRepository mInstance;
public UserRepository(IUserDataSource mLocalDataSource) {
this.mLocalDataSource = mLocalDataSource;
}
public static UserRepository getmInstance(IUserDataSource mLocalDataSource) {
if(mInstance == null){
mInstance = new UserRepository(mLocalDataSource);
}
return mInstance;
}
#Override
public Flowable<UserDetails> getUserById(int userId) {
return mLocalDataSource.getUserById(userId);
}
#Override
public Flowable<List<UserDetails>> getAllDetails() {
return mLocalDataSource.getAllDetails();
}
#Override
public void insertUser(UserDetails... userDetails) {
mLocalDataSource.insertUser(userDetails);
}
#Override
public void updateUser(UserDetails... userDetails) {
mLocalDataSource.updateUser(userDetails);
}
#Override
public void deleteUser(UserDetails userDetails) {
mLocalDataSource.deleteUser(userDetails);
}
}
UserDao.java
#Dao
public interface UserDao {
#Query("SELECT * FROM `user details` WHERE id=:userId")
Flowable<UserDetails> getUserById(int userId);
#Query("SELECT * FROM `user details`")
Flowable<List<UserDetails>> getAllDetails();
#Insert
void insertUser(UserDetails... userDetails);
#Update
void updateUser(UserDetails... userDetails);
#Delete
void deleteUser(UserDetails userDetails);
}
IUserDataSource.java
public interface IUserDataSource {
Flowable<UserDetails> getUserById(int userId);
Flowable<List<UserDetails>> getAllDetails();
void insertUser(UserDetails... userDetails);
void updateUser(UserDetails... userDetails);
void deleteUser(UserDetails userDetails);
}
The errors are:
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
Cannot find getter for field.
Cannot find setter for field.
Cannot figure out how to read this field from a cursor.
Cannot find getter for field.
Cannot find setter for field.
I appreciate any help greatly as I have spent a number of hours trying to fix this and this project is one fifth of my grade; it is due in soon and I need to spend time finishing other features and testing it rather than spending hours trying to fix errors. Thank you.
I believe that the errors you are trying to describe are similar to :-
The cause of these would be that you have made your UserDetails a subclass of the AppCompatActivity class by encoding extends AppCompatActivity
Instead of :-
#Entity(tableName = "user details")
public class UserDetails extends AppCompatActivity { ..........
You should have :-
#Entity(tableName = "user details")
public class UserDetails { ........
Note the dots represent the rest of the code, they are not intended to be coded, they are for the sake of brevity.

Splash Screen using AsyncTask

I have a splash screen using AsyncTask, it will download some data from database and store the data in ArrayList. This ArrayList will be used for RecyclerView in fragments of MainActivity.class.
The problem is when I run the app from Android Studio to my phone, everything works perfectly. But, when I destroy the app and run it manually from my phone it will display blank white screen and then it will crash. And if I run once again after it crashed, the app will work. So, this app will always work only if I run it from Android Studio or after it crashed.
The error says that it is caused by the empty list. If I'm not mistaken, I think the AsyncTask doesn't seem to work properly after the activity is destroyed. But I don't know how to fix it. Please help me to solve this problem.
SplashScreen.java
public class SplashScreenActivity extends AppCompatActivity {
public static Event event;
private static List<Feed> feedList;
private static List<Event> eventList;
private static List<Event> todayList;
private static List<Event> upcomingList;
private static List<Partner> partnerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
Config.TODAY_DATE = String.valueOf(today.monthDay) + "-" + String.valueOf(today.month) + "-" + String.valueOf(today.year);
new DownloadData().execute("");
}
class DownloadData extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
startActivity(new Intent(getBaseContext(), WelcomeActivity.class));
finish();
}
#Override
protected String doInBackground(String... params) {
RequestHandler rh = new RequestHandler();
String JSON_STRING = rh.sendGetRequest(Config.URL_GET_ALL_DATA);
JSONObject jsonObject;
eventList = new ArrayList<>();
todayList = new ArrayList<>();
upcomingList = new ArrayList<>();
partnerList = new ArrayList<>();
feedList = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray getEvent = jsonObject.getJSONArray(Config.TAG_JSON_EVENT);
for (int i = 0; i < getEvent.length(); i++) {
int id = getEvent.getJSONObject(i).getInt(Config.TAG_ID);
int eoId = getEvent.getJSONObject(i).getInt(Config.TAG_EO_ID);
String eoName = getEvent.getJSONObject(i).getString(Config.TAG_EO_NAME);
String title = getEvent.getJSONObject(i).getString(Config.TAG_TITLE);
String day = getEvent.getJSONObject(i).getString(Config.TAG_DAY);
String date = getEvent.getJSONObject(i).getString(Config.TAG_DATE);
int price = getEvent.getJSONObject(i).getInt(Config.TAG_PRICE);
event = new Event(id, eoId, eoName, title, day, date, price);
eventList.add(event);
if(Config.TODAY_DATE.equals(event.getDate())){
todayList.add(event);
} else {
upcomingList.add(event);
}
}
JSONArray getPartner = jsonObject.getJSONArray(Config.TAG_JSON_PARTNER);
for (int i = 0; i < getPartner.length(); i++) {
int pId = getPartner.getJSONObject(i).getInt(Config.TAG_ID);
String pName = getPartner.getJSONObject(i).getString(Config.TAG_NAME);
String pEmail = getPartner.getJSONObject(i).getString(Config.TAG_EMAIL);
String pPhone = getPartner.getJSONObject(i).getString(Config.TAG_PHONE);
String pPhoto = getPartner.getJSONObject(i).getString(Config.TAG_PHOTO_URL);
Partner partner = new Partner(pId, pName, pEmail, pPhone, pPhoto);
partnerList.add(partner);
}
JSONArray getArticle = jsonObject.getJSONArray(Config.TAG_JSON_ARTICLE);
for (int i = 0; i < getArticle.length(); i++) {
int feedId = getArticle.getJSONObject(i).getInt(Config.TAG_ID);
String feedAuthor = getArticle.getJSONObject(i).getString(Config.TAG_FEED_AUTHOR);
String feedTitle = getArticle.getJSONObject(i).getString(Config.TAG_FEED_TITLE);
String feedContent = getArticle.getJSONObject(i).getString(Config.TAG_FEED_CONTENT);
String feedDate = getArticle.getJSONObject(i).getString(Config.TAG_FEED_DATE);
String feedThumbnail = getArticle.getJSONObject(i).getString(Config.TAG_FEED_THUMBNAIL);
Feed feed = new Feed(feedId, feedAuthor, feedTitle, feedContent, feedDate, feedThumbnail);
feedList.add(feed);
}
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
}
public static List<Feed> getFeedList(){ return feedList;}
public static List<Event> getEventList() {return eventList;}
public static List<Event> getTodayList() { return todayList;}
public static List<Event> getUpcomingList() { return upcomingList;}
public static List<Partner> getPartnerList() {return partnerList;}
}
DiscoverFragment.java
public class DiscoverFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
protected View view;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
private List<Feed> feedList;
private List<Event> eventList;
private List<Partner> partnerList;
public DiscoverFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discover, container, false);
RecyclerView recyclerViewEvent = (RecyclerView) view.findViewById(R.id.discover_event_recycler_view);
RecyclerView recyclerViewPartner = (RecyclerView) view.findViewById(R.id.discover_partner_recycler_view);
ClickableViewPager intro_images = (ClickableViewPager) view.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) view.findViewById(R.id.viewPagerCountDots);
eventList = SplashScreenActivity.getEventList();
partnerList = SplashScreenActivity.getPartnerList();
feedList = SplashScreenActivity.getFeedList();
EventAdapter eventAdapter = new EventAdapter(getContext(), eventList);
DiscoverPartnerAdapter discoverPartnerAdapter = new DiscoverPartnerAdapter(getContext(), partnerList);
DiscoverFeedAdapter mAdapter = new DiscoverFeedAdapter(getContext(), feedList);
final LinearLayoutManager layoutManagerEvent = new LinearLayoutManager(getContext());
final LinearLayoutManager layoutManagerPartner = new LinearLayoutManager(getContext());
layoutManagerEvent.setOrientation(LinearLayoutManager.HORIZONTAL);
layoutManagerPartner.setOrientation(LinearLayoutManager.HORIZONTAL);
addBottomDots(0);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(0);
intro_images.addOnPageChangeListener(this);
intro_images.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Config.FEED_ID = position;
startActivity(new Intent(getContext(), ArticleActivity.class));
}
});
return view;
}
private void addBottomDots(int currentPage) {
dots = new ImageView[feedList.size()]; //the problem
pager_indicator.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
if (dots.length > 0)
dots[currentPage].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
LogCat
01-29 00:40:57.565 32535-32535/com.irmaelita.esodiaapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.irmaelita.esodiaapp, PID: 32535
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.addBottomDots(DiscoverFragment.java:181)
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.onCreateView(DiscoverFragment.java:158)
feedList is null. You create feedList instance when DownloadData task is executed. But you call feedList.size() in addBottomDots when fragment view should be created. So, most probably addBottomDots is called before DownloadData task is executed. You need to fix it.
The feedlist in your discover fragment is going empty while initializing. Please set a null check before doing so.It not about running from android studio.If I have understood it correctly you are trying to access a list from splasScreen activity after finishing it. ie in post execute you finish the current activity and the fragment is in main activity,so the list is going null.So if this is the case (and please correct me if not) then either download the data somewhere centrally or best way send it to main activity with intent and use it there. Also when running from android studio kill the app manually and run it again,while the phone is connected and see if it crashes in current scenario.
Send your data from doInBackground to MainActivity with sendBroadcast
Add broadcast method in DownloadData class
private void broadcast(SplashParcel parcel) {
Intent i = new Intent("splash_parcel");
i.putExtra("values", parcel);
sendBroadcast(i);
}
#Override
protected String doInBackground(String... params) {
// your code
// ..
try {
// your code
// ..
// send splashParcel to MainActivity
SplashParcel splashParcel = new SplashParcel(feedList, eventList, todayList, upcomingList, partnerList);
broadcast (splashParcel);
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
Add new class SplashParcel.java
public class SplashParcel implements Parcelable {
public static final Creator<SplashParcel> CREATOR = new Creator<SplashParcel>() {
#Override
public SplashParcel createFromParcel(Parcel in) {
return new SplashParcel(in);
}
#Override
public SplashParcel[] newArray(int size) {
return new SplashParcel[size];
}
};
private static List<Feed> _feedList;
private static List<Event> _eventList;
private static List<Event> _todayList;
private static List<Event> _upcomingList;
private static List<Partner> _partnerList;
protected SplashParcel(Parcel in) {
_feedList = new ArrayList<Feed>();
in.readList(_feedList, null);
_eventList = new ArrayList<Event>();
in.readList(_eventList, null);
_todayList = new ArrayList<Event>();
in.readList(_todayList, null);
_upcomingList = new ArrayList<Event>();
in.readList(_upcomingList, null);
_partnerList = new ArrayList<Partner>();
in.readList(_partnerList, null);
}
public SplashParcel(List<Feed> feedList, List<Event> eventList, List<Event> todayList, List<Event> upcomingList, List<Partner> partnerList) {
_feedList = feedList;
_eventList = eventList;
_todayList = todayList;
_upcomingList = upcomingList;
_partnerList = partnerList;
}
public SplashParcel() {
}
public List<Feed> getFeedList() {
return _feedList;
}
public void setFeedList(List<Feed> feedList) {
_feedList = feedList;
}
public List<Event> getEventList() {
return _eventList;
}
public void setEventList(List<Event> eventList) {
_eventList = eventList;
}
public List<Event> getTodayList() {
return _todayList;
}
public void setTodayList(List<Event> todayList) {
_todayList = todayList;
}
public List<Event> getUpcomingList() {
return _upcomingList;
}
public void setUpcomingList(List<Event> upcomingList) {
_upcomingList = upcomingList;
}
public List<Partner> getPartnerList() {
return _partnerList;
}
public void setPartnerList(List<Partner> partnerList) {
_partnerList = partnerList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(_feedList);
parcel.writeList(_eventList);
parcel.writeList(_todayList);
parcel.writeList(_upcomingList);
parcel.writeList(_partnerList);
}
}
MainActivity.java
// member variable
private BroadcastReceiver _splashReceiver;
private Bundle _bundle = new Bundle();
#Override
protected void onResume() {
super.onResume();
splashReceiver();
}
// receive splashParcel from SplashScreenActivity
private void splashReceiver() {
if (_splashReceiver == null) {
_splashReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SplashParcel splashParcel = intent.getParcelableExtra("values");
if (splashParcel != null) {
// save splashParcel into _budle
_bundle.putParcelable("splash_parcel", splashParcel);
}
}
};
registerReceiver(_splashReceiver, new IntentFilter("splash_parcel"));
}
}
//Send _bundle to DiscoverFragment
private void showDiscoverFragment(){
if(_bundle != null) {
// create instance of discoverFragment with passing _bundle as arguments
DiscoverFragment discoverFragment = new DiscoverFragment();
discoverFragment.setArguments(_bundle);
// replace activity_main.xml with discoverFragment
getSupportFragmentManager().beginTransaction().replace(R.id.main_container, discoverFragment).addBackStack(null).commit();
}
}
In onCreateView of DiscoverFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SplashParcel splashParcel = getArguments().getParcelable("splash_parcel");
if(splashParcel != null) {
// your splashParcel ready in here
List<Feed> feedList = splashParcel.getFeedList()
List<Event> eventList = splashParcel.getEventList()
List<Event> todayList = splashParcel.getTodayList();
List<Event> upcommingList = splashParcel.getUpcomingList();
List<Partner> partnerList = splashParcel.getPartnerList();
}
}

Values duplicating when fetching data from database and displaying to ListView

Im new to Android Developement and currently working on an app that should give me the time between first time clicking a button and second time clicking the button and add it to a currently selected customer.
Current Status of App:
I established a connection to da mySql Database using Volley and a local webservice.
It works to insert my customers and time stamps to the table, but when loading times for a specific customer i get a strange result in one case. I tried debugging it but the app keeps crashing on debugging without a message. When not debugging it doesnt crash but shows weird data.
To the problem:
In my main activity called "ZeitErfassen" i have a button to get an overview of all customers display in a ListView.
I create the Listview with a custom ArrayAdapter because i want to pass my objects to the next Activity where my customers are displayed.
So onCreate of the overview of customers i create a new arraylist and fill it with all customers from my database. this list i pass to my customadapter and then set it as my adapter of the Listview.
Now, when i click on an item, i call a php script and pass the customer_id to the query to fetch all times from database where customer_id = customer_id.
Now the part where i get "strange" data...
1.(Source:ZeitErfassen;Destination:AddCustomer) I create a new customer,example xyz, in the app, data gets passed to the database.
2.(Source:ZeitErfassen;Destination:DisplayCustomer) I call my overview for all customers where the ListView is filled with data as described above. At the end ob the List I see the customer i just created,xyz.
3.Go back to Main Activity(ZeitErfassen)
4.(Source:ZeitErfassen;Destination:DisplayCustomer)I open the overview for all customers again, and it shows my last created user two times! so last entry, xyz, entry before last, xyz!
After that, i can open the view as many times as i want, the customer never gets duplicated again!
The debugger stopps after step 2.
Now when i click on the new customers, it calls the script to fetch the times by customer_id.
One of the xyz entrys display the correct times from database.
The second one, i just found out, display the times where customer_id="". In the database the value for "" is 0.
I have no clue where the second customer suddenly appears from and debugging didnt help me either -.-
When i close the app an open it again, there ist just one entry for the user that was visible twice before closing the app. It doesnt duplicate on opening view...
Here is my code..
Main Activity ZeitErfassen
public class ZeitErfassen extends AppCompatActivity {
public static LinkedList<Kunde> kunden = new LinkedList<Kunde>();
boolean running = false;
long startTime,endTime,totalTime;
private SharedPreferences app_preferences;
private SharedPreferences.Editor editor;
private TextView displayTime;
public Button startEndButton;
private ArrayAdapter<String> adapter;
private Spinner spinner;
public static Kunde selectedCustomer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zeit_erfassen);
//Einstellungen laden
app_preferences = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
startTime= app_preferences.getLong("startTime", 0);
endTime = app_preferences.getLong("endTime", 0);
running = app_preferences.getBoolean("running", false);
displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
startEndButton = (Button)findViewById(R.id.start_Timer);
startEndButton.setText((CharSequence) app_preferences.getString("timerButton", "Start Timer"));
DatabaseHelper.customerFromDatabaseToList(this);
editor = app_preferences.edit();
editor.commit();
}
public void onDestroy() {
super.onDestroy();
editor.putLong("startTime", startTime);
editor.putString("zeitAnzeige", (String) displayTime.getText());
editor.putString("timerButton", (String) startEndButton.getText());
editor.putLong("endTime", endTime);
editor.putLong("totalTime", totalTime);
editor.putBoolean("running", app_preferences.getBoolean("running", false));
editor.commit();
this.finish();
}
public void onResume() {
super.onResume();
// saveCustomers();
// createDropDown();
}
public void startTimer(View view) {
editor = app_preferences.edit();
if(running == false) {
startTime = getTime();
running = true;
editor.putLong("startTime", startTime);
startEndButton.setText("End Timer");
displayTime.setText("Zeitstoppung läuft");
editor.putString("zeitAnzeige", (String) displayTime.getText());
editor.putString("timerButton", (String) startEndButton.getText());
editor.putBoolean("running", true);
editor.commit();
} else {
setSelectedCustomer();
endTime = getTime();
editor.putLong("endTime",endTime);
totalTime = endTime - startTime;
editor.putLong("totalTime", totalTime);
displayTime.setText(formatTime(totalTime));
editor.putString("zeitAnzeige", (String) displayTime.getText());
startEndButton.setText("Start Timer");
editor.putString("timerButton", (String) startEndButton.getText());
running = false;
editor.putBoolean("running", false);
editor.commit();
DatabaseHelper.timeToDatabase(String.valueOf(selectedCustomer.getId()),formatTime(totalTime),this);
// selectedCustomer.saveTimeToCustomer(selectedCustomer, formatTimeForCustomer(totalTime));
}
}
public String formatTime(Long totalTime) {
int hours = (int) ((totalTime / (1000*60*60)) % 24);
int minutes = (int) ((totalTime / (1000*60)) % 60);
int seconds = (int) (totalTime / 1000) % 60;
String time = (String.valueOf(hours) + ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds));
return time;
}
public String formatTimeForCustomer(Long totalTime) {
StringBuilder time = new StringBuilder();
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
time.append((String.valueOf(year) + "." + String.valueOf(month) + "." + String.valueOf(day))).append(formatTime(totalTime));
return time.toString();
}
public void neuerKunde(View view) {
Intent intent = new Intent(this, AddKunde.class);
startActivity(intent);
}
public void kundenÜbersicht(View view) {
// setSelectedCustomer();
Intent intent = new Intent(this, DisplayCustomer.class);
startActivity(intent);
}
public long getTime() {
long millis = System.currentTimeMillis();
return millis;
}
public void setSelectedCustomer() {
if(kunden.size() > 0) {
if (spinner.getSelectedItem().toString() != null) {
String tempCustomer = spinner.getSelectedItem().toString();
for (Kunde k : kunden) {
if (k.getName().equals(tempCustomer)) {
selectedCustomer = k;
}
}
}
}
}
public void createDropDown() {
/*File file = new File(this.getFilesDir(),"kunden.ser"); NOT USED BECAUSE DATABASE WORKS
if(file.exists()) {
Kunde.importFromFile(this);
}*/
if (kunden.size() > 0) {
spinner = (Spinner) findViewById(R.id.chooseCustomer);
// Create an ArrayAdapter using the string array and a default spinner layout
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DisplayCustomer.namesOfCustomers());
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
}
}
DisplayCustomer(Where all customers are displayed with data from Database)
public class DisplayCustomer extends AppCompatActivity {
CustomerAdapter customerAdapter;
public ArrayAdapter<String> adapterCustomerView;
private ListView listCustomerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ArrayList<Kunde> customerList = getCustomerObjects();
customerAdapter = new CustomerAdapter(this,customerList);
listCustomerView = (ListView)findViewById(R.id.list_View_Customers);
// adapterCustomerView = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namesOfCustomers());
listCustomerView.setAdapter(customerAdapter);
openCustomerDetails();
}
public static ArrayList<String> namesOfCustomers() {
ArrayList<String> customerNames = new ArrayList<>();
if(ZeitErfassen.kunden.size() > 0 ) {
for (Kunde k : ZeitErfassen.kunden) {
customerNames.add(k.getName());
}
}
return customerNames;
}
public static ArrayList<Kunde> getCustomerObjects() {
ArrayList<Kunde> customerList = new ArrayList<>();
if(ZeitErfassen.kunden.size() > 0 ) {
for (Kunde k : ZeitErfassen.kunden) {
customerList.add(k);
}
}
return customerList;
}
public void openCustomerDetails() {
listCustomerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Kunde kunde = new Kunde();
kunde = (Kunde)listCustomerView.getItemAtPosition(position);
Intent intent = new Intent(DisplayCustomer.this, DisplayDetailedCustomer.class);
intent.putExtra("selectedCustomerObject",(Parcelable)kunde);
startActivity(intent);
}
});
}
}
My CustomerAdapter to pass data from one intent to another.
public class CustomerAdapter extends ArrayAdapter<Kunde> {
public CustomerAdapter(Context context, ArrayList<Kunde> customerList) {
super(context,0,customerList);
}
public View getView(int position, View convertView, ViewGroup parent) {
//Data for this position
Kunde kunde = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.items_customer_layout, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvCustomerName);
// Populate the data into the template view using the data object
tvName.setText(kunde.getName());
// Return the completed view to render on screen
return convertView;
}
}
DatabaseHelper Class
public class DatabaseHelper {
public static RequestQueue requestQueue;
public static String host = "http://192.168.150.238/";
public static final String insertUrl = host+"insertCustomer.php";
public static final String showUrl = host+"showCustomer.php";
public static final String insertTimeUrl = host+"insertTime.php";
public static final String showTimeUrl = host+"showTimes.php";
public static void customerFromDatabaseToList(final Context context) {
//Display customer from database
requestQueue = Volley.newRequestQueue(context);
final ArrayList<String> customerNames = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray customers = response.getJSONArray("customers");
if(customers.length() > 0) {
for (int i = 0; i < customers.length(); i++) {
JSONObject customer = customers.getJSONObject(i);
String customerName = customer.getString("cus_name");
String customerAddress = customer.getString("cus_address");
int customerID = Integer.valueOf(customer.getString("cus_id"));
if (customerName != null && customerAddress != null) {
try {
Kunde k = new Kunde(customerName, customerAddress, customerID);
if (!listContainsObject(k)) {
ZeitErfassen.kunden.add(k);
}
} catch (Exception e) {
showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
}
} else {
showAlert("Fehler in customerFromDatabaseToListn!", "Fehler", context);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
public static boolean listContainsObject(Kunde cust) {
for(Kunde k : ZeitErfassen.kunden) {
if(k.getId() == cust.getId()) {
return true;
}
}
return false;
}
public static void timeToDatabase(final String customer_id, final String time_value, final Context context) {
requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST, DatabaseHelper.insertTimeUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showAlert("Fehler","Fehler bei Verbindung zur Datenbank",context);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("customerid",customer_id);
parameters.put("timevalue",time_value);
return parameters;
}
};
requestQueue.add(request);
};
public static void showAlert(String title, String message, Context context) {
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(message)
.setTitle(title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
}
public static ArrayList<String> timesFromDataBaseToList(final Context context,final int customer_id) {
requestQueue = Volley.newRequestQueue(context);
final String cus_id = String.valueOf(customer_id) ;
final ArrayList<String> customerTimes = new ArrayList<>();
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, showTimeUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response.toString());
JSONArray times = object.getJSONArray("customertimes");
if (times.length() > 0) {
for (int i = 0; i < times.length(); i++) {
JSONObject jsonObject = times.getJSONObject(i);
String timeValue = jsonObject.getString("time_value");
if (timeValue != null) {
customerTimes.add(timeValue);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Fehler beim Holen der Zeiten",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("cus_id",cus_id);
return parameters;
}
};
requestQueue.add(jsonObjectRequest);
return customerTimes;
};
}
DisplayDetailedCustomer / Display the times
public class DisplayDetailedCustomer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_detailed_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent getCustomerParcable = getIntent();
Kunde customer = getCustomerParcable.getExtras().getParcelable("selectedCustomerObject");
TextView displayCustomerNameDetailed =(TextView) findViewById(R.id.detailedCustomerViewName);
TextView displayCustomerAddressDetailed =(TextView) findViewById(R.id.detailedCustomerAddress);
ListView timeListView = (ListView)findViewById(R.id.detailedTimeListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, DatabaseHelper.timesFromDataBaseToList(this,customer.getId()));
timeListView.setAdapter(adapter);
displayCustomerNameDetailed.setText(customer.getName());
displayCustomerAddressDetailed.setText(customer.getAdresse());
}
}
Kunde Class / Customer Class with interface Parcelable
public class Kunde implements Serializable,Parcelable {
private String name;
private String adresse;
private int id;
public LinkedList<String> zeiten;
public Kunde(String name, String adresse) throws Exception{
setName(name);
setAdresse(adresse);
zeiten = new LinkedList<String>();
}
public Kunde(String name, String adresse,int id) throws Exception{
setName(name);
setAdresse(adresse);
setId(id);
zeiten = new LinkedList<String>();
}
public Kunde(){};
public void setId(int id) {
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name) throws Exception {
if(name != null) {
this.name = name;
} else throw new Exception("Name ist ungueltig! in setName");
}
public void setAdresse(String adresse) throws Exception{
if(adresse != null) {
this.adresse = adresse;
}else throw new Exception("Adresse ist ungueltig! in setAdresse");
}
public String getName() {
return name;
}
public String getAdresse() {
return adresse;
}
public void saveZeit(Long totalTime) {
zeiten.add(String.valueOf(totalTime));
}
public void saveTimeToCustomer(Kunde customer,String time){
customer.zeiten.add(time);
}
//------------------------------------Parcelable Methods to pass Daata from one Intent to another----------------------------------------
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
dest.writeString(this.adresse);
// dest.writeList(this.zeiten);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Kunde> CREATOR = new Parcelable.Creator<Kunde>() {
public Kunde createFromParcel(Parcel in) {
return new Kunde(in);
}
public Kunde[] newArray(int size) {
return new Kunde[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Kunde(Parcel in) {
LinkedList<String> zeiten = null;
id = in.readInt();
name = in.readString();
adresse = in.readString();
}
}
Thanks for taking your time!!

Categories

Resources