how to show SQLite data in simpleadapter - java

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"};

Related

Android - TextView setText updates text only sometimes

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.

where to put android.support.v4.widget.SwipeRefreshLayout and how to implement it?

just wanna ask where to put the android.support.v4.widget.SwipeRefreshLayout on my codes? I'm confused if it should be on my activity_main.xml or in my list_item.xml file..
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And This is my List_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="#+id/datetime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:layout_weight="1" />
<TextView
android:id="#+id/qname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/qagent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/qevent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/info1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/info2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
<TextView
android:id="#+id/info3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:layout_weight="1" />
</LinearLayout>
I Found some sample codes on the internet where they put it on the main xml but some samples also put it on the list xml..
This is my Main activity :
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
private static String IPaddress = "http://192.168.1.110/";
// URL to get contacts JSON
private static String url = IPaddress + "Projects/GetUsers.php";
private static final String TAG_QUEUE = "queue";
private static final String TAG_DATETIME = "datetime";
private static final String TAG_NAME = "qname";
private static final String TAG_AGENT = "qagent";
private static final String TAG_EVENT = "qevent";
private static final String TAG_INFO1 = "info1";
private static final String TAG_INFO2 = "info2";
private static final String TAG_INFO3 = "info3";
// contacts JSONArray
JSONArray queue = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>>queueList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queueList = new ArrayList<HashMap<String, String>>();
// ListView lv = getListView();
// Calling async task to get json
new GetEventCounter().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetEventCounter extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity2.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
queue = jsonObj.getJSONArray(TAG_QUEUE);
for (int i = 0; i < queue.length(); i++) {
JSONObject c = queue.getJSONObject(i);
String datetime = String.format("%s : %s", TAG_DATETIME, c.getString(TAG_DATETIME));
String qname = String.format("%s : %s", TAG_NAME, c.getString(TAG_NAME));
String qagent = String.format("%s : %s", TAG_AGENT, c.getString(TAG_AGENT));
String qevent = String.format("%s : %s", TAG_EVENT, c.getString(TAG_EVENT));
String info1 = String.format("%s : %s", TAG_INFO1, c.getString(TAG_INFO1));
String info2 = String.format("%s : %s", TAG_INFO2, c.getString(TAG_INFO2));
String info3 = String.format("%s : %s", TAG_INFO3, c.getString(TAG_INFO3));
HashMap<String, String> event = new HashMap<String, String>();
event.put(TAG_DATETIME, datetime);
event.put(TAG_NAME, qname);
event.put(TAG_AGENT, qagent);
event.put(TAG_EVENT, qevent);
event.put(TAG_INFO1, info1);
event.put(TAG_INFO2, info2);
event.put(TAG_INFO3, info3);
queueList.add(event);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity2.this, queueList,
R.layout.list_item, new String[] { TAG_DATETIME, TAG_NAME, TAG_AGENT, TAG_EVENT, TAG_INFO1, TAG_INFO2, TAG_INFO3},
new int[] { R.id.datetime, R.id.qname, R.id.qagent, R.id.qevent, R.id.info1, R.id.info2, R.id.info3 });
setListAdapter(adapter);
}
}
protected Fragment getSampleFragment() {
// TODO Auto-generated method stub
return null;
}
}
This will be the output that i want to have an SwipeRefresh effect..
Those output came from MySQL Database :
This samples caused my confusion
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swype"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
And :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swype"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/serial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="25dp"
android:layout_margin="5dp"
android:layout_alignParentLeft="true"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/title"
android:layout_toRightOf="#id/serial"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:paddingLeft="20dp"
android:textSize="18dp" />
</RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>
Thanks!
To add the swipe to refresh widget to an existing app, add SwipeRefreshLayout as the parent of a single ListView or GridView. Remember that SwipeRefreshLayout only supports a single ListView or GridView child. - Add the SwipeRefreshLayout Widget
So, your activity_main.xml should be like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout
</LinearLayout>
Implementation:
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(this);
//to change the color of the refresh indictor
swipeRefreshLayout.setColorScheme(getResources().getColor(R.color.yourcolor),
getResources().getColor(R.color.yourcolor),
getResources().getColor(R.color.yourcolor),
getResources().getColor(R.color.yourcolor));
}
#Override
public void onRefresh() {
//do something here
//setRefreshing(false) will hide the indicator
swipeRefreshLayout.setRefreshing(false);
}
}
It should wrap around the listview, something like this:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp">
<android.widget.ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.widget.ListView>
</android.support.v4.widget.SwipeRefreshLayout>
If you're using Android Studio, you can look at a Swiperefresh sample:
File\New\Import Sample\ then search for "swipe..."
In your java code, you initialize the SwipeRefresh object exactly how you would do a TextView, Button or anything else, except in your onResume(), you also want to put something like this:
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initiateRefresh();
}
});
and then inside initiateRefresh(), you do something like:
AssignData2ListView();
mSwipeRefreshLayout.setRefreshing(false);

ListView won't populate (from file)

I am trying to populate a ListView from a .txt file but somehow fail to it.
The file read and is added to the ArrayList properly. I have tried the ArrayAdapter to the ArrayList and set it as the Adapter of the ListView under OnCreate() and call notifyDataSetChanged() after the list is updated.
I'm fairly new to java, I'm more used to (and prefer) C#
Here's parts of my code:
public class MainActivity extends ActionBarActivity{
ArrayAdapter<String> arrayAdapter = null;
ArrayList<String> arrayList = null;
ListView listView = null;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
listView = (ListView) findViewById(R.id.lv_Run);
arrayList = new ArrayList<String>();
arrayList.clear();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
}
//<...>
if (file.isFile() && file.getName().endsWith(".txt")){
Button btn = new Button(ll1.getContext());
btn.setText(file.getName().replace(".txt", ""));
btn.setTag(file.getName().replace(".txt", ""));
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String btnString = v.getTag().toString();
UpdateList(btnString);
}
});
btn.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
ll1.addView(btn);
}
//<...>
public void UpdateList(String btnString){
try{
File file = new File(runs.getAbsolutePath()+ File.separator + btnString + ".txt");
arrayList = getFileContent(file.getAbsolutePath());
arrayAdapter.notifyDataSetChanged();
catch (IOException e){
e.printStackTrace();
}
}
//<...>
public static ArrayList<String> getFileContent(String fileName) throws IOException{
ArrayList<String> result = new ArrayList<>();
File aFile = new File(fileName);
BufferedReader reader;
String aLine;
if (!aFile.isFile()){
return result;
}
try{
reader = new BufferedReader(new FileReader(aFile));
}
catch (FileNotFoundException e1){
e1.printStackTrace();
return result;
}
while ((aLine = reader.readLine()) != null){
result.add(aLine + "\n");
}
reader.close();
return result;
}
//<...>
<LinearLayout 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"
tools:context=".MainActivity"
android:background="#ff000000"
android:baselineAligned="false"
android:id="#+id/pan_MasterPan">
<LinearLayout android:orientation="vertical"
android:layout_weight="2.5"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/pan_Left">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_weight="8"
android:id="#+id/pan_SelRun">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/select_run"
android:id="#+id/btn_LoadRun"
android:clickable="true"
android:onClick="runSelectClick"/>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_weight="1"
android:focusableInTouchMode="false"
android:id="#+id/pan_RunPOI">
<ListView
android:id="#+id/lv_Run"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="visible"
android:layout_weight="1"
android:dividerHeight="1dp"
android:drawSelectorOnTop="true"
android:clickable="true"
android:choiceMode="singleChoice"
android:divider="#android:color/black"/>
</LinearLayout>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_weight="1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#ff1A1A1A"
android:id="#+id/pan_Right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ForDebug"
android:text="#string/debugbtnstrg"
android:clickable="true"
android:onClick="ForDebug_OnClick"
android:longClickable="false"
android:textStyle="italic"/>
</LinearLayout>
</LinearLayout>
Two days I try this and that without any difference between every try...
Thanks a lot for you time, it's really appreciated.
---- Edit ----
Updated Code: (sorry to show only parts, this is part of a massive and messy code...)
public void UpdateList(String btnString){
try{
File file = new File(runs.getAbsolutePath()+ File.separator + btnString + ".txt");
arrayList = getFileContent(file.getAbsolutePath());
Toast.makeText(getApplicationContext(), "aL_Size: " + arrayList.size(), Toast.LENGTH_LONG).show();
//return 5
arrayAdapter.addAll(arrayList);
Toast.makeText(getApplicationContext(), "aA_Count: " + arrayAdapter.getCount(), Toast.LENGTH_LONG).show();
//return 5
arrayAdapter.notifyDataSetChanged();
catch (IOException e){
e.printStackTrace();
}
}
---- Edit 2 ----
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
listView = (ListView) findViewById(R.id.lv_Run);
arrayList = new ArrayList<String>();
arrayList.clear();
arrayList.add("TEST1");
arrayList.add("TEST2");
arrayList.add("TEST3");
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
}
Call ArrayAdapter.addAll method for adding new items in current adapter of ListView before calling notifyDataSetChanged :
arrayList = getFileContent(file.getAbsolutePath());
arrayAdapter.addAll(arrayList);
arrayAdapter.notifyDataSetChanged();

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.

Listview will not populate

Alright I'm stuck on populating a ListView in Android. This must be a tiring question for you guys but I can't find the problem. Basically it will produce placements in the ListView to hold texts, but it wont produce text. I checked my database class and it seems to be storing the data correctly, and I checked the syntax, but I cant find the problem.
Main activity that holds the list view
public class MainScreen extends ListActivity {
private TextView roommateId;
dbHelper db = new dbHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
Log.i("Created", "main created");
ArrayList<HashMap<String, String>> roommates = db.getAllRoommates();
if(roommates.size()!=0){
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
roommateId = (TextView) view.findViewById(R.id.roommateId);
String roommateIdValue = roommateId.getText().toString();
Intent intent = new Intent(getApplication(), RoommateView.class);
intent.putExtra("roommateId", roommateIdValue);
startActivity(intent);
}
});
ListAdapter adapter = new SimpleAdapter(MainScreen.this, roommates, R.layout.contact_entry,
new String[] {"roommateId", "firstName", "lastName"},
new int[]{R.id.roommateId, R.id.lastName, R.id.firstName});
setListAdapter(adapter);
}
}
Database code that returns the array list
public ArrayList<HashMap<String,String>> getAllRoommates(){
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
String query = "SELECT * FROM " + DB_TABLE;
SQLiteDatabase data = this.getWritableDatabase();
Cursor cursor = data.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
HashMap<String,String> roommateMap = new HashMap<String, String>();
roommateMap.put(ID, cursor.getString(0));
Log.d("Roommate ID", cursor.getString(0));
roommateMap.put(FIRST_NAME, cursor.getString(1));
Log.d("First Name", cursor.getString(1));
roommateMap.put(LAST_NAME, cursor.getString(2));
list.add(roommateMap);
}while(cursor.moveToNext());
}
return list;
}
contact entry xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/last_name"
android:id="#+id/lastName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/first_name"
android:id="#+id/firstName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/id"
android:id="#+id/roommateId"/>
</TableRow>
Main screen xml
<TableLayout 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"
tools:context=".MainActivity" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000" >
<TextView
android:id="#+id/contactsTitleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/button1"
android:background="#444444"
android:onClick="showAddRoommate"
android:text="#string/add_roommate"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
</TableRow>
</TableLayout>
Alright, I think I found the problem, it was that the String array in the simple adapter wasn't corresponding to the hash map key values, so when it was looking for key values that were not in the Hash Map. Change that and it populated. Putting the answer down incase anyone in the future sees this post.

Categories