Why is my "Notes" tab crashing? - java

I've tried searching for an answer but I'm relatively new to this area of programming and using Android Studio. Firstly, this is the error that I'm receiving when the emulator crashes. Bear with me as theres a lot of code and this is my first time posting.
--------- beginning of crash
08-16 16:59:46.930 1861-1861/com.example.richard.stopandsearch E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.richard.stopandsearch, PID: 1861
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.richard.stopandsearch.MainActivity$NotesListAdapter.getView(MainActivity.java:157)
at android.widget.AbsListView.obtainView(AbsListView.java:2347)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
at android.widget.ListView.onMeasure(ListView.java:1182)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:444)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17547)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
at android.view.View.measure(View.java:17547)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.Activ
MainActivity.Java
package com.example.richard.stopandsearch;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText LocationTxt, TimeTxt, DateTxt, OfficerTxt, DetailsTxt;
List<Notes> Notes = new ArrayList<Notes>();
ListView notesListView;
databaseHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationTxt = (EditText) findViewById(R.id.txtLocation);
TimeTxt = (EditText) findViewById(R.id.txtTime);
DateTxt = (EditText) findViewById(R.id.txtDate);
OfficerTxt = (EditText) findViewById(R.id.txtOfficer);
DetailsTxt = (EditText) findViewById(R.id.txtDetails);
notesListView = (ListView) findViewById(R.id.listView);
dbHandler = new databaseHandler(getApplicationContext());
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("addNote");
tabSpec.setContent(R.id.tabAddNote);
tabSpec.setIndicator("AddNote");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("notes");
tabSpec.setContent(R.id.tabNotes);
tabSpec.setIndicator("Notes");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("info");
tabSpec.setContent(R.id.tabInfo);
tabSpec.setIndicator("Info");
tabHost.addTab(tabSpec);
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Notes notes = new Notes(dbHandler.getNotesCount(), String.valueOf(LocationTxt.getText()), String.valueOf(TimeTxt.getText()), String.valueOf(DateTxt.getText()), String.valueOf(OfficerTxt.getText()), String.valueOf(DetailsTxt.getText()));
if (!noteExists(notes)) {
// Notes.add (new Notes(0, LocationTxt.getText().toString(), TimeTxt.getText().toString(), DateTxt.getText().toString(), OfficerTxt.getText().toString(), DetailsTxt.getText().toString()));
dbHandler.createNote(notes);
Notes.add(notes);
// populateList();
Toast.makeText(getApplicationContext(), "Your note has been added.", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(), String.valueOf(LocationTxt.getText()) + " already exists. Please enter a different location.", Toast.LENGTH_SHORT).show();
}
});
DetailsTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addBtn.setEnabled(String.valueOf(DetailsTxt.getText()).trim().length() >0);
// #Override
// public void afterTextChanged(Editable s) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
// List<Notes> addableNotes = dbHandler.getAllNotes();
// int noteCount = dbHandler.getNotesCount();
// for (int i=0; i < noteCount; i++) {
// Notes.add(addableNotes.get(i));
// }
if (dbHandler.getNotesCount()!=0)
Notes.addAll(dbHandler.getAllNotes());
// if (!addableNotes.isEmpty())
populateList();
}
private boolean noteExists(Notes notes) {
String location = notes.getLocation();
int notesCount = Notes.size();
for (int i=0; i < notesCount; i++) {
if(location.compareToIgnoreCase(Notes.get(i).getLocation()) ==0)
return true;
}
return false;
}
private void populateList() {
ArrayAdapter<Notes> adapter = new NotesListAdapter();
notesListView.setAdapter(adapter);
}
// private void addNotes(String location, String time, String date, String officer, String details) {
//Notes.add(new Notes(location, time, date, officer, details));
// }
public class NotesListAdapter extends ArrayAdapter<Notes> {
public NotesListAdapter() {
super(MainActivity.this, R.layout.listviewitem, Notes);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listviewitem, parent, false);
Notes currentNote = Notes.get(position);
TextView location = (TextView) view.findViewById(R.id.txtLocationView);
location.setText(currentNote.getLocation());
TextView time = (TextView) view.findViewById(R.id.txtTimeView);
time.setText (currentNote.getLocation());
TextView date = (TextView) view.findViewById(R.id.txtDateView);
date.setText (currentNote.getLocation());
TextView officer = (TextView) view.findViewById(R.id.txtOfficer);
officer.setText(currentNote.getLocation());
TextView details = (TextView) view.findViewById(R.id.txtDetailsView);
details.setText(currentNote.getLocation());
return view;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
databaseHandler.java
package com.example.richard.stopandsearch;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class databaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notes",
TABLE_NOTES = "notes",
KEY_ID = "id",
KEY_LOCATION = "location",
KEY_TIME = "time",
KEY_DATE = "date",
KEY_OFFICER = "officer",
KEY_DETAILS = "details";
public databaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NOTES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCATION + " TEXT, " + KEY_TIME + " TEXT, " + KEY_DATE + " TEXT, " + KEY_OFFICER + " TEXT, " + KEY_DETAILS + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
onCreate(db);
}
public void createNote(Notes notes) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LOCATION, notes.getLocation());
values.put(KEY_TIME, notes.getTime());
values.put(KEY_DATE, notes.getDate());
values.put(KEY_OFFICER, notes.getOfficer());
values.put(KEY_DETAILS, notes.getDetails());
db.insert(TABLE_NOTES, null, values);
db.close();
}
public Notes getNotes(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID, KEY_LOCATION, KEY_TIME, KEY_DATE, KEY_OFFICER, KEY_DETAILS }, KEY_ID + "=?", new String [] {String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
assert cursor != null;
Notes notes = new Notes(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3), cursor.getString(4), cursor.getString(5));
db.close();
cursor.close();
return notes;
}
public void deleteNote(Notes notes) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + "=?", new String[] {String.valueOf(notes.getId())});
db.close();
}
public int getNotesCount () {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NOTES, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public int updateNotes(Notes notes) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LOCATION, notes.getLocation());
values.put(KEY_TIME, notes.getTime());
values.put(KEY_DATE, notes.getDate());
values.put(KEY_OFFICER, notes.getOfficer());
values.put(KEY_DETAILS, notes.getDetails());
int rowsAffected = db.update(TABLE_NOTES, values, KEY_ID + "=?", new String[]{String.valueOf(notes.getId())});
db.close();
return rowsAffected;
}
public List<Notes> getAllNotes() {
List<Notes> notes = new ArrayList<Notes>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NOTES, null);
if (cursor.moveToFirst()) {
do {
notes.add(new Notes(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3), cursor.getString(4), cursor.getString(5)));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return notes;
}
}
Notes.Java
package com.example.richard.stopandsearch;
public class Notes {
private String _location, _time, _date, _officer, _details;
private int _id;
public Notes (int id, String location, String time, String date, String officer, String details) {
_id = id;
_location = location;
_time = time;
_date = date;
_officer = officer;
_details = details;
}
public int getId() {return _id; }
public String getLocation() {
return _location;
}
public String getTime() {
return _time;
}
public String getDate() {
return _date;
}
public String getOfficer() {
return _officer;
}
public String getDetails() {
return _details;
}
}
Activity_Main.xml
<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:orientation="vertical"
android:background="#f9f9f9">
<TabHost
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tabHost">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/tabInfo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/imgLogo3"
android:layout_gravity="center_horizontal"
android:src="#drawable/policelogo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Information"
android:id="#+id/txtInfo"
android:textColor="#1b0f3e"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabNotes"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgLogo"
android:layout_gravity="center_horizontal"
android:src="#drawable/policelogo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Notes"
android:id="#+id/txtNotes"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"
android:singleLine="false"
android:textColor="#1b0f3e" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabAddNote"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/imgLogo2"
android:layout_gravity="center_horizontal"
android:src="#drawable/policelogo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Add Note"
android:id="#+id/lblNotesTitle"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:textColor="#1b0f3e" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/txtLocation"
android:layout_marginTop="16dp"
android:hint="Location"
android:textColor="#1b0f3e" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="time"
android:ems="10"
android:id="#+id/txtTime"
android:hint="Time"
android:layout_marginTop="16dp"
android:textColor="#1b0f3e" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:id="#+id/txtDate"
android:hint="Date"
android:layout_marginTop="16dp"
android:textColor="#1b0f3e" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/txtOfficer"
android:hint="Officer name/number"
android:layout_marginTop="16dp"
android:textColor="#1b0f3e" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/txtDetails"
android:hint="Event details"
android:layout_marginTop="16dp"
android:lines="4"
android:textColor="#1b0f3e" />
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Add Note"
android:id="#+id/btnAdd"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:enabled="false"
android:textColor="#1b0f3e" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
Again I apologise for the huge chunks of code, but I'm hoping there's something that may be obvious for somebody experienced that is eluding me. Thanks in advance.

Going off of your error log, it looks as if you are inflating listviewitem.xml in your getView() method, but the widgets (TextViews) you are referencing are in activity_main.xml.
Edit: Well, at least one is, with the id txtOfficer
In terms of a resolution, ensure all of the id attributes you assign in your xml layouts are unique, and ensure that you only use findViewById() to locate a widget that is contained inside the calling View:
view = getLayoutInflater().inflate(R.layout.listviewitem, parent, false);
view.findViewById(*id of a widget inside listviewitem.xml*)

The problem what #PPartisan pointed out is real, but also note that in your activity_main.xml you are referencing EditText elements as TextView elements in your java code.

Related

How to show properly my data in RecyclerView?

This is the updated code for my RececlerView to show data in my SQLite Database but still I cant make the data to show in my recycler view but there is no errors in my app.
The applications only show "No API Data" which is from this part of my code.
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
I will show you the codes.
This is a part of my DatabaseHelper the method on Listing the data in myDatabase for RecyclerView.
public boolean checkUser(String email) {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry._ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = Timerecordshelper.BeneficiaryEntry.COL_1 + " = ?";
// selection argument
String[] selectionArgs = {email};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'test#gmail.com';
*/
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public List<TimeinData> getAllTimeinData() {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry.COL_1,
Timerecordshelper.BeneficiaryEntry.COL_2,
Timerecordshelper.BeneficiaryEntry.COL_3,
Timerecordshelper.BeneficiaryEntry.COL_4,
Timerecordshelper.BeneficiaryEntry.COL_5,
};
// sorting orders
String sortOrder =
Timerecordshelper.BeneficiaryEntry.COL_1 + " ASC";
List<TimeinData> TimeList = new ArrayList<TimeinData>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
TimeinData Timerecords = new TimeinData();
Timerecords.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_1))));
Timerecords.setIn(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_2)));
Timerecords.setCustomer(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_3)));
Timerecords.setBranch(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_4)));
Timerecords.setMachine(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_5)));
// Adding user record to list
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return TimeList;
}
TimeinRecyclerAdapter.java
package com.example.serviceapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimeinRecyclerAdapter extends
RecyclerView.Adapter<TimeinRecyclerAdapter.BeneficiaryViewHolder> {
private ArrayList<TimeinData> listBeneficiary;
public ImageView overflow;
private Context mContext;
private ArrayList<TimeinData> mFilteredList;
public TimeinRecyclerAdapter(ArrayList<TimeinData> listBeneficiary, Context
mContext) {
this.listBeneficiary = listBeneficiary;
this.mContext = mContext;
this.mFilteredList = listBeneficiary;
}
public class BeneficiaryViewHolder extends RecyclerView.ViewHolder {
public AppCompatTextView textViewName;
public AppCompatTextView textViewEmail;
public AppCompatTextView textViewAddress;
public AppCompatTextView textViewCountry;
public BeneficiaryViewHolder(View view) {
super(view);
textViewName = view.findViewById(R.id.textViewName);
textViewEmail = view.findViewById(R.id.textViewEmail);
textViewAddress = view.findViewById(R.id.textViewAddress);
textViewCountry = view.findViewById(R.id.textViewCountry);
}
}
#Override
public BeneficiaryViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// inflating recycler item view
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_timeinrecycler, parent, false);
return new BeneficiaryViewHolder(itemView);
}
#Override
public void onBindViewHolder(final BeneficiaryViewHolder holder, int
position) {
holder.textViewName.setText(listBeneficiary.get(position).getId());
holder.textViewName.setText(listBeneficiary.get(position).getIn());
holder.textViewEmail.setText(listBeneficiary.get(position).getCustomer());
holder.textViewAddress.setText(listBeneficiary.get(position).getBranch());
holder.textViewCountry.setText(listBeneficiary.get(position).getMachine());
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
}
Timerecordshelper.java
package com.example.serviceapplication;
import android.provider.BaseColumns;
public class Timerecordshelper {
public static final class BeneficiaryEntry implements BaseColumns {
public static final String TABLE_NAME_IN = "TABLE_NAME_IN";
public static final String COL_1 = "Job ID";
public static final String COL_2 = "Time In";
public static final String COL_3 = "Customer:";
public static final String COL_4 = "Branch";
public static final String COL_5 = "Machine";
}
}
This codes acts as the gettersetter for my Recycleview to get data in SQLite.
TimeinData.java
package com.example.serviceapplication;
public class TimeinData {
private int id;
private String In;
private String Customer;
private String Branch;
private String Machine;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIn() {
return In;
}
public void setIn(String In) {
this.In = In;
}
public String getCustomer() {
return Customer;
}
public void setCustomer(String Customer) {
this.Customer = Customer;
}
public String getBranch() {
return Branch;
}
public void setBranch(String Branch) {
this.Branch = Branch;
}
public String getMachine() {
return Machine;
}
public void setMachine(String Machine) {
this.Machine = Machine;
}
}
TimerecordsListActivity.java
package com.example.serviceapplication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimerecordsListActivty extends AppCompatActivity {
private AppCompatActivity activity = TimerecordsListActivty.this;
Context context = TimerecordsListActivty.this;
private RecyclerView recyclerViewBeneficiary;
private ArrayList<TimeinData> listBeneficiary;
private TimeinRecyclerAdapter beneficiaryRecyclerAdapter;
private DatabaseHelper databaseHelper;
SearchView searchBox;
private ArrayList<TimeinData> filteredList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeinrec);
initViews();
initObjects();
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("Job ID")) {
//get all needed extras intent
int id = getIntent().getExtras().getInt("ID");
String in = getIntent().getExtras().getString("Time In");
String customer = getIntent().getExtras().getString("Customer");
String branch = getIntent().getExtras().getString("Branch");
String machine = getIntent().getExtras().getString("Machine");
}else{
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is to initialize views
*/
private void initViews() {
recyclerViewBeneficiary = (RecyclerView)
findViewById(R.id.recyclerViewBeneficiary);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listBeneficiary = new ArrayList<>();
beneficiaryRecyclerAdapter = new TimeinRecyclerAdapter(listBeneficiary,
this);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerViewBeneficiary.setLayoutManager(mLayoutManager);
recyclerViewBeneficiary.setItemAnimator(new DefaultItemAnimator());
recyclerViewBeneficiary.setHasFixedSize(true);
recyclerViewBeneficiary.setAdapter(beneficiaryRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listBeneficiary.clear();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
And this is the XML Layouts of my following codes just showing you to understand more about ID i assigned.
Activity_timeinrec.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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:fitsSystemWindows="true"
tools:context="com.example.serviceapplication.TimerecordsListActivty">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewBeneficiary"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginTop="?actionBarSize"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_timeinrecycler.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewCountry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
I expect that the apps shows all the data in TABLE_NAME_IN, but on the otherhand as I said it only shows the No "API Data".

java programming language and android development

good evening dear friends, I'm working with SQLite db and android android applications I have a problem with my button when I click on login activity the message "could not execute for android onClick" my code are:
for LoginDatabaseAdapter.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by mugenzi israel on 9/19/2017.
*/
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
static final String TABLE_NAME ="LOGIN";
public static final int NAME_COLUMN = 1;
static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + " ID " + " INTEGER PRIMARY KEY AUTOINCREMENT," + " USERNAME text, PASSWORD text );";
public SQLiteDatabase db;
private Context context ;
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context){
Context context;
context = _context;
dbHelper = new DataBaseHelper(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException{
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
db.close();
}
public SQLiteDatabase getDatabaseInstance(){
return db;
}
public void insertEntry(String userName,String password){
ContentValues newValues = new ContentValues();
newValues.put("USERNAME",userName);
newValues.put("PASSWORD",password);
db.insert("LOGIN",null,newValues);
}
public int deleteEntry(String UserName){
String where = "USERNAME=?";
int numberOFEntriesDeleted;
numberOFEntriesDeleted = db.delete(
"LOGIN",where, new String[]{
UserName}
);
return numberOFEntriesDeleted;
}
public String getSingleEntry(String userName){
Cursor cursor = db.query("LOGIN",null,"USERNAME=?",new String[]{userName},null,null,null);
if(cursor.getCount()<1){
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password){
ContentValues updatedValues = new ContentValues();
updatedValues.put("USERNAME",userName);
updatedValues.put("PASSWORD",password);
String where = "USERNAME = ?";
db.update("LOGIN",updatedValues,where,new String[]{userName});
}
}
code for DatabaseHelper.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by mugenzi israel on 9/19/2017.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context,name,factory,version);
}
private static final String TABLE_NAME = "LOGIN";
static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + " ID " + " INTEGER PRIMARY KEY AUTOINCREMENT," + " USERNAME text, PASSWORD text );";
#Override
public void onCreate(SQLiteDatabase _db){
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase _db,int _oldVersion,int _newVersion){
Log.w("TaskDBAdapter","Upgrading from version"+_oldVersion+"to"+_newVersion+
",which will destroy all old data") ;
_db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(_db);
}
}
code for Main_activity_login.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Main_activity_login extends AppCompatActivity {
Button login;
Button sign;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
/* final Button login;
final Button sign;
LoginDataBaseAdapter loginDataBaseAdapter;*/
login = (Button)findViewById(R.id.log);
final Spinner spinner = (Spinner)findViewById(R.id.spinner1);
sign = (Button)findViewById(R.id.sgn);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.roles_selection,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+ "Selected",Toast.LENGTH_LONG).show();
((TextView) parent.getChildAt(0)).setTextColor(Color.RED);//TO change the color of spinner items
final Intent intent;
switch (position)
{
case 1:
intent = new Intent(Main_activity_login.this,Bus_info_admin.class);
startActivity(intent);
break;
case 2:
intent = new Intent(Main_activity_login.this,pick_ticket.class);
startActivity(intent);
break;
case 3:
intent = new Intent(Main_activity_login.this,SignIn.class);
startActivity(intent);
break;
case 4:
intent = new Intent(Main_activity_login.this,View_Booking.class);
startActivity(intent);
default:
System.out.println("wrong");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent){
}
});
/* login.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
// code for button one click
Intent intent = new Intent(Main_activity_login.this,DetailsLogin.class); startActivity(intent);
}
}
);*/
sign.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(Main_activity_login.this,SignIn.class);
startActivity(intent);
}
}
);
}
public void logIn(View v){
final Dialog dialog = new Dialog(Main_activity_login.this);
dialog.setContentView(R.layout.activity_main_login);//
dialog.setTitle("Login");
final EditText editUserName = (EditText)findViewById(R.id.EditLog);
final EditText editPassword = (EditText)findViewById(R.id.Edit_menu2);
Button btnLogin = (Button)findViewById(R.id.log);
final String userName,password,storedPassword;
userName = editUserName.getText().toString();
password = editPassword.getText().toString();
storedPassword = loginDataBaseAdapter.getSingleEntry(userName);
btnLogin.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
if (password.equals(storedPassword)){
Toast.makeText(Main_activity_login.this,"You made it!,Login successful",Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent intent = new Intent(Main_activity_login.this,DetailsLogin.class);
startActivity(intent);
}
else {
Toast.makeText(Main_activity_login.this,"User name or password does not match",Toast.LENGTH_LONG).show();
}
}
}
);
}
#Override
protected void onDestroy(){
super.onDestroy();
loginDataBaseAdapter.close();
}
/*public void startActivity() {
Intent intent = new Intent(Main_activity_login.this,Bus_info_admin.class);
startActivity(intent);
}*/
/*public void buttonLoginClick(View v){
Intent intent = new Intent(v.getContext(),DetailsLogin.class);
v.getContext().startActivity(intent);
}
*/
}
code for SignIn.java:
package com.delaroystudios.bus_seat_booking_system;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignIn extends AppCompatActivity { //AppCompatActivity
EditText editUserName,editPassword,editConfirmPassword;
Button btnCreateAccount,btn;
Context context = this;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
editUserName =(EditText)findViewById(R.id.id_name);
editPassword = (EditText)findViewById(R.id.email);
editConfirmPassword = (EditText)findViewById(R.id.password);
btnCreateAccount = (Button)findViewById(R.id.register) ;
btnCreateAccount.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
String userName = editUserName.getText().toString();
String password = editPassword.getText().toString();
String confirmPassword = editConfirmPassword.getText().toString();
if (userName.equals("")||password.equals("")||confirmPassword.equals("")){
Toast.makeText(getApplicationContext(),"Field Vacant",Toast.LENGTH_LONG).show();
return;
}
if (!password.equals(confirmPassword)){
Toast.makeText(getApplicationContext(),"Password does not match",Toast.LENGTH_LONG).show();
return;
}
else {
loginDataBaseAdapter.insertEntry(userName,password);
Toast.makeText(getApplicationContext(),"Account Successfully created",Toast.LENGTH_LONG).show();
Intent i = new Intent(SignIn.this,Main_activity_login.class);
startActivity(i);
finish();
}
}
}
);
/*btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(SignIn.this,Main_activity_login.class);
startActivity(intent);
}
);*/
}
#Override
protected void onDestroy(){
super.onDestroy();
loginDataBaseAdapter.close();
}
}
code for sign_in.xml:
<?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:orientation="vertical"
tools:context="com.delaroystudios.bus_seat_booking_system.SignIn">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="#string/register_here"
android:textSize="32sp"
android:gravity="center"
android:layout_marginTop="30dp"
/>
<EditText
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/user_id"
android:id="#+id/id_user"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/full_name"
android:id="#+id/id_name"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/phone_no"
android:id="#+id/phone"
/>
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:hint="#string/email_id"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/password"
android:id="#+id/password"
android:layout_marginBottom="20dp"
/>
<Button
android:id="#+id/register"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="#string/register"
android:onClick="onClick"
/>
</LinearLayout>
code for activity_main_login.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.delaroystudios.bus_seat_booking_system.Main_activity_login"
android:background="#drawable/bus1"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/menu1"
android:layout_marginBottom="100dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_marginStart="30dp"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/home"
android:textSize="20sp"
android:textColor="#9b59b6"
/>
<Button
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about"
android:textColor="#9b59b6"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/contact"
android:textSize="20sp"
android:textColor="#9b59b6"
/>
<!--a verifier -->
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu1"
android:id="#+id/menu2"
android:layout_marginBottom="30dp"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/Login2"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<EditText
android:id="#+id/EditLog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/login"
android:textColorHint="#9b59b6"
android:textColor="#ffffff"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu2"
android:id="#+id/menu3"
android:layout_marginBottom="30dp"
>
<TextView
android:id="#+id/textView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/Pass"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/your_password"
android:id="#+id/Edit_menu2"
android:textColorHint="#9b59b6"
android:textColor="#ffffff"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu3"
android:layout_marginBottom="10dp"
android:id="#+id/role"
>
<TextView
android:id="#+id/T_role"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/role"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner1"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/men1"
android:layout_marginTop="70dp"
android:layout_below="#+id/role"
android:gravity="center"
android:layout_marginStart="30dp"
>
<Button
android:id="#+id/log"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:onClick="logIn"
android:text="#string/login"
android:textColor="#9b59b6"
android:textColorHint="#9b59b6"
android:textSize="20sp"
/>
<Button
android:id="#+id/sgn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:onClick="onClick"
android:text="#string/sign_in"
android:textColor="#9b59b6"
android:textColorHint="#9b59b6"
android:textSize="20sp"
/>
In sign_in.xml,
<Button
android:id="#+id/register"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="#string/register"
android:onClick="onClick"
/>
remove android:onClick="onClick" line. That should be work.

Null pointer exception whilst adding to the DB

I'm developing a simple bird-watching log app for one of my classes at college and I seem to not be able to spot what the heck is going wrong, so after spending a few days banging my head against the wall, I suppose it'd make more sense to just ask for someone with a fresh pair of eyes to have a look.
The app is really simple - I have two activities, one with a ListView, that gets populated by the DB (MainActivity) and another, that takes the arguments to create a new entry (AddActivity). Besides these I have a DBHelper (MySQLiteHelper) to handle my DB calls, a simple class to describe how my object should look like (Sighting), a DataSource class (SightingDataSource) to handle facilitate the calls to the helper and a bunch of non-relevant resources (layouts, etc.) The AddActivity blows up with null pointer exceptions whilst calling the addSighting method. It also for whatever reason doesn't like the int typecast of the bCount field, so for testing purposes I've set a static int, just whilst I figure out the exception portion of my problem.
Here's my source:
AddActivity:
package com.vladislavtachev.cscb763;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddActivity extends ListActivity {
public SightingsDataSource datasource;
private EditText locFld = null;
private EditText bNameFld = null;
private EditText bCountFld = null;
private Button addSightBtn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
locFld = (EditText) findViewById(R.id.locFld);
bNameFld = (EditText) findViewById(R.id.bNameFld);
bCountFld = (EditText) findViewById(R.id.bCountFld);
setContentView(R.layout.activity_add);
addSightBtn = (Button) findViewById(R.id.addSightBtn);
addSightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSight(v);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) { return true; }
return super.onOptionsItemSelected(item);
}
public void addSight(View view){
long time = System.currentTimeMillis()/1000L;
datasource.addSighting(locFld.getText().toString(),
time,
bNameFld.getText().toString(),3
// Integer.parseInt(bCountFld.getText().toString())
);
// datasource.addSighting(sighting);
setContentView(R.layout.activity_main);
}
}
SightingDataSource
package com.vladislavtachev.cscb763;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SightingsDataSource {
//DB info
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COL_ID, MySQLiteHelper.COL_LOCATION,
MySQLiteHelper.COL_TIME, MySQLiteHelper.COL_BNAME, MySQLiteHelper.COL_BCOUNT };
public SightingsDataSource(Context context){
dbHelper = new MySQLiteHelper(context);
}
public void open(){
database = dbHelper.getWritableDatabase();
}
public void close(){ dbHelper.close(); }
public void addSighting(String l, long time, String bName, int bCount){
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COL_LOCATION, l);
values.put(MySQLiteHelper.COL_TIME, time);
values.put(MySQLiteHelper.COL_BNAME, bName);
values.put(MySQLiteHelper.COL_BCOUNT, bCount);
long insertId = database.insert(MySQLiteHelper.TABLE_SIGHTINGS, null, values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SIGHTINGS, allColumns, MySQLiteHelper.COL_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Sighting newSighting = cursorToSighting(cursor);
cursor.close();
}
private Sighting cursorToSighting(Cursor cursor){
Sighting sighting = new Sighting();
sighting.setId(cursor.getLong(0));
sighting.setLocation(cursor.getString(1));
sighting.setTime(cursor.getLong(2));
sighting.setbName(cursor.getString(3));
sighting.setbCount(cursor.getInt(4));
return sighting;
}
public List<Sighting> getAllSightings(){
List<Sighting> sightings = new ArrayList<Sighting>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SIGHTINGS, allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Sighting sighting = cursorToSighting(cursor);
sightings.add(sighting);
cursor.moveToNext();
}
cursor.close();
return sightings;
}
}
MySQLiteHelper
package com.vladislavtachev.cscb763;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper{
public final static String DB_NAME = "sightings.db";
public final static int DB_VER = 1;
public final static String TABLE_SIGHTINGS = "sightings";
public final static String COL_ID = "_id";
public final static String COL_LOCATION = "_loc";
public final static String COL_TIME = "_time";
public final static String COL_BNAME = "_bname";
public final static String COL_BCOUNT = "_bcount";
private final static String DB_CREATE = "create table if not exists"
+ TABLE_SIGHTINGS + "("
+ COL_ID + " integer primary key autoincrement, "
+ COL_LOCATION + " text not null, "
+ COL_TIME + " integer not null, "
+ COL_BNAME + " text not null, "
+ COL_BCOUNT + " integer not null);";
public MySQLiteHelper(Context context){
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onCreate(SQLiteDatabase database){
database.execSQL(DB_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVer, int newVer){
database.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGHTINGS);
onCreate(database);
}
}
activity_add.xml layout
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.vladislavtachev.cscb763.AddActivity"
style="#android:style/Theme.Material">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lblBName"
android:id="#+id/lblBName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bNameFld"
android:layout_below="#+id/lblBName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lblBCount"
android:id="#+id/lblBCount"
android:layout_alignBottom="#+id/bCountFld"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/bCountFld"
android:layout_below="#+id/bNameFld"
android:layout_alignRight="#+id/bNameFld"
android:layout_alignEnd="#+id/bNameFld"
android:layout_toEndOf="#+id/lblBCount"
android:layout_toRightOf="#+id/lblBCount" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/lblLocation"
android:id="#+id/lblLocation"
android:layout_alignBottom="#+id/locFld"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/locFld"
android:layout_below="#+id/bCountFld"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/lblLocation"
android:layout_toRightOf="#+id/lblLocation" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/addSightBtn"
android:id="#+id/addSightBtn"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<ListView
android:layout_width="10px"
android:layout_height="10px"
android:id="#android:id/list"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/locFld"
android:layout_alignEnd="#+id/locFld" />
</RelativeLayout>
Error stack
07-01 18:08:49.131 2384-2384/com.vladislavtachev.cscb763 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.vladislavtachev.cscb763, PID: 2384
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.vladislavtachev.cscb763.SightingsDataSource.addSighting(java.lang.String, long, java.lang.String, int)' on a null object reference
at com.vladislavtachev.cscb763.AddActivity.addSight(AddActivity.java:75)
at com.vladislavtachev.cscb763.AddActivity$1.onClick(AddActivity.java:38)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
All help is appreciated!
Cheers,
V./
datasource is never initialized in AddActivity. You also call setContentView twice. Delete the second one.
you should Always Check to see if the cursor is null.
if(cursor!=null curosr.moeToNext()){}..
and to close it
if (cursor!=null && !cursor.isClosed){cursor.close();}

Please anyone help me connection with main activity and Adapterclass.

Please anyone tell me how to connect MainActivity class with adapterClass, I am not able to connect to my sqllite database. Any help would be greatly appreciated.
Below is my main activity class
public class LoginActivity extends Activity {
EditText nameText,phoneText;
Button registeredButton,newUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
newUser =(Button)findViewById(R.id.new_user);
newUser.setOnClickListener(new View.OnClickListener()
#Override
public void onClick(View v) {
nameText=(EditText)findViewById(R.id.user_text);
phoneText=(EditText)findViewById(R.id.pass_text);
String name= nameText.getText().toString();
String phone=phoneText.getText().toString();
AdapterClass ad1=new AdapterClass(getApplicationContext(),DatabaseDetail.REGISTER);
ad1.Open();
Cursor cursor=ad1.query("SELECT * FROM CUS_REGISTER WHERE CUS_NAME=? AND CUS_PHONE=?",new String[] { name, phone });
Cursor cursor = ad1.fetchRecords(new String[]{}, null);
startManagingCursor(cursor);
cursor.moveToFirst();
if(cursor.getCount() > 0)
{
Toast.makeText(getApplicationContext(), "Sucess", 5000).show();
}else{
}
}
});
}
}
And this my adapter class code
public Cursor query(String args, String[] pColumnValues) {
// TODO Auto-generated method stub
return database.query(DATABASE_TABLE, pColumnValues, args, null, args, args, args);
}
MainActivity Class
package com.example.sqlitedbtestproject;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.app.Activity;
public class MainActivity extends Activity {
AryaDatabaseAdapter help;
EditText name, address, infoFetcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText1);
address = (EditText) findViewById(R.id.editText2);
infoFetcher = (EditText) findViewById(R.id.editText3);
help = new AryaDatabaseAdapter(this);
}
public void addUser(View view)
{
if(help.insertData(name.getText().toString(), address.getText().toString())>0)
{
MessagePopper.message(this, "Successfully Inserted");
}
else
{
MessagePopper.message(this, "Un successfull Attempt");
}
}
public void viewDetail(View view)
{
MessagePopper.message(this, help.getAllData());
}
public void viewUserDetail(View view)
{
MessagePopper.message(this, help.getSpecificData(infoFetcher.getText().toString()));
}
public void updateUserDetail(View view)
{
MessagePopper.message(this, "Updated number of rows are "+help.updateRow(name.getText().toString(),infoFetcher.getText().toString()));
}
public void deleteUserDetail(View view)
{
MessagePopper.message(this, "Deleted number of rows are "+help.deleteRow(infoFetcher.getText().toString()));
}
}
Database Adapter class
package com.example.sqlitedbtestproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AryaDatabaseAdapter
{
Context context;
DBHelper helpDB;
AryaDatabaseAdapter(Context ctx)
{
helpDB = new DBHelper(ctx);
}
public Long insertData(String name, String address)
{ System.out.println("Reached inside insert data ");
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.NAME, name);
contentValues.put(DBHelper.ADDRESS, address);
SQLiteDatabase db = helpDB.getWritableDatabase();
Long l = db.insert(DBHelper.TABLE_NAME, null, contentValues);
System.out.println("Reached inside insert data "+l+" "+name+" "+address);
return l;
}
public String getAllData()
{ System.out.println("Reached inside get data ");
SQLiteDatabase db = helpDB.getWritableDatabase();
String columns[] = {DBHelper.UID,DBHelper.NAME, DBHelper.ADDRESS};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , null,null,null,null,null);
StringBuffer buff=new StringBuffer();
while(cursor.moveToNext())
{
buff.append(cursor.getInt(cursor.getColumnIndex(DBHelper.UID))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.NAME))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS))+" \n ");
}
return buff.toString();
}
public String getSpecificData(String name)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
String columns[] = {DBHelper.UID, DBHelper.ADDRESS};
System.out.println("Name is "+name);
String []selectionArgs = {name};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , DBHelper.NAME+" =? ",selectionArgs,null,null,null);
StringBuffer buff=new StringBuffer();
while(cursor.moveToNext())
{
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.UID));
String address = cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS));
buff.append(id+" "+address+" \n ");
}
return buff.toString();
}
public int updateRow(String oldname , String newName)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.NAME, newName);
String whereArgs[] = {oldname};
return db.update(DBHelper.TABLE_NAME, contentValues, DBHelper.NAME + " =? ", whereArgs);
}
public int deleteRow(String name)
{
SQLiteDatabase db = helpDB.getWritableDatabase();
String whereArgs[] = {name};
return db.delete(DBHelper.TABLE_NAME, DBHelper.NAME + " =? ", whereArgs);
}
static class DBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "aryadatabase";
private final static String TABLE_NAME = "ARYATABLE";
private final static int DATABASE_VERSION = 1;
private final static String UID = "_id";
private final static String NAME = "Name";
private final static String ADDRESS = "Address";
private final static String CREATE = "CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+ADDRESS+" VARCHAR(255));";
private final static String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
Context context ;
public DBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
MessagePopper.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
//CREATE TABLE ARYATABLE (_id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(255));
try
{
db.execSQL(CREATE);
MessagePopper.message(context, "OnCreate Called");
}
catch (SQLException e)
{
MessagePopper.message(context, e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try
{
db.execSQL(DROP_TABLE);
MessagePopper.message(context, "OnUpgarde Called");
onCreate(db);
}
catch (SQLException e)
{
MessagePopper.message(context, e.getMessage());
}
}
}
}
Message or Toast popper example
package com.example.sqlitedbtestproject;
import android.content.Context;
import android.widget.Toast;
public class MessagePopper {
public static void message(Context ctx, String Message)
{
Toast.makeText(ctx, Message, Toast.LENGTH_SHORT).show();
}
}
Layout File
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Name :"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="19dp"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_alignRight="#+id/editText2"
android:layout_below="#+id/editText2"
android:layout_marginTop="18dp"
android:onClick="addUser"
android:text="Add User" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="14dp"
android:onClick="viewDetail"
android:text="View Details" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button2"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:ems="10"
android:hint="Name of person for details" />
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText3"
android:layout_alignRight="#+id/editText3"
android:layout_below="#+id/editText3"
android:onClick="viewUserDetail"
android:text="View User Address" />
<Button
android:id="#+id/button4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button3"
android:layout_alignParentBottom="true"
android:layout_marginBottom="17dp"
android:onClick="updateUserDetail"
android:text="Update" />
<Button
android:id="#+id/button5"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button4"
android:layout_centerHorizontal="true"
android:onClick="deleteUserDetail"
android:text="Delete" />
</RelativeLayout>
View this sample code i have developed and verify against your code. You should upload logcat for precise solution here. :)

Insert sound/audio

I have a database containing a ListView and a picture, I want to include in each of each voice data. I've tried but I got a lot of errors. The following are my java and xml.
Database.java
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database extends SQLiteOpenHelper {
final static String DB_NAME = "db_tum_obat";
public Database(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS tum(_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, nama_latin TEXT, khasiat TEXT, img BLOB, img2 BLOB)";
db.execSQL(sql);
ContentValues values = new ContentValues();
values.put("_id", "1");
values.put("nama", "Jarak Pagar");
values.put("nama_latin", "Jatropha curcas Linn.");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im31);
values.put("img2", R.drawable.home);// im31 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
values.put("_id", "2");
values.put("nama", "Kumis Kucing");
values.put("nama_latin", "Orthosipon aristatus (B1) Miq.");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im32);
values.put("img2", R.drawable.keluar1);// im32 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
values.put("_id", "3");
values.put("nama", "Lidah Buaya");
values.put("nama_latin", "Aloe Verra Linn.");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im33);
values.put("img2", R.drawable.home);// im33 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
values.put("_id", "4");
values.put("nama", "Pandan Wangi");
values.put("nama_latin", "Pandanus amryllifolius Roxb");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im34);
values.put("img2", R.drawable.keluar1);// im34 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS tum");
onCreate(db);
}
}
MainActivity.java
package com.example.database;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
protected ListView lv;
protected ListAdapter adapter;
SQLiteDatabase db;
Cursor cursor;
EditText et_db;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = (new Database(this)).getWritableDatabase();
lv = (ListView) findViewById(R.id.lv);
et_db = (EditText) findViewById(R.id.et);
try {
cursor = db.rawQuery("SELECT * FROM tum ORDER BY nama ASC", null);
adapter = new SimpleCursorAdapter(this, R.layout.isi_lv, cursor,
new String[] { "nama", "nama_latin", "img" }, new int[] {
R.id.tv_nama, R.id.tv_penyebab, R.id.imV });
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
detail(position);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void search_db(View v) {
String edit_db = et_db.getText().toString();
if (!edit_db.equals("")) {
try {
cursor = db.rawQuery("SELECT * FROM tum WHERE nama LIKE ?",
new String[] { "%" + edit_db + "%" });
adapter = new SimpleCursorAdapter(this, R.layout.isi_lv,
cursor, new String[] { "nama", "nama_latin", "img" },
new int[] { R.id.tv_nama, R.id.tv_penyebab, R.id.imV });
if (adapter.getCount() == 0) {
Toast.makeText(
this,
"Tidak ditemukan data dengan kata kunci " + edit_db
+ "", Toast.LENGTH_SHORT).show();
} else {
lv.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
cursor = db.rawQuery("SELECT * FROM tum ORDER BY nama ASC",
null);
adapter = new SimpleCursorAdapter(this, R.layout.isi_lv,
cursor, new String[] { "nama", "nama_latin", "img" },
new int[] { R.id.tv_nama, R.id.tv_penyebab, R.id.imV });
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void detail(int position) {
int im2 = 0;
String _id = "";
String nama = "";
String latin = "";
String khasiat = "";
if (cursor.moveToFirst()) {
cursor.moveToPosition(position);
im2 = cursor.getInt(cursor.getColumnIndex("img2"));
nama = cursor.getString(cursor.getColumnIndex("nama"));
latin = cursor.getString(cursor.getColumnIndex("nama_latin"));
khasiat = cursor.getString(cursor.getColumnIndex("khasiat"));
}
Intent iIntent = new Intent(this, DetailTum.class);
iIntent.putExtra("dataIM2", im2);
iIntent.putExtra("dataNama", nama);
iIntent.putExtra("dataLatin", latin);
iIntent.putExtra("dataKhasiat", khasiat);
setResult(RESULT_OK, iIntent);
startActivityForResult(iIntent, 99);
}
}
DetailTum.java
package com.example.database;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
public class DetailTum extends Activity {
ImageView Im2;
TextView tv_nama, tv_latin, tv_khasiat, id, namaIm;
Gallery gallery;
ImageSwitcher imageSwitcher;
Integer[] imageIDs = new Integer[3];
int msg_im2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
Intent iIdentifikasi = getIntent();
msg_im2 = iIdentifikasi.getIntExtra("dataIM2", 0);
String msg_nama = iIdentifikasi.getStringExtra("dataNama");
String msg_latin = iIdentifikasi.getStringExtra("dataLatin");
String msg_khasiat = iIdentifikasi.getStringExtra("dataKhasiat");
Im2 = (ImageView) findViewById(R.id.iv_detail2);
tv_nama = (TextView) findViewById(R.id.tvNama);
tv_latin = (TextView) findViewById(R.id.tvLatin);
tv_khasiat = (TextView) findViewById(R.id.tvKhasiat);
Im2.setImageResource(msg_im2);
tv_nama.setText(msg_nama);
tv_latin.setText(msg_latin);
tv_khasiat.setText(msg_khasiat);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFF567"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/btn" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="search_db"
android:text="Search" />
<ListView
android:id="#+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et" >
</ListView>
isi_lv.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/tv_nama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/imV"
android:text="TextView"
android:textSize="10pt" />
<TextView
android:id="#+id/tv_penyebab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_nama"
android:layout_below="#+id/tv_nama"
android:text="TextView" />
detail.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:background="#FFF567"
android:orientation="vertical" >
<ImageView
android:id="#+id/iv_detail2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":" />
<TextView
android:id="#+id/tvNama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama Latin" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":" />
<TextView
android:id="#+id/tvLatin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Khasiat" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":" />
<TextView
android:id="#+id/tvKhasiat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
If you wan to save the path, do what Telthien said.
If you want to save the file as a whole,You can save the data as BLOB type. http://www.sqlite.org/datatype3.html

Categories