I'm new to android and I managed to insert data from EditText into database and I show it into ListView, but now I need to show a single note when clicked on item inside ListView and I just don't know how. I want it to be editable in activity_edit_note.xml .Can someone please help me? Here is my code.
Notes.java
package com.cidecode.xnotes;
public class Notes {
private long id;
private String title;
private String note;
private String date;
public Notes(){
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString(){
return title + "\t" + date + "\n" + note;
}
}
DatabaseHelper.java
package com.cidecode.xnotes;
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String TABLE_NOTES = "notes";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_NOTE = "note";
public static final String COLUMN_DATE = "date";
private static final String DATABASE_NAME = "xnotes.db";
private static final int DATABASE_VERSION = 1;
// Create the database
private static final String DATABASE_CREATE = "create table " + TABLE_NOTES + "(" +
COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE + " text not null, " +
COLUMN_NOTE + " text not null, " + COLUMN_DATE + " text not null);";
// Drop table notes
private static final String DATABASE_DROP_TABLE_NOTES = "drop table if exists " + TABLE_NOTES;
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(android.database.sqlite.SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(android.database.sqlite.SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHelper.class.getName(), "Upgrading database from v" + oldVersion + " to v" +
newVersion + " which will delete all old data.");
db.execSQL(DATABASE_DROP_TABLE_NOTES);
onCreate(db);
}
}
NotesDataSource.java
package com.cidecode.xnotes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.EditText;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class NotesDataSource {
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private String[] allColumns = {DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_TITLE, DatabaseHelper.COLUMN_NOTE, DatabaseHelper.COLUMN_DATE};
public NotesDataSource(Context context){
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException{
database = dbHelper.getWritableDatabase();
}
public void close(){
dbHelper.close();
}
public Notes createNote(String title, String note, String date){
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_TITLE, title);
values.put(DatabaseHelper.COLUMN_NOTE, note);
values.put(DatabaseHelper.COLUMN_DATE, date);
long insertId = database.insert(DatabaseHelper.TABLE_NOTES, null, values);
Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
DatabaseHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Notes newNotes = cursorToNote(cursor);
cursor.close();
return newNotes;
}
public List<Notes> getAllNotes(){
List<Notes> notesList = new ArrayList<Notes>();
Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
Notes note = cursorToNote(cursor);
notesList.add(note);
cursor.moveToNext();
}
cursor.close();
return notesList;
}
private Notes cursorToNote(Cursor cursor){
Notes note = new Notes();
note.setId(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setNote(cursor.getString(2));
note.setDate(cursor.getString(3));
return note;
}
public void deleteNote(int id){
database.delete(DatabaseHelper.TABLE_NOTES, DatabaseHelper.COLUMN_ID + "=" + id, null);
}
}
AddNote.java
package com.cidecode.xnotes;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.SQLException;
public class AddNote extends ActionBarActivity {
private EditText title = null;
private EditText note = null;
private String s_title, s_note, s_date;
Button b_save;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private NotesDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
dbHelper = new DatabaseHelper(this);
datasource = new NotesDataSource(this);
try {
datasource.open();
} catch (SQLException e) {
e.printStackTrace();
}
title = (EditText)findViewById(R.id.id_title);
note = (EditText)findViewById(R.id.id_write_note_here);
s_title = title.getText().toString();
s_note = note.getText().toString();
s_date = "21.11.1111";
b_save = (Button)findViewById(R.id.id_save);
b_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datasource.createNote(title.getText().toString(), note.getText().toString(), s_date);
Toast.makeText(getApplicationContext(), "Note is saved.", Toast.LENGTH_LONG).show();
Log.w("Title: ", title.getText().toString());
Log.w("Note: ", note.getText().toString());
Log.w("Date: ", s_date);
Intent intent = new Intent(AddNote.this, MainActivity.class);
startActivity(intent);
}
});
}
#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_add_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_add_note.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"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#EBD28F">
<TextView
android:id="#+id/id_add_new_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/s_add_new_note"
android:gravity="center"
android:textSize="30sp"
android:layout_marginBottom="10dp"/>
<EditText
android:id="#+id/id_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/s_title"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"/>
<EditText
android:id="#+id/id_write_note_here"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:hint="#string/s_write_note_here"
android:gravity="top" />
<Button
android:id="#+id/id_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="#string/s_save"
android:textColor="#FFFFFF"
android:background="#5E553A"/>
</LinearLayout>
MainActivity.java
package com.cidecode.xnotes;
import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.sql.SQLException;
import java.util.List;
public class MainActivity extends ListActivity {
Button AddNew;
private ListView listView;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private NotesDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DatabaseHelper(this);
datasource = new NotesDataSource(this);
try {
datasource.open();
} catch (SQLException e) {
e.printStackTrace();
}
List<Notes> values = datasource.getAllNotes();
final ArrayAdapter<Notes> adapter = new ArrayAdapter<Notes>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return false;
}
});
AddNew = (Button)findViewById(R.id.id_add_new);
AddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddNote.class);
startActivity(intent);
}
});
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
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"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#EBD28F">
<TextView
android:id="#+id/id_xnotes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/s_xnotes"
android:gravity="center"
android:textSize="30sp"
android:layout_marginBottom="10dp"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:longClickable="true"></ListView>
<Button
android:id="#+id/id_add_new"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="#string/s_add_new"
android:textColor="#FFFFFF"
android:background="#5E553A"/>
</LinearLayout>
EditNote.java
package com.cidecode.xnotes;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class EditNote extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
}
#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_edit_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_edit_note.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"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#EBD28F">
<TextView
android:id="#+id/id_add_new_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/s_edit_note"
android:gravity="center"
android:textSize="30sp"
android:layout_marginBottom="10dp"/>
<EditText
android:id="#+id/id_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/s_title"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"/>
<EditText
android:id="#+id/id_write_note_here"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:hint="#string/s_write_note_here"
android:gravity="top" />
<Button
android:id="#+id/id_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="#string/s_save"
android:textColor="#FFFFFF"
android:background="#5E553A"/>
</LinearLayout>
Its a method to get single note by COLUMN_ID
public Notes getSingleNote(long id){
Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
COLUMN_ID +"=?", new String[]{String.valueOf(id)}, null, null, null);
Note note = null;
if(cursor.moveToFirst())
note = cursorToNote(cursor);
cursor.close();
return note;
}
Declare List<Notes> values globally. And update your listView item click listener like below mentioned:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Notes selectedNote = values.get(position);
}
});
Here "selectedNote" selected item. And pass this item by following the below link.
How do I pass an object from one activity to another on Android?
Related
When the user logins an activity where the user can create their account opens (CreateProfileActivity). When the profile is created the user is redirected to the recyclerView activity where their profile info is displayed in a recyclerView. When user clicks on the item in recyclerView the Update Activity will open. I want their profile information from the recyclerView to load on the Update Activity. Please help.
P.S. Since I haven't made the CreateProfile_Activity open only once, as I don't want the user to create more than one profile, So for now: I ran the app once and created an account and then I changed it so now when the user logins it opens the recyclerView_Activity.
Here is the recyclerView_Activity
package com.example.insert_update_activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class recyclerView_Activity extends AppCompatActivity {
// Button insertBtn;
RecyclerView recyclerView;
DBHelper myDB;
ArrayList<String> temp_id, temp_name, temp_age;
myAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
/* insertBtn = (Button) findViewById(R.id.insertBtn);
insertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(recyclerView_Activity.this, Insert_Activity.class);
startActivity(intent);
}
});*/
myDB = new DBHelper(recyclerView_Activity.this);
temp_id = new ArrayList<>();
temp_name = new ArrayList<>();
temp_age = new ArrayList<>();
storeDataInArrays();
myAdapter = new myAdapter(recyclerView_Activity.this, this, temp_id, temp_name, temp_age);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView_Activity.this));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
{
recreate();
}
}
void storeDataInArrays() {
Cursor cursor = myDB.readData(); // Cursor cursor = myDB.readAllData();
if (cursor.getCount() == 0)
{
Toast.makeText(recyclerView_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
}
else
{
while (cursor.moveToNext()) {
temp_id.add(cursor.getString(0));
temp_name.add(cursor.getString(1));
temp_age.add(cursor.getString(2));
}
}
}
}
Here is the UpdateActivity
package com.example.insert_update_activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class Update_Activity extends AppCompatActivity {
EditText name, age;
Button updateBtn;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
name = (EditText) findViewById(R.id.edit_name);
age = (EditText) findViewById(R.id.edit_age);
updateBtn = (Button) findViewById(R.id.updateBtn);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sName = name.getText().toString().trim();
String sAge = age.getText().toString().trim();
DBHelper db = new DBHelper(Update_Activity.this);
db.updateData(id, sName, sAge);
Intent intent = new Intent(Update_Activity.this, com.example.insert_update_activity.recyclerView_Activity.class);
startActivity(intent);
}
});
getAndSetIntentData();
}
void getAndSetIntentData() {
if (getIntent().hasExtra("id") && getIntent().hasExtra("Name") && getIntent().hasExtra("Age"))
{
// Getting data from Intent
id = getIntent().getStringExtra("id");
String NAME = getIntent().getStringExtra("Name");
String AGE = getIntent().getStringExtra("Age");
// Setting Intent Data
name.setText(NAME);
age.setText(AGE);
}
else
{
Toast.makeText(Update_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
}
}
}
Here is the DBHelper
package com.example.insert_update_activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "Database.db";
private static final int DATABASE_VERSION = 1;
// Create table
private static final String TABLE_TEMP = "TEMPP";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
public DBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String profileQuery = "CREATE TABLE " + TABLE_TEMP +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_AGE + " INTEGER " + ")";
db.execSQL(profileQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEMP);
onCreate(db);
}
// Functions for TEMP TABLE ******************************************************************************************************************************************** PROFILE TEMP
public Boolean insertData(String name, String age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, name);
cv.put(COLUMN_AGE, age);
long result = db.insert(TABLE_TEMP, null, cv);
if (result == -1) {
Toast.makeText(context, "Failed to Insert", Toast.LENGTH_SHORT).show();
return false;
} else {
Toast.makeText(context, "Data Inserted Successfully!", Toast.LENGTH_SHORT).show();
return true;
}
}
Cursor readData() {
String query = "SELECT * FROM " + TABLE_TEMP;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null) {
cursor = db.rawQuery(query, null);
}
return cursor;
}
// Update data using where clause;
public Boolean updateData(String row_id, String name, String age)
{
SQLiteDatabase db = this.getWritableDatabase(); // SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, name);
cv.put(COLUMN_AGE, age);
long result = db.update(TABLE_TEMP, cv, COLUMN_ID + " =? ", new String[]{row_id});
if (result == -1)
{
Toast.makeText(context, "Failed to Update", Toast.LENGTH_SHORT).show();
return false;
}
else
{
Toast.makeText(context, "Successfully Updated!", Toast.LENGTH_SHORT).show();
return true;
}
}
}
Here is the Adapter
package com.example.insert_update_activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class myAdapter extends RecyclerView.Adapter<myAdapter.MyViewHolder> {
private Context context;
Activity activity;
private ArrayList id, name, age;
myAdapter(Activity activity, Context context, ArrayList id, ArrayList name, ArrayList age) {
this.activity = activity;
this.context = context;
this.id = id;
this.name = name;
this.age = age;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.id_txt.setText(String.valueOf(id.get(position)));
holder.name_txt.setText(String.valueOf(name.get(position)));
holder.age_txt.setText(String.valueOf(age.get(position)));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Update_Activity.class);
intent.putExtra("id", String.valueOf(id.get(position)));
intent.putExtra("name", String.valueOf(name.get(position)));
intent.putExtra("age", String.valueOf(age.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id_txt, name_txt, age_txt;
LinearLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id_txt = itemView.findViewById(R.id.id_txt);
name_txt = itemView.findViewById(R.id.name_txt);
age_txt = itemView.findViewById(R.id.age_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
And here is the xml file my_row for the recyclerView
<?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="wrap_content"
android:orientation="vertical"
android:id="#+id/mainLayout">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:outlineSpotShadowColor="#000000"
app:cardElevation="3dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp">
<TextView
android:id="#+id/id_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="1"
android:textColor="#9A9797"
android:textSize="35dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/nameTitle"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="NAME:"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ageTitle"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="AGE:"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="#+id/nameTitle"
app:layout_constraintTop_toBottomOf="#+id/nameTitle" />
<TextView
android:id="#+id/name_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="15sp"
app:layout_constraintStart_toEndOf="#+id/nameTitle"
app:layout_constraintTop_toTopOf="#+id/nameTitle" />
<TextView
android:id="#+id/age_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:textSize="15sp"
app:layout_constraintStart_toEndOf="#+id/ageTitle"
app:layout_constraintTop_toBottomOf="#+id/nameTitle" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
The login activity is pretty simple. It just allows the user to login if username == "User1" and password == "123456".
The CreateProfile_Activity just uses the insertData once
Okay so now it works. I'm not sure this is why, but I will post the changes I made.
So one problem was in myAdapter. In the mainLayout OnClick the "name" and "age" where different from the "Name" and "Age" in the UpdateActivity where I get data from Intent. The first letters of both 'age' and 'name' were not in CAPITALS.
Another thing I changed was the get(position) in the onBindHolder.
Now the onBindHolder looks like this:
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.id_txt.setText(String.valueOf(id.get(holder.getAdapterPosition())));
holder.name_txt.setText(String.valueOf(name.get(holder.getAdapterPosition())));
holder.age_txt.setText(String.valueOf(age.get(holder.getAdapterPosition())));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Update_Activity.class);
intent.putExtra("id", String.valueOf(id.get(holder.getAdapterPosition())));
intent.putExtra("Name", String.valueOf(name.get(holder.getAdapterPosition())));
intent.putExtra("Age", String.valueOf(age.get(holder.getAdapterPosition())));
v.getContext().startActivity(intent);
//activity.startActivityForResult(intent, 1);
}
});
}
Hope it helps anyone
I don't know what I'm doing wrong. I was ready to migrate from listview to recyclerview and followed the syntax then it gives me an error of
"element == null" from my build output
Here's my Databasehelper file:
package com.revise;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String NAME_TABLE = "NAME_TABLE";
public static final String COL_ID = "COLUMN_ID";
public static final String COLUMN_NAME = "COLUMN_NAME";
public static final String COLUMN_PRICE = "COLUMN_PRICE";
public static final String COLUMN_QUANTITY = "COLUMN_QUANTITY";
public static final String COLUMN_TOTAL = "COLUMN_TOTAL";
//private static final int DATABASE_VERSION = 2;
public DataBaseHelper(#Nullable Context context) {
super(context, "item.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + NAME_TABLE + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_NAME + " TEXT, "
+ COLUMN_PRICE + " FLOAT, "
+ COLUMN_QUANTITY + " INT, "
+ COLUMN_TOTAL + " FLOAT)";
db.execSQL(createTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+NAME_TABLE);
onCreate(db);
}
public boolean addOne(Product product){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, product.getName());
cv.put(COLUMN_PRICE, product.getPrice());
cv.put(COLUMN_QUANTITY, product.getQuantity());
cv.put(COLUMN_TOTAL, product.getTotal());
long insert = db.insert(NAME_TABLE, null, cv);
if(insert==-1){
return false;
}
else{ return true; }
}
public boolean deleteOne(Product product){
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM "+NAME_TABLE+" WHERE " +COLUMN_NAME+ "=" +product.getName();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
return true;
}else { return false; }
}
public List<Product> getEveryone(){
List<Product> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + NAME_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
do{
String name = cursor.getString(1);
float price = cursor.getFloat(2);
int quantity = cursor.getInt(3);
Product newProduct = new Product(name, price, quantity);
returnList.add(newProduct);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return returnList;
}
}
Here's my RecyclerViewAdapter:
package com.revise;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
List<Product> productList;
Context context;
public RecyclerViewAdapter(List<Product> productList, Context context) {
this.productList = productList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//itemlayout is the name of the layout that we are gonna be using
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemlayout,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
holder.tv_name.setText(productList.get(position).getName());//tv_name
holder.tv_price.setText(String.valueOf(productList.get(position).getPrice()));
holder.tv_qty.setText(String.valueOf(productList.get(position).getQuantity()));
holder.tv_total.setText(String.valueOf(productList.get(position).getTotal()));
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
//variables from my itemlayout
TextView tv_name, tv_price, tv_qty, tv_total;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = itemView.findViewById(R.id.tv_name);
tv_price = itemView.findViewById(R.id.tv_price);
tv_qty = itemView.findViewById(R.id.tv_qty);
tv_total = itemView.findViewById(R.id.tv_total);
}
}
}
The activity that is configuring the buttons:
package com.revise;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DataActivity extends AppCompatActivity {
Button bt_add;
EditText et_name, et_price, et_qty;
DataBaseHelper myDb;
List<Product> productList = new ArrayList<Product>();
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_add = findViewById(R.id.bt_add);
et_name = findViewById(R.id.et_name);
et_price = findViewById(R.id.et_price);
et_qty = findViewById(R.id.et_qty);
//lv_itemlist = findViewById(R.id.lv_itemlist);
myDb = new DataBaseHelper(DataActivity.this);
fillProductList(myDb);
bt_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Product p = new Product();
try {
p.setName(et_name.getText().toString());
p.setPrice(Float.parseFloat(et_price.getText().toString()));
p.setQuantity(Integer.parseInt(et_qty.getText().toString()));
} catch (Exception e){
Toast.makeText(DataActivity.this,"Exception:"+e,Toast.LENGTH_SHORT).show();
}
DataBaseHelper dataBaseHelper = new DataBaseHelper(DataActivity.this);
dataBaseHelper.addOne(p);
}
});
recyclerView = findViewById(R.id.lv_itemlist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(DataActivity.this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new RecyclerViewAdapter(productList, DataActivity.this);
recyclerView.setAdapter(mAdapter);
}
private void fillProductList(DataBaseHelper myDb) {
productList.addAll(myDb.getEveryone());
}
}
and it's corresponding xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DataActivity">
<EditText
android:id="#+id/et_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/et_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="numberDecimal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/et_name" />
<EditText
android:id="#+id/et_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/et_price" />
<Button
android:id="#+id/bt_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.189"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/et_qty" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/lv_itemlist"
android:layout_width="384dp"
android:layout_height="456dp"
android:layout_marginTop="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bt_add" />
</androidx.constraintlayout.widget.ConstraintLayout>
One thing I notice is your mAdapter is of type RecyclerView.Adapter not RecyclerViewAdapter.
There are a bunch of videos and articles on working with recycler views that I suggest you watch. Also start using Androids Room library. It's the recommended way to work with SQLite. There is a codelab for it, I believe called Room with a View.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
this ERROR came after i was modifying those click listeners
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.apple.sqlite, PID: 31591
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apple.sqlite/com.example.apple.sqlite.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setKeyListener(android.text.method.KeyListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setKeyListener(android.text.method.KeyListener)' on a null object reference
at com.example.apple.sqlite.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
MainActivity.java code
package com.example.apple.sqlite;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Calendar calendar;
private TextView dateView;
private int year, month, day;
private ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
dateView = (TextView) findViewById(R.id.SQDate);
dateView.setKeyListener(null);
Button dateButton = (Button)findViewById(R.id.DateButton);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
dateButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
String format = getString(R.string.setdate) + setDateFormat(year,month,day);
dateView.setText(format);
}
}, year,month, day).show();
}
});
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
private String setDateFormat(int year,int monthOfYear,int dayOfMonth){
return String.valueOf(year) + "-"
+ String.valueOf(monthOfYear + 1) + "-"
+ String.valueOf(dayOfMonth);
}
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca",
Toast.LENGTH_SHORT)
.show();
}
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(year).append("-")
.append(month).append("-").append(day));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
DisplayContact.java code
package com.example.apple.sqlite;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by Apple on 2017/3/5.
*/
public class DisplayContact extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView date ;
TextView item;
TextView describe;
TextView money;
int id_To_Update = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
date = (TextView) findViewById(R.id.SQDate);
item = (TextView) findViewById(R.id.SQItem);
describe = (TextView) findViewById(R.id.SQDescribe);
money = (TextView) findViewById(R.id.SQMoney);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String xdate = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_DATE));
String xitem = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_ITEM));
String xdescribe = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_DESCRIBE));
String xmoney = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_MONEY));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.EnterButton);
b.setVisibility(View.INVISIBLE);
date.setText((CharSequence)xdate);
date.setFocusable(false);
date.setClickable(false);
item.setText((CharSequence)xitem);
item.setFocusable(false);
item.setClickable(false);
describe.setText((CharSequence)xdescribe);
describe.setFocusable(false);
describe.setClickable(false);
money.setText((CharSequence)xmoney);
money.setFocusable(false);
money.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.main_menu, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem items) {
super.onOptionsItemSelected(items);
switch(items.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.EnterButton);
b.setVisibility(View.VISIBLE);
date.setEnabled(true);
date.setFocusableInTouchMode(true);
date.setClickable(true);
item.setEnabled(true);
item.setFocusableInTouchMode(true);
item.setClickable(true);
describe.setEnabled(true);
describe.setFocusableInTouchMode(true);
describe.setClickable(true);
money.setEnabled(true);
money.setFocusableInTouchMode(true);
money.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(items);
}
}
/*public void run(View view) {
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,date.getText().toString(),
item.getText().toString(), describe.getText().toString(),
money.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(date.getText().toString(), item.getText().toString(),
describe.getText().toString(), money.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
}*/
}
DBHelper.java code
package com.example.apple.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by Apple on 2017/3/4.
*/
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_DATE = "date";
public static final String CONTACTS_COLUMN_ITEM = "item";
public static final String CONTACTS_COLUMN_DESCRIBE = "describe";
public static final String CONTACTS_COLUMN_MONEY = "money";
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE contacts " +
"(_id INTEGER PRIMARY KEY NOT NULL , " +
"date DATETIME NOT NULL , " +
"item VARCHAR, " +
"describe VARCHAR," +
"money INTEGER)"
);
}
public boolean insertContact (String date, String item, String describe, String money) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("date", date);
contentValues.put("item", item);
contentValues.put("describe", describe);
contentValues.put("money", money);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, "contacts");
return numRows;
}
public boolean updateContact (Integer id, String date, String item, String describe, String money) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("date", date);
contentValues.put("item", item);
contentValues.put("describe", describe);
contentValues.put("money", money);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex("contacts")));
res.moveToNext();
}
return array_list;
}
}
I reference two web and created this project
http://www.tutorialspoint.com/android/android_sqlite_database.htm
https://www.tutorialspoint.com/android/android_datepicker_control.htm
How can I do?
activity_main.xml
<?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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30sp"
android:text="#string/DataBase" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
activity_display_contact.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" >
<TextView
android:id="#+id/Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/enter"
android:textSize="26sp"
android:textStyle="normal" />
<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/item" />
<EditText
android:id="#+id/SQItem"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint=""/>
</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/describe" />
<EditText
android:id="#+id/SQDescribe"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint=""/>
</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/money" />
<EditText
android:id="#+id/SQMoney"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint=""/>
</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/date" />
<EditText
android:id="#+id/SQDate"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint=""/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/EnterButton"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/news" />
<Button
android:id="#+id/DateButton"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/choose" />
<Button
android:id="#+id/CancelButton"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel" />
</LinearLayout>
</LinearLayout>
In your layout activity_main.xml, is there any TextView with android:id="#+id/SQDate"?
I guess you are trying to call that TextView from another .xml
Edited:
Your View that has ID = SQDate is not a TextView, it is an EditText.
In your MainActivity class, change this:
private TextView dateView;
and
dateView = (TextView) findViewById(R.id.SQDate);
To:
private EditText dateView;
and
dateView = (EditText) findViewById(R.id.SQDate);
change your TextView Id to SQDate in activity_main.xml
Replace :
android:id="#+id/textView"
With:
android:id="#+id/SQDate"
I have tried to created a button to delete the whole table records but I got this error message "java.lang.IllegalStateException: Could not find a method deleteAll(View) in the activity class com.example.android.ch2.user for onClick handler on view class android.widget.Button with id 'b_delete'
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4780)
Any ideas that really helpful. Thanks
XML code:
<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.example.android.ch2.user">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View User"
android:id="#+id/button20"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="68dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="#+id/b_delete"
android:layout_alignTop="#+id/button20"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="deleteAll"
android:enabled="true"
android:clickable="true" />
</RelativeLayout>
Java code:
package com.example.android.ch2;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class user extends ActionBarActivity {
private static final String TABLE_NAME = "reg_info";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
}
#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_user, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void deleteAll()
{
SQLiteDatabase db = null;
db.execSQL("delete * from "+ TABLE_NAME);
db.close();
}}
JavaHelper
package com.example.android.ch2;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int database_version = 1;
public String CREATE_QUERY = "CREATE TABLE "+ TableData.TableInfo.TABLE_NAME+" ("+ TableData.TableInfo.USER_NAME+" TEXT,"+ TableData.TableInfo.USER_EMAIL+" TEXT,"+ TableData.TableInfo.USER_FOOD+" TEXT);";
public DatabaseOperations(Context context){
super(context, TableData.TableInfo.DATABASE_NAME, null, database_version);
Log.d ("Database operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation (DatabaseOperations dop, String name,String email,String food){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_EMAIL, email);
cv.put(TableData.TableInfo.USER_FOOD, food);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d ("Database operations", "One raw inserted");
}
}
Your method signature should be public void deleteAll(View view)
Edit
Ok, so why don't we try this:
public void deleteAll(View view) {
DatabaseOperations helper = new DatabaseOperations(this);
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("DELETE FROM " + TableData.TableInfo.TABLE_NAME);
db.close();
}
I tried all possible cases but data is not showing in the list from database.my starting activity have list view which is to be empty in starting and when user fill the data and save it from another activity,ans press back button the data should be shown in the first activity which have list view.,but every time data is not show
MainActivty.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Campaign_Details extends Activity {
private Demo selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_demostration);
TextView text1=(TextView) findViewById(R.id.text1);
TextView text2=(TextView) findViewById(R.id.text1);
DataBaseHandler info= new DataBaseHandler(this);
info.open();
String data=info.getData();
info.close();
String[] values= new String[]{ data };
//txt.setText(data);
// Button next=(Button) findViewById(R.id.next);
// Map<String, String[]> storage = new HashMap<String, String[]>();
// String[] tableItems = storage.get("ContactTable");
// next.setOnClickListener(this);
// final ListView listview = (ListView) findViewById(R.id.listview);
ListView listview1 = (ListView) findViewById(R.id.listview1);
// TextView emptyText = (TextView)findViewById(android.R.id.empty);
//listview.setEmptyView(findViewById(R.id.empty));
// TextView emptyText = (TextView)findViewById(android.R.id.empty);
// listview .setEmptyView(emptyText);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
selectedAdapter = new Demo(this,values);
ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(selectedAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent n = new Intent(getApplicationContext(), SmsSend.class);
startActivity(n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.nextPage:
Intent i = new Intent(this,SmsSend.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
demo.java
package com.example.smscampaign;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Demo extends ArrayAdapter{
private Campaign_Details list1;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Demo(Context context, String[] values) {
super(context, R.layout.list);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.data);
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.data);
text1.setText(values[position]);
return v;
}
}
activity_list_demonstration.xml
<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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:stretchColumns="3" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textcolour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="#drawable/green_circle" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10dp"
android:text="Active Campaign"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4AE56B" />
<TextView
android:id="#+id/textnum1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="130dp"
android:background="#drawable/green_badge"
android:gravity="center"
android:text=" 0 "
android:textColor="#color/white" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="240dp"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:stretchColumns="3" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textcolour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="#drawable/grey_circle" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Closed Campaign"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textnum2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="130dp"
android:background="#drawable/grey_badge"
android:gravity="center"
android:text=" 0 "
android:textColor="#color/white" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="140dp"
android:orientation="vertical" >
<ListView
android:id="#+id/listview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text" >
</TextView>
</LinearLayout>
DatabaseHandler.java// databaseclass
package com.example.smscampaign;
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.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandler{
public static final String KEY_ROWID="_id";
public static final String KEY_NAME="person_name";
public static final String KEY_SCALE="scale_person";
private static final String DATABASE_NAME="Scaledb";
private static final String DATABASE_TABLE="peopleTable";
private static final int DATABASE_VERSION=1;
private DbHelper ourHepler;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_SCALE + " TEXT NOT NULL );"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
onCreate(db);
}
}
public DataBaseHandler(Context c){
ourContext=c;
}
public DataBaseHandler open() throws SQLException{
ourHepler = new DbHelper(ourContext);
ourDatabase= ourHepler.getWritableDatabase();
return this;
}
public void close()
{
ourHepler.close();
}
public long entryCreate(String name, String scale) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_SCALE, scale);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col, null, null, null, null, null);
String run="";
int iRow=c.getColumnIndex(KEY_ROWID);
int iName=c.getColumnIndex(KEY_NAME);
int iScale=c.getColumnIndex(KEY_SCALE);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
run=run+c.getString(iRow)+ " " + c.getString(iName) + " " + c.getString(iScale) + "\n";
}
return run;
}
public String getScale(long l) {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String scale=c.getString(2);
return scale;
}
return null;
}
public String getName(long l) {
// TODO Auto-generated method stub
String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String name=c.getString(1);
return name;
}
return null;
}
public void updateEntry(long lt, String mName, String mScale) {
// TODO Auto-generated method stub
ContentValues cvUpdate=new ContentValues();
cvUpdate.put(KEY_NAME,mName);
cvUpdate.put(KEY_SCALE,mScale);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "-" + lt, null);
}
public void deleteEntry(long ltt) throws SQLException{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + ltt,null);
}
}
You need to change at some places. You have declared your arraylist globally as a
private ArrayList<String> list;
after that again you have declared on onCreate() method
final ArrayList<String> list = new ArrayList<String>();
So replace that by
list = new ArrayList<String>();
Now in your all data is added in your list but in your adapter you have passed values string array. So you also need to change from
selectedAdapter = new Demo(this,values);
to
selectedAdapter = new Demo(this,list);
Change the getview method contents.
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.data);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
Also if you are not customizing layout[using only a textview] use the arrayadapter straightaway by choosing default layout.
in your ArrayAdapter you wrote
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
} else
v = convertView;
Remove the else statement. or rather remove the complete if-else statement. Also
TextView text1 = (TextView) v.findViewById(R.id.data); is extra you have already defined this specific TextView in label
EDIT
public Demo(Context context, String[] values) {
super(context, R.layout.list);
this.context = context;
this.values = values;
}
to
public Demo(Context context, String[] values) {
super(context, R.layout.list,values);
this.context = context;
this.values = values;
}
press back button the data should be shown in the first activity
You write your database loading code in onCreate() method which executes once in its life-cycle i.e when your application starts or when activity destroyed like in orientation changes.
So when you press back button the onCreate() has not called and the same will be continue with list.
Some suggessions:
its good if you write all database stuff in your onResume()
otherwise call finish() in your onPause() method of your main activity and again start it through intent in back pressed method of your second_activity..finish() kills the activity when you go to next one ..and again recreate when you come from the second through strtaActivity followed by its corresponding intent.
And also its better if you use StringTokenizer when you get data from database and put into String array.