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

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.

Related

Save data on button click using Shared Preferences

I am working on an activity, my goal is that by clicking the save button it shows me the data, entered values and clicking the edit button allows me to edit the data, saved values. I have some TextView and EditText and 2 buttons.
´´´
public class MyInfo extends AppCompatActivity {
SharedPreferences sharedpreferences;
TextView name;
TextView address;
TextView firstContactName;
TextView firstContactPhoneNumber;
TextView secondContactName;
TextView secondContactPhoneNumber;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Address = "addressKey";
public static final String FirstContactName = "firstContactNameKey";
public static final String SecondContactName = "secondContactNameKey";
public static final String FirstContactPhoneNumber = "firstContactPhoneNumberKey";
public static final String SecondContactPhoneNumber = "secondContactPhoneNumber";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_info);
name = (TextView) findViewById(R.id.edit_text_my_name);
address = (TextView) findViewById(R.id.edit_text_my_address);
firstContactName = (TextView) findViewById(R.id.edit_text_first_contact_name);
firstContactPhoneNumber = (TextView) findViewById(R.id.edit_text_first_contact_phone);
secondContactName = (TextView) findViewById(R.id.edit_text_second_contact_name);
secondContactPhoneNumber = (TextView) findViewById(R.id.edit_text_second_contact_phone);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Address)) {
address.setText(sharedpreferences.getString(Address, ""));
}
if (sharedpreferences.contains(FirstContactName)) {
firstContactName.setText(sharedpreferences.getString(FirstContactName, ""));
}
if (sharedpreferences.contains(FirstContactPhoneNumber)) {
firstContactPhoneNumber.setText(sharedpreferences.getString(FirstContactPhoneNumber, ""));
}
if (sharedpreferences.contains(SecondContactName)) {
secondContactName.setText(sharedpreferences.getString(SecondContactName, ""));
}
if (sharedpreferences.contains(SecondContactPhoneNumber)) {
secondContactPhoneNumber.setText(sharedpreferences.getString(SecondContactPhoneNumber, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String a = address.getText().toString();
String fcn = firstContactName.getText().toString();
String fcpn = firstContactPhoneNumber.getText().toString();
String scn = secondContactName.getText().toString();
String scpn = secondContactPhoneNumber.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Address, a);
editor.putString(FirstContactName, fcn);
editor.putString(FirstContactPhoneNumber, fcpn);
editor.putString(SecondContactName, scn);
editor.putString(SecondContactPhoneNumber, scpn);
editor.apply();
name = (TextView) findViewById(R.id.edit_text_my_name);
address = (TextView) findViewById(R.id.edit_text_my_address);
firstContactName = (TextView) findViewById(R.id.edit_text_first_contact_name);
firstContactPhoneNumber = (TextView) findViewById(R.id.edit_text_first_contact_phone);
secondContactName = (TextView) findViewById(R.id.edit_text_second_contact_name);
secondContactPhoneNumber = (TextView) findViewById(R.id.edit_text_second_contact_phone);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Address)) {
address.setText(sharedpreferences.getString(Address, ""));
}
if (sharedpreferences.contains(FirstContactName)) {
firstContactName.setText(sharedpreferences.getString(FirstContactName, ""));
}
if (sharedpreferences.contains(FirstContactPhoneNumber)) {
firstContactPhoneNumber.setText(sharedpreferences.getString(FirstContactPhoneNumber, ""));
}
if (sharedpreferences.contains(SecondContactName)) {
secondContactName.setText(sharedpreferences.getString(SecondContactName, ""));
}
if (sharedpreferences.contains(SecondContactPhoneNumber)) {
secondContactPhoneNumber.setText(sharedpreferences.getString(SecondContactPhoneNumber, ""));
}
}
}
´´´
I have thought about it but I can't make it work, I don't know what is wrong with my java code
´´´
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:paddingLeft="#dimen/padding_left_right"
android:paddingRight="#dimen/padding_left_right"
android:paddingTop="#dimen/padding_top_bottom"
android:paddingBottom="#dimen/padding_top_bottom"
android:orientation="vertical"
tools:context=".MyInfo">
<TextView
android:id="#+id/text_view_my_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/my_name"
android:textAlignment="center"
android:layout_gravity="center_horizontal"/>
<EditText
android:id="#+id/edit_text_my_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_my_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/my_address"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_my_address"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_first_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/first_contact_name"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_first_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_first_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/first_contact_phone"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_first_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_second_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/second_contact_name"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_second_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_second_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/second_contact_phone"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_second_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<Button
android:id="#+id/edit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Clear"
android:text="#string/edit_button" />
<Button
android:id="#+id/save_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Save"
android:text="#string/save_button" />
</LinearLayout>
</LinearLayout>
´´´
first initial your widget then save values on share preference
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Address)) {
address.setText(sharedpreferences.getString(Address, ""));
}
if (sharedpreferences.contains(FirstContactName)) {
firstContactName.setText(sharedpreferences.getString(FirstContactName, ""));
}
if (sharedpreferences.contains(FirstContactPhoneNumber)) {
firstContactPhoneNumber.setText(sharedpreferences.getString(FirstContactPhoneNumber, ""));
}
if (sharedpreferences.contains(SecondContactName)) {
secondContactName.setText(sharedpreferences.getString(SecondContactName, ""));
}
if (sharedpreferences.contains(SecondContactPhoneNumber)) {
secondContactPhoneNumber.setText(sharedpreferences.getString(SecondContactPhoneNumber, ""));
}
name = (TextView) findViewById(R.id.edit_text_my_name);
address = (TextView) findViewById(R.id.edit_text_my_address);
firstContactName = (TextView) findViewById(R.id.edit_text_first_contact_name);
firstContactPhoneNumber = (TextView) findViewById(R.id.edit_text_first_contact_phone);
secondContactName = (TextView) findViewById(R.id.edit_text_second_contact_name);
secondContactPhoneNumber = (TextView) findViewById(R.id.edit_text_second_contact_phone);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
String n = name.getText().toString();
String a = address.getText().toString();
String fcn = firstContactName.getText().toString();
String fcpn = firstContactPhoneNumber.getText().toString();
String scn = secondContactName.getText().toString();
String scpn = secondContactPhoneNumber.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Address, a);
editor.putString(FirstContactName, fcn);
editor.putString(FirstContactPhoneNumber, fcpn);
editor.putString(SecondContactName, scn);
editor.putString(SecondContactPhoneNumber, scpn);
editor.apply();
All your text strings seems to be coming from 'TextView'. I can't see the 'EditText' where you would edit the values. Change the values you want to be editable to be displayed in 'EditText' instead of 'TextView'.

my ListView is not showing my image

I have to make a listview from database and i want to put a image that is clickable in my list.I use CursorAdapter for it,but my image does not show on my list.Here is my BooksCursorAdapter
public class BooksCursorAdapter extends CursorAdapter {
public BooksCursorAdapter(Context context, Cursor c) {
super(context, c, 0 );
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.books_list_item, parent, false);
}
#Override
public void bindView(View view,final Context context, Cursor cursor) {
TextView productText = view.findViewById(R.id.productText);
TextView priceText = view.findViewById(R.id.priceText);
TextView quantityText = view.findViewById(R.id.quantityText);
ImageView shopButton = view.findViewById(R.id.shop_button);
int productColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT);
int priceColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_PRICE);
final int quantityColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY);
String bookProduct = cursor.getString(productColumnIndex);
String bookPrice = cursor.getString(priceColumnIndex);
final int bookQuantity = cursor.getInt(quantityColumnIndex);
productText.setText(bookProduct);
priceText.setText(bookPrice);
quantityText.setText(Integer.toString(bookQuantity));
int idColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry._ID);
final int booksId = cursor.getInt(idColumnIndex);
shopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri currentUri = ContentUris.withAppendedId(BooksContract.BooksEntry.CONTENT_URI, booksId);
makeSale(context, bookQuantity, currentUri);
}
});
}
private void makeSale(Context context, int bookQuantity, Uri uri) {
if (bookQuantity == 0) {
Toast.makeText(context, R.string.no_books, Toast.LENGTH_SHORT).show();
} else {
int newQuantity = bookQuantity - 1;
ContentValues values = new ContentValues();
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY, newQuantity);
context.getContentResolver().update(uri, values, null, null);
}
}
}
Everything works fine and how it should be only that my image is not showing.
My book_list_item.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="333dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_margin">
<TextView
android:id="#+id/productText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#2B3D4D" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/priceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#AEB6BD"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/currencyTextList" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/quantityTextList"
android:padding="5dp"/>
<TextView
android:id="#+id/quantityText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#AEB6BD" />
</LinearLayout>
</LinearLayout>
<ImageView
android:layout_width="52dp"
android:layout_height="match_parent"
android:src="#drawable/shop_button"
android:id="#+id/shop_button"/>
</LinearLayout>
The image appears in my preview but not on my phone.I want to display an image stored on xml, that I can click on.
I did what #crammeur said, in second LinearLayout i replaced android:layout_width="333dp" with android:layout_width="0dp" and add android:layout_weight="1"

listview not getting displayed

I am trying to filter data from database and display filtered data into listview using cursor. Unfortunately, the cursor is returned from the query isn't empty but the items not getting displayed in the activity.And moreover, there's no error being displayed in the logcat.
My search_results.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search__results);
lview = (ListView) findViewById(R.id.list);
Intent intent = getIntent();
String from = intent.getStringExtra("from");
String to = intent.getStringExtra("to");
// String date = intent.getStringExtra("date");
// String clas = intent.getStringExtra("class");
myrailway = new no.nordicsemi.android.nrftoolbox.myRailwayAdapter(this);
// Cursor cursor = myrailway.getTrainDetails(from, to);
String[] FROM = null;
String[] TO = null;
String[] TRAINNAME = null;
String[] TRAINNO = null;
String[] DEPART = null;
String[] ARRIVAL = null;
Cursor cursor = myrailway.getTrainDetails(from, to);
if(cursor != null) {
Log.e("ERROR","NON EMPTY CURSOR");
int count = 0;
if (cursor.moveToFirst()) {
Log.e("ERROR","ENTERED LOOP");
do {
String stnfrom = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_STNFROM));
String stnto = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_STNTO));
String trainname = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_NAME));
String trainno = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_TRAINNUM));
String depart = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_DEPART));
String arrival = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_ARRIVAL));
FROM[count] = stnfrom; Log.e("fr",stnfrom);
TO[count] = stnto; Log.e("too",stnto);
TRAINNAME[count] = trainname; Log.e("trainanme",trainname);
TRAINNO[count] = trainno; Log.e("trainno",trainno);
DEPART[count] = depart; Log.e("depart",depart);
ARRIVAL[count] = arrival; Log.e("arrival",arrival);
count = count + 1;
cursor.close();
} while (cursor.moveToNext());
lviewAdapter = new ListViewAdapter(this, FROM, TO, DEPART, ARRIVAL, TRAINNAME, TRAINNO);
lview.setAdapter(lviewAdapter);
}
}
else
Log.e("ERROR","EMPTY CURSOR");
}
My ListViewAdapter.java:
public class ListViewAdapter extends BaseAdapter {
Activity context;
String from[];
String to[];
String depart[];
String arrival[];
String trainname[];
String trainno[];
private no.nordicsemi.android.nrftoolbox.myRailwayAdapter myrailway;
public ListViewAdapter(Activity context, String[] from, String[] to, String[] depart, String[] arrival, String[] trainname, String[] trainno) {
super();
this.context = context;
this.from = from;
this.to = to;
this.depart = depart;
this.arrival = arrival;
this.trainname = trainname;
this.trainno = trainno;
}
#Override
public int getCount() {
return depart.length;
}
#Override
public Object getItem(int i) {
return depart[i];
}
#Override
public long getItemId(int i) {
myrailway = new no.nordicsemi.android.nrftoolbox.myRailwayAdapter(this.context);
Long recc= Long.valueOf(0);
Cursor c= myrailway.getpass(trainname[i]);
if(c!=null)
{
c.moveToFirst();
recc=c.getLong(0);
}
return recc;
}
private class ViewHolder {
TextView txtfrom;
TextView txtto;
TextView txttrainno;
TextView txttrainname;
TextView txtdepart;
TextView txtarrival;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null)
{
view = inflater.inflate(R.layout.listview_items, null);
holder = new ViewHolder();
holder.txtfrom = (TextView) view.findViewById(R.id.from);
holder.txtto = (TextView) view.findViewById(R.id.to);
holder.txttrainno = (TextView) view.findViewById(R.id.trainno);
holder.txttrainname = (TextView) view.findViewById(R.id.trainname);
holder.txtdepart = (TextView) view.findViewById(R.id.depart);
holder.txtarrival = (TextView) view.findViewById(R.id.arrival);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
holder.txtfrom.setText(from[position]);
holder.txtto.setText(to[position]);
holder.txttrainno.setText(trainno[position]);
holder.txttrainname.setText(trainname[position]);
holder.txtdepart.setText(depart[position]);
holder.txtarrival.setText(arrival[position]);
return view;
}
}
My search_results.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="no.nordicsemi.android.nrftoolbox.Search_Results">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</RelativeLayout>
My listview_items.xml:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="0dip" android:layout_gravity="top"
>
<TableRow>
<TextView
android:id="#+id/from"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:textColor="#000000"
android:layout_span="1"
/>
<TextView
android:id="#+id/to"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:textColor="#000000"
android:layout_span="1"
/>
</TableRow>
<TableRow>
<TextView
android:text=""
android:id="#+id/trainno"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
<TextView
android:text=""
android:id="#+id/trainname"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
</TableRow>
<TableRow>
<TextView
android:text=""
android:id="#+id/depart"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
<TextView
android:text=""
android:id="#+id/arrival"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
</TableRow>
</TableLayout>
<Button
android:id="#+id/book"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:onClick="book"
android:text="BOOK">
</Button>
</TableRow>
</TableLayout>
Now, the cursor isn't empty but the listview is not displayed by the listview adapter.
Can someone point out the error in the code??
Please use this.
#Override
public int getCount() {
//here too;
return depart.lenght;
}
#Override
public Object getItem(int i) {
//there is error: repalce return null; with
return depart[i];
}
#Override
public long getItemId(int i) {
//change this too
return depart[i].getId();
}
I can see 2 reasons that this may happen:
You arrays are not filled with data/or filled with empty data and that the reason they are not presented. (less likely because you would receive a null pointer exception when you try to access a null location in the array)
Your row layout doesn't show data parameters. (I will be
on this reason, please show you row layout XML(listview_items.xml) so that we could check
it)
Check: Make a check and print to the log all the data from 6 the arrays for every row before you set the data in the getView method.
getCount(), getItem() and getItemId() are not set properly.
getCount() should return the number of items in the arraylist;
getItem() should return the item at the given position from the arraylist;
getItemId() should return the internal id of the item if it has one, or the position of the item in the array or an hash number of the item.

How to handle NULL results from JSON when I click on list view row?

Very little experience when it comes to Java. My app pulls data from an API to a list view just fine. Once clicked on the list view I want to display more details. My code is in different files and I can't figure out how handle null results when I set my text view text. Right now it is giving me a few errors. Thank you in advanced. I've tried debugging and my own research to no avail for over a day.
My error was: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference.
MainActivity.java:
public void showMemberDetailsScreen(int _id) {
mMembersListScreen.setVisibility(View.GONE);
mMemberDetailsScreen.setVisibility(View.VISIBLE);
if (NetworkUtils.isConnected(this)) {
GetDetailsTask task = new GetDetailsTask(this);
task.execute(_id);
} else {
Log.i(TAG, "onCreate: NOT CONNECTED");
}
}
/**
* Populate the member details screen with data.
*
* #param _name
* #param _birthday
* #param _gender
* #param _twitterId
* #param _numCommittees
* #param _numRoles
*/
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView)mMembersListScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}
OnItemClickListener mItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> _parent, View _view, int _position, long _id) {
// TODO: Show the members detail screen
Log.i(TAG, "onItemClick: RAN");
showMemberDetailsScreen(_position);
Log.i(TAG, "onItemClick: POSITION = " + _position);
}
};
GetDetailsTask.java:
private static final String NAME = "name";
private static final String BIRTHDAY = "birthday";
private static final String GENDER = "gender";
private static final String TWITTER_ID = "twitter_id";
private static final String NUM_COMMITTEES = "num_committees";
private static final String NUM_ROLES = "num_roles";
private MainActivity mActivity;
public GetDetailsTask(MainActivity _activity) {
mActivity = _activity;
}
#Override
protected HashMap<String, String> doInBackground(Integer... _params) {
// Add member ID to the end of the URL
String data = NetworkUtils.getNetworkData(API_URL + _params[0]);
HashMap<String, String> retValues = new HashMap<String, String>();
try {
JSONObject response = new JSONObject(data);
String name = response.optString("name");
retValues.put(NAME, name);
String birthday = response.optString("birthday");
retValues.put(BIRTHDAY, birthday);
String gender = response.optString("gender_label");
retValues.put(GENDER, gender);
String twitterId = response.optString("twitterid");
retValues.put(TWITTER_ID, twitterId);
if (response.has("committeeassignments")) {
JSONArray committeeArray = response.optJSONArray("committeeassignments");
int numCommittees = committeeArray.length();
retValues.put(NUM_COMMITTEES, "" + numCommittees);
Log.i(TAG, "doInBackground: NUM COMMITTESS = " + numCommittees);
} else {
retValues.put(NUM_COMMITTEES, "" + 0);
}
if (response.has("roles")){
JSONArray rolesArray = response.optJSONArray("roles");
int numRoles = rolesArray.length();
retValues.put(NUM_ROLES, "" + numRoles);
} else {
retValues.put(NUM_ROLES, "" + 0);
}
} catch(JSONException e) {
e.printStackTrace();
}
return retValues;
}
#Override
protected void onPostExecute(HashMap<String, String> _result) {
super.onPostExecute(_result);
if (_result != null) {
String name = _result.get(NAME);
String birthday = _result.get(BIRTHDAY);
String gender = _result.get(GENDER);
String twitterId = _result.get(TWITTER_ID);
String numCommittees = _result.get(NUM_COMMITTEES);
String numRoles = _result.get(NUM_ROLES);
mActivity.populateMemberDetailsScreen(name, birthday, gender, twitterId, numCommittees, numRoles);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/members_list_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<ListView
android:id="#+id/members_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/member_details_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/birthday" />
<TextView android:id="#+id/text_birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/gender" />
<TextView
android:id="#+id/text_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/twitter_id" />
<TextView android:id="#+id/text_twitter_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/num_committees" />
<TextView
android:id="#+id/text_num_committees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_num_roles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</LinearLayout>
You are trying to show your details screen but in your method you are finding view by id under your mMembersListScreen when you should use mMemberDetailsScreen. Try this:
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}

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

Categories