Android - TextView setText updates text only sometimes - java

I'm new to android development and I'm stuck with the following issue:
I have objects in a listView. When an item in the list is clicked a detailed page with the information appears. This worked fine until at some point the text was displayed only sometimes. When I go back and click on the very same item the text might get displayed correctly again (or not). I have done a textView.getText() and it displays the correct text in the logcat but the user can't actually see this text displayed in the app (at least not always). I wasn't able to pinpoint the mistake and I cannot reproduce the mistake regularly.
FYI: The genre gets displayed always. But title and author only sometimes.
I am grateful for any help! If you have any codestyle/bestpractice remarks please add those to your answers.
Below you can find the relevant code.
Best,
Marc
Activity passing the data
public class BooksActivity extends AppCompatActivity {
private SQLiteDatabase db;
private final BooksDBOpenHelper dbHelper = new BooksDBOpenHelper(this, DBConstants.DB_NAME, null, 1);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_books);
TextView header = this.findViewById(R.id.tv_header);
header.setText(R.string.books_list);
ImageButton backButton = this.findViewById(R.id.toolbar_back_button);
backButton.setOnClickListener(view -> finish());
}
#Override
protected void onStart() {
super.onStart();
db = dbHelper.getWritableDatabase();
ArrayList<CustomBookItem> bookItems = new ArrayList<>();
String table_name = DBConstants.Books.TABLE_NAME;
String[] columns = {
DBConstants.Books.COLUMN_NAME_TITLE,
DBConstants.Books.COLUMN_NAME_AUTHOR,
DBConstants.Books.COLUMN_NAME_GENRE,
DBConstants.Books.COLUMN_NAME_ON_LOAN,
DBConstants.ID
};
String where = null;
String[] where_args = null;
String group_by = null;
String having = null;
String order_by = null;
Cursor cursor = db.query(table_name, columns, where, where_args, group_by, having, order_by);
while (cursor.moveToNext()) {
bookItems.add(new CustomBookItem(
cursor.getString(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)
));
}
cursor.close();
ListView lvMainList = findViewById(R.id.lv_books_list);
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(this, bookItems);
lvMainList.setAdapter(customArrayAdapter);
lvMainList.setOnItemClickListener((adapterView, view, pos, id) -> {
Log.i("BooksActivity", "item was clicked");
CustomBookItem bookItem = (CustomBookItem) adapterView.getAdapter().getItem(pos);
Intent intent = new Intent(this, BookActivity.class);
intent.putExtra(DBConstants.Books.COLUMN_NAME_TITLE, bookItem.getTitle());
intent.putExtra(DBConstants.Books.COLUMN_NAME_AUTHOR, bookItem.getAuthor());
intent.putExtra(DBConstants.Books.COLUMN_NAME_GENRE, bookItem.getGenre());
intent.putExtra(DBConstants.Books.COLUMN_NAME_ON_LOAN, bookItem.getOnLoan());
intent.putExtra(DBConstants.ID, bookItem.getId());
startActivity(intent);
});
customArrayAdapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
db.close();
}
}
Activity receiving the data
public class BookActivity extends AppCompatActivity {
private Resources resources;
private final BooksDBOpenHelper dbHelper = new BooksDBOpenHelper(this, DBConstants.DB_NAME, null, 1);
private SQLiteDatabase db;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_book);
this.resources = this.getResources();
TextView header = this.findViewById(R.id.tv_header);
header.setText(R.string.book);
ImageButton backButton = this.findViewById(R.id.toolbar_back_button);
backButton.setOnClickListener(view -> finish());
}
#Override
protected void onStart() {
super.onStart();
Intent intent = this.getIntent();
String id = intent.getStringExtra(DBConstants.ID);
TextView tvTitle = this.findViewById(R.id.book_title);
tvTitle.setText(intent.getStringExtra(DBConstants.Books.COLUMN_NAME_TITLE));
Log.d("BookActivity", tvTitle.getText().toString());
TextView tvAuthor = this.findViewById(R.id.book_author);
tvAuthor.setText(intent.getStringExtra(DBConstants.Books.COLUMN_NAME_AUTHOR));
Log.d("BookActivity", tvAuthor.getText().toString());
TextView tvGenre = this.findViewById(R.id.book_genre);
tvGenre.setText(intent.getStringExtra(DBConstants.Books.COLUMN_NAME_GENRE));
Log.d("BookActivity", tvGenre.getText().toString());
View loanBookButton = this.findViewById(R.id.loanBookButton);
View returnBookButton = this.findViewById(R.id.returnBookButton);
if (intent.getStringExtra(DBConstants.Books.COLUMN_NAME_ON_LOAN).equals("0")) {
returnBookButton.setBackgroundColor(this.resources.getColor(R.color.grayed_out));
returnBookButton.setEnabled(false);
} else {
loanBookButton.setBackgroundColor(this.resources.getColor(R.color.grayed_out));
loanBookButton.setEnabled(false);
}
loanBookButton.setOnClickListener(view -> loanBook(id));
returnBookButton.setOnClickListener(view -> returnBook(id));
}
public void returnBook(String id) {
this.db = this.dbHelper.getReadableDatabase();
this.db.execSQL("UPDATE " + DBConstants.Books.TABLE_NAME +
" SET " + DBConstants.Books.COLUMN_NAME_ON_LOAN + "='0' " +
"WHERE id=" + id);
this.finish();
}
public void loanBook(String id) {
this.db = this.dbHelper.getReadableDatabase();
this.db.execSQL("UPDATE " + DBConstants.Books.TABLE_NAME +
" SET " + DBConstants.Books.COLUMN_NAME_ON_LOAN + "='1' " +
"WHERE id=" + id);
this.finish();
}
}
Layout of sending activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/container_header_lyt"
layout="#layout/toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"/>
<ListView
android:id="#+id/lv_books_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/container_header_lyt"/>
</RelativeLayout>
Layout of receiving activity
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/container_header_lyt"
layout="#layout/toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/loanBookButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="64dp"
android:layout_marginTop="580dp"
android:layout_marginEnd="229dp"
android:layout_marginBottom="103dp"
android:text="#string/loan_book_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/returnBookButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginStart="229dp"
android:layout_marginTop="580dp"
android:layout_marginEnd="64dp"
android:layout_marginBottom="103dp"
android:text="#string/return_book_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/book_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="176dp"
android:layout_marginTop="174dp"
android:layout_marginEnd="176dp"
android:layout_marginBottom="487dp"
android:textAlignment="center"
android:textSize="32sp"
app:layout_constraintBottom_toTopOf="#+id/loanBookButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/book_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="176dp"
android:layout_marginTop="69dp"
android:layout_marginEnd="176dp"
android:layout_marginBottom="399dp"
android:textSize="28sp"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/loanBookButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/book_title" />
<TextView
android:id="#+id/book_genre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="176dp"
android:layout_marginTop="69dp"
android:layout_marginEnd="176dp"
android:layout_marginBottom="311dp"
android:textSize="28sp"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/loanBookButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/book_author" />
</androidx.constraintlayout.widget.ConstraintLayout>
Edit
I restructured the layout of the receiving activity by changing it from a constraint layout to a relative. I don't know why this worked but it fixed my problem.

Related

Messages are not showing, Firebase Chat

After message sending it isn't showing. But I'm receiving the message in Firebase Database. What's wrong with it? Have you any suggestions?
MainActivity.class
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
FirebaseUser currentUser;
private FirebaseListAdapter<ChatMessage> adapter;
private final static String TAG = "LOG";
EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
checkAuth();
input = (EditText)findViewById(R.id.input);
FloatingActionButton fab =
(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().equals(null) && input.getText().toString().equals("")) {
Log.i(TAG, "Mesage is empty");
} else {
// Read the input field and push a new instance
// of ChatMessage to the Firebase database
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance()
.getCurrentUser()
.getDisplayName())
);
displayChatMessages();
// Clear the input
input.setText("");
}
}
});
}
private void displayChatMessages() {
ListView listOfMessages = (ListView) findViewById(R.id.list_of_messages);
//Suppose you want to retrieve "chats" in your Firebase DB:
Query query = FirebaseDatabase.getInstance().getReference();
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.setLayout(R.layout.message)
.build();
//Finally you pass them to the constructor here:
adapter = new FirebaseListAdapter<ChatMessage>(options){
#Override
protected void populateView(View v, ChatMessage model, int position) {
// Get references to the views of message.xml
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
TextView messageTime = (TextView) v.findViewById(R.id.message_time);
// Set their text
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
Log.i(TAG, model.getMessageUser() + ": " + model.getMessageText());
// Format the date before showing it
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
public void checkAuth(){
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
displayChatMessages();
///
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
}
#Override
public void onStart() {
super.onStart();
checkAuth();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#id/fab"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/fab">
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:tint="#android:color/white"
app:fabSize="mini"
app:layout_constraintStart_toStartOf="#+id/textInputLayout"
/>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="16dp"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/message_user"
android:layout_alignParentEnd="true"
android:id="#+id/message_time" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/message_user"
android:layout_alignParentStart="true"
android:layout_marginTop="5dp"
android:id="#+id/message_text"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textSize="18sp" />
By the way, it's not a good solution to obey type more text.
It looks like your post is mostly code; please add some more details.

How to make messages appear on different sides?

I make a chat app using a video tutorial, but this tutorial does not show how to make messages from different people appear on different sides. The sender and receiver see all messages on the left. Could you please give some advices on this? Thanks in advance.
Now it looks like this
Main code
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE=1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SIGN_IN_CODE) {
if(requestCode == RESULT_OK) {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
} else {
Snackbar.make(activity_main, "You are not authorized", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText textField = findViewById(R.id.messageField);
if(textField.getText().toString().equals(""))
return;
FirebaseDatabase.getInstance().getReference().push().setValue(
new Message(
FirebaseAuth.getInstance().getCurrentUser().getEmail(),
textField.getText().toString()));
textField.setText("");
}
});
//Пользователь ещё не авторизован
if (FirebaseAuth.getInstance().getCurrentUser()==null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
//Пользователь авторизован
else {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
private void displayAllMessages() {
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Message> options =
new FirebaseListOptions.Builder<Message>()
.setQuery(FirebaseDatabase.getInstance().getReference(), Message.class)
.setLayout(R.layout.list_item)
.build();
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Message Class
public class Message {
private String UserName;
private String TextMessage;
private long MessageTime;
public Message() {}
public Message (String UserName, String TextMessage){
this.UserName = UserName;
this.TextMessage = TextMessage;
this.MessageTime = new Date().getTime();
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getTextMessage() {
return TextMessage;
}
public void setTextMessage(String textMessage) {
TextMessage = textMessage;
}
public long getMessageTime() {
return MessageTime;
}
public void setMessageTime(long messageTime) {
MessageTime = messageTime;
}
}
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/activity_main">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send_button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
app:fabSize="normal">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#id/btnSend"
>
<EditText
android:id="#+id/messageField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Message..."
/>
</com.google.android.material.textfield.TextInputLayout>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/text_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
XML for the message bubbles
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Try adding layout_gravity attribute in your BubbleTextView when you need this like this:
android:layout_gravity="right"
Every user will have a unique email - Let say here in the example - d#mail.ru is your email. You need to add user logic to dynamically check to decide whether you want a bubble test layout to be LEFT or RIGHT.
Update the message bubble layout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Adapter code:- you can update as you need either LEFT or RIGHT.
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
RelativeLayout Layout = v.findViewById(R.id.parentlayout);
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
if(!model.getUserName().equals("d#mail.ru")) {
mess_text.setGravity(Gravity.LEFT)
} else {
mess_text.setGravity(Gravity.RIGHT)
}
}
};
Check this link as a reference - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java

Is there a way to save tablerows into Firebase? Realtime or Firestore?

I made this mobile app that can add table rows after pressing a button. Each row contains an Edittext, four dropdown menus (spinners), and a button that deletes a row. Each row is like a duplicate after I press the button "add". Now, my only problem is how to save that specific content into firebase's real-time database or could firestore. Do you guys have recommendations of how to do this, any resources, or is this question is broad? I can specify some things you're confused.
I can save an edit text that holds the title for the document, and it successfully works, except the table rows because it holds multiple data types. I just heard that firebase can only hold primitive datatypes.
This is the code that is relevant to the problem, so I won't have to paste all 357 lines of code.
private android.support.v7.widget.Toolbar maintoolbar, editToolBar;
private FirebaseAuth mAuth;
private FloatingActionButton fab;
private RelativeLayout layoutMain;
private RelativeLayout layoutButtons;
private RelativeLayout layoutContent;
private boolean isOpen = false;
private Button addnewRowButton, saveItButton;
private EditText titleofDoc;
private Context context = null;
private ProgressBar pb;
private DatabaseReference dr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
dr = FirebaseDatabase.getInstance().getReference().child("Notes").child(mAuth.getCurrentUser().getUid());
maintoolbar = findViewById(R.id.mainToolBar);
setSupportActionBar(maintoolbar);
getSupportActionBar().setTitle("Files");
layoutMain = findViewById(R.id.mainLays);
layoutButtons = findViewById(R.id.layoutButtons);
layoutContent = findViewById(R.id.layoutContent);
addnewRowButton = findViewById(R.id.AddRow);
saveItButton = findViewById(R.id.SaveThis);
titleofDoc = findViewById(R.id.TitleofDoc);
editToolBar = findViewById(R.id.main_edit_toolbar);
pb = findViewById(R.id.progressBar2);
saveItButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = titleofDoc.getText().toString().trim();
if (!TextUtils.isEmpty(title)) {
pb.setVisibility(View.VISIBLE);
createNew(title);
pb.setVisibility(View.INVISIBLE);
} else {
Snackbar.make(v, "Fill Empty Fields", Snackbar.LENGTH_SHORT).show();
pb.setVisibility(View.INVISIBLE);
}
}
});
addnewRowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addNewRow();
}
});
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewMenu();
}
});
}
This is the method that makes the table rows.
private void addNewRow() {
final TableLayout tl = findViewById(R.id.tbllays);
String[] teamRoles = {"Director", "Marketing", "Team", "All"};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, teamRoles);
context = getApplicationContext();
//adds new row
final TableRow tbr = new TableRow(context);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
tbr.setLayoutParams(layoutParams);
//add edittext to name the task
EditText editText = new EditText(context);
editText.setHint("Add Task");
tbr.addView(editText, 0);
//add spinner to assign teams
Spinner toDo = new Spinner(context);
toDo.setAdapter(adapter);
tbr.addView(toDo, 1);
//add spinner to assign teams
Spinner InProgress = new Spinner(context);
InProgress.setAdapter(adapter);
tbr.addView(InProgress, 2);
//add spinner to assign teams
Spinner Test = new Spinner(context);
Test.setAdapter(adapter);
tbr.addView(Test, 3);
//add spinner to assign teams
Spinner Done = new Spinner(context);
Done.setAdapter(adapter);
tbr.addView(Done, 4);
// Add a button in the second column
Button button = new Button(context);
button.setText("X");
tbr.addView(button, 5);
button.setBackgroundColor(Color.rgb(159, 168, 218));
// Get delete table row button.
Button deleteRowButton = (Button) button;
deleteRowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tbr.removeAllViews();
}
});
tl.addView(tbr);
}
This is the method that can only save the title instead of the content (the table rows in this case).
private void createNew(String title) {
if (mAuth.getCurrentUser() != null) {
final DatabaseReference newThingRef = dr.push();
final Map thingMap = new HashMap();
thingMap.put("title", title);
thingMap.put("timestamp", ServerValue.TIMESTAMP);
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
newThingRef.setValue(thingMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Note added", Toast.LENGTH_SHORT).show();
Intent MainIntent = new Intent(MainActivity.this, MainActivity.class);
startActivity(MainIntent);
} else {
String error = task.getException().getMessage();
Toast.makeText(MainActivity.this, "ERROR: " + error, Toast.LENGTH_LONG).show();
}
}
});
}
});
mainThread.start();
} else {...}
}
This is the xml file (the part where the editor is held)
<RelativeLayout
android:id="#+id/layoutContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/mainToolBar"
>
<RelativeLayout
android:id="#+id/layoutButtons"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:gravity="center"
android:visibility="gone">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainEditor">
<LinearLayout
android:id="#+id/LinLay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="370dp">
<android.support.v7.widget.Toolbar
android:id="#+id/main_edit_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme" />
<ProgressBar
android:id="#+id/progressBar2"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:indeterminate="true" />
<EditText
android:id="#+id/TitleofDoc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:ellipsize="end"
android:hint="#string/title"
android:importantForAutofill="no"
android:inputType=""
android:maxHeight="1dp"
android:maxLength="30"
android:maxLines="1"
android:padding="10dp"
tools:targetApi="o" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:alpha=".3"
android:background="#android:color/black" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<TableLayout
android:id="#+id/tbllays"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/AddRow"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_weight=".1"
android:background="#color/colorAccent"
android:text="#string/add_row"
android:textColor="#color/colorPrimaryDark" />
<Button
android:id="#+id/SaveThis"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_weight=".1"
android:background="#color/colorPrimaryDark"
android:text="#string/save" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:text="#string/task" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="#string/to_do" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_weight=".1"
android:text="#string/in_progress" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="3"
android:layout_weight=".1"
android:text="#string/testing" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="4"
android:layout_weight=".1"
android:text="#string/done" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="5"
android:layout_weight=".1"
android:text="#string/delete" />
</TableRow>
</TableLayout>
</HorizontalScrollView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
</RelativeLayout>
Ignore the user part, that is only if the user is signed in.
This is how it runs
You need to add an Listener at the end of each spinner and store in in the variable for example:
Spinner Done = new Spinner(context);
Done.setAdapter(adapter);
Done.setOnItemSelectedListner(this)
tbr.addView(Done, 4);
Then store this variable Done using DatabaseReference
You don't actually want to save the rows, you want to save the underlying content.
Instead of thinking of the on-screen rows as the content itself, think of them as just displaying your underlying content. This underlying content can be backed up, modified, whatever you want, whilst the representation of it on screen can be completely reconstructed at any time.
To convert your code, I'd suggest the following series of steps:
Create something like a Task class, that has all the fields you want (e.g. name, team).
Store a list of Tasks in your current Activity / Fragment class, e.g. private List<Task> myTasks.
Write a method displayTasks that removes all existing rows from your layout, then iterates through myTasks and draws them all to the screen.
Change addNewRow so that it adds a new Task to myTasks, then calls displayTasks.
You now have a list of Tasks, which can be written directly into Cloud Firestore, and be retrieved later.
I'm fully aware this answer isn't the simple "just do x" you're after, but it's the answer you actually need! All of the steps are very simple, and of course feel free to modify them for your use case.
Once you're comfortable with the concept of "what's on screen isn't my data, just a representation of it", you may want to look into LiveData and ViewModel. They're trickier, but with a lot of benefits (explained within the links).

how to show SQLite data in simpleadapter

I am facing an issue. i am trying to show sqlite data in the simple adapter but the data is not showing up in my application i don't know what is the wrong. i am new to android development need help.....
Here is my code
public class user extends AppCompatActivity {
sqlite_database database;
ListView listView;
ArrayList<HashMap<String, String>> arrayList;
String stname,stfname,contact;
HashMap<String, String> hmap;
String n,f,c;
TextView studentName, studentFatherName,studnetContact;
Button show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
database = new sqlite_database(getApplicationContext());
listView=(ListView)findViewById(R.id.userlistView);
show = (Button)findViewById(R.id.btnShoww);
studentName = (TextView)findViewById(R.id.studentName);
studentFatherName = (TextView)findViewById(R.id.studentFName);
studnetContact = (TextView)findViewById(R.id.studentContact);
studentName.setText(n);
studentFatherName.setText(f);
studnetContact.setText(c);
ShowData();
arrayList = new ArrayList<HashMap<String,String>>();
try{
Cursor c = database.showAllStudentData();
while(c.moveToNext())
{
hmap= new HashMap<String, String>();
stname=c.getString(0);
hmap.put("n", stname);
stfname=c.getString(1);
hmap.put("f", stfname);
contact=c.getString(2);
hmap.put("c", contact);
arrayList.add(hmap);
}
}
catch(Exception e){
Log.e("error",e.getMessage());
}
String from[]={n,f,c};
int to[]={R.id.studentName,R.id.studentFName,R.id.studentContact};
SimpleAdapter adapter = new SimpleAdapter(this, arrayList, R.layout.user_info_layout, from, to);
listView.setAdapter(adapter);
}
public void ShowData()
{
show.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = database.showAllStudentData();
if (result.getCount() == 0) {
//show Message
showMessage("Error", "Nothing is here");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()) {
buffer.append("Name: " + result.getString(0) + "\n");
buffer.append("Father Name: " + result.getString(1) + "\n");
buffer.append("Contact: " + result.getString(2) + "\n\n");
}
showMessage("Data", buffer.toString());
}
}
);
}
public void showMessage (String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
And this is my SQLite code
public Cursor showAllData()
{
SQLiteDatabase mydatabase = helper.getWritableDatabase();
Cursor result = mydatabase.rawQuery("select * from "+ Helper.TABLE_NAME,null);
return result;
}
layout....
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/userImage" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"></LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/studentName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/studentFName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/studentContact" />
</LinearLayout>
userActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.ks.doit.user">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#006700"
android:id="#+id/toolbar"></android.support.v7.widget.Toolbar>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/userlistView"
android:layout_below="#+id/toolbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show All Data"
android:id="#+id/btnShoww"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
You should use CursorAdapter iа you're querying data from database for example:
// columns
final String[] columns = new String[] { "stname", "stfname, "contact" };
// resource id's
final int[] to = new int[] { R.id.studentName, R.id.studentFName, R.id.studentContact };
// adapter
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.student_layout, cursor, columns, to);
// set adapter to listview
listView.setListAdapter(mAdapter);
I have fixed it! It created a list of empty strings named from[].
So, it should be like this:
String from[] = {"n", "f", "c"};

How to View data, based on date input(edittext)?

I wanted to do a view output using table layout.
My idea goes like this.
I have a main page, known as activity_main.xml
when you click on the cancel button, it will go to a summary page,
know as data.xml.
In data.xml, I have a date edittext, whereby ,when I enter a date,eg 12/2/2013,
and after I click the button search, it will show me the record of it.
However, I'm not sure how to do it.
If I didn't enter any date and click "search", it will show all the records.
Right now,I am able to show all the records, without searching the data.
Below is my code.
Can someone kindly help me out with the search by date?
I hope that I've explained myself clear enough.
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_PRICE = "fuelprice";
public static final String KEY_FUEL = "fuelpump";
public static final String KEY_COST = "tcost";
public static final String KEY_ODM = "odometer";
public static final String KEY_CON = "fcon";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "fuelLog";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
try{
db.execSQL(DATABASE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}//onCreate
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}//onUpgrade
}//DatabaseHelper
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//open
//---closes the database---
public void close()
{
DBHelper.close();
}//close
//---insert a log into the database---
public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_PRICE, fuelprice);
initialValues.put(KEY_FUEL, fuelpump);
initialValues.put(KEY_COST, tcost);
initialValues.put(KEY_ODM, odometer);
initialValues.put(KEY_CON, fcon);
return db.insert(DATABASE_TABLE, null, initialValues);
}//insertLog
// --retrieves all the data
public Cursor getAllLog()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE, KEY_PRICE, KEY_FUEL,KEY_ODM,KEY_CON}, null, null, null, null, null);
}
}
summary.java
public class summary extends Activity{
TableLayout tablelayout_Log = null;
Button searchButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
tablelayout_Log = (TableLayout) findViewById(R.id.tableLayout_Log);
tablelayout_Log.setStretchAllColumns(true);
tablelayout_Log.setShrinkAllColumns(true);
//View
searchButton = (Button) findViewById(R.id.searchBtn);
searchButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
}
});
}//oncreate
public void refreshTable()
{
tablelayout_Log.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Fuel Log");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span = 5;
rowTitle.addView(title, params);
tablelayout_Log.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try
{
dbAdaptor.open();
cursor = dbAdaptor.getAllLog();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String date = cursor.getString(1);
String price = cursor.getString(2);
String pump = cursor.getString(3);
String odometer = cursor.getString(4);
String fcon = cursor.getString(5);
TextView viewId = new TextView(getApplicationContext());
viewId.setText("" + id);
TextView viewDate = new TextView(getApplicationContext());
viewDate.setText(date);
TextView viewPrice = new TextView(getApplicationContext());
viewPrice.setText(price);
TextView viewPump = new TextView(getApplicationContext());
viewPump.setText(pump);
TextView viewOdometer = new TextView(getApplicationContext());
viewOdometer.setText(odometer);
TextView viewCon = new TextView(getApplicationContext());
viewCon.setText(fcon);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(viewId);
row.addView(viewDate);
row.addView(viewPrice);
row.addView(viewPump);
row.addView(viewOdometer);
row.addView(viewCon);
tablelayout_Log.addView(row);
}
while(cursor.moveToNext());
}
catch(Exception e){
Log.d("Fuel Log", e.getMessage());
}
finally
{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}//refreshTable
}//main
MainActivity.java
public class MainActivity extends Activity {
TableLayout tablelayout_Contacts = null;
Button insertButton = null;
EditText nameEdit = null;
EditText contactEdit = null;
Button viewButton = null;
Button deleteButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tablelayout_Contacts = (TableLayout) findViewById(R.id.tableLayout_Contacts);
tablelayout_Contacts.setStretchAllColumns(true);
tablelayout_Contacts.setShrinkAllColumns(true);
nameEdit = (EditText) findViewById(R.id.editText_Name);
contactEdit = (EditText) findViewById(R.id.editText_Number);
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
dbAdaptor.open();
String name = nameEdit.getText().toString();
String number = contactEdit.getText().toString();
dbAdaptor.insertContact(name, number);
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
finally{
if(dbAdaptor != null)
dbAdaptor.close();
}
}
});
//View records
viewButton = (Button) findViewById(R.id.button2);
viewButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
//delete records
deleteButton = (Button) findViewById(R.id.button3);
deleteButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
refreshTable();
String name = nameEdit.getText().toString();
if(!name.equals(""))
{
dbAdaptor.deleteContact(name);
}
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
}//oncreate
//refresh table
public void refreshTable()
{
tablelayout_Contacts.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Contacts");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span =3;
rowTitle.addView(title,params);
tablelayout_Contacts.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try{
dbAdaptor.open();
cursor = dbAdaptor.getAllContacts();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String name = cursor.getString(1);
String contact = cursor.getString(2);
TextView idView = new TextView(getApplicationContext());
idView.setText("" + id);
TextView nameView = new TextView(getApplicationContext());
nameView.setText(name);
TextView contactView = new TextView(getApplicationContext());
nameView.setText(contact);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(idView);
row.addView(nameView);
row.addView(contactView);
tablelayout_Contacts.addView(row);
}
while (cursor.moveToNext());
}
catch (Exception e)
{
Log.d("Contact Manager", e.getMessage());
}
finally{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/date"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpricetxtview"
android:text="#string/fuelprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpumptxtview"
android:text="#string/fuelpump"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelpump"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/totalcosttxtview"
android:text="#string/totalcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/tcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/odometertxtview"
android:text="#string/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/fcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveBTN"
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/updateBTN"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/cancelBTN"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</LinearLayout>
</LinearLayout>
data.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/datepast"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fc"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/highpricetxtview"
android:text="#string/highprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/highprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/searchBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search" />
<Button
android:id="#+id/deleteBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
<Button
android:id="#+id/backBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/tableLayout_Log"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
The error you are getting is a nullpointer that means that some object that is at line 205 in MainActivity or it is used at that line is null. Check that first and then try to run again.
The immediate problem is here:
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
Not all throwables have a message and a null can be returned. A null cannot be logged. It causes the "println needs a message" exception in the stacktrace.
So first, change that to e.g.
catch (Exception e)
{
Log.e("Fuel Log", "", e);
}
This will log the exception with error level, empty message and with full stacktrace.
Then you can see what causes that exception in the first place.
Hello date type is not supported in Sqlite Database.you have assign date as text so it will take string so you need to keep string in proper order so that it can work as date search.
You can store date in form of 2013-12-23 (20131223) then you can get your query by passing date
by the way you can try like below
public ArrayList<String> getEventsForNotification(String dateSearch)
{
ArrayList<String> arrayList=new ArrayList<String>();
String sql="SELECT "+KEY_EVENT_NAME+" FROM "+ TABLE_EVENT +" WHERE SUBSTR("+KEY_EVENT_DATE+",6) like '"+dateSearch+"'";
Cursor cursor=sqLiteDatabase.rawQuery(sql, null);
if(cursor.moveToFirst())
{
do
{
arrayList.add(cursor.getString(0));
}while(cursor.moveToNext());
cursor.close();
cursor=null;
}
return arrayList;
}
modify according to your need.

Categories