data is not visible in listview - java

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.

Related

How do i display my database using recyclerview in android studio?

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.

Android Studio E/AndroidRuntime: FATAL EXCEPTION: main [duplicate]

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"

cannot resolve symbol HorizontalListView

I am trying to declare a horizontal listview in my activity like this
private LinearLayout lay;
HorizontalListView listview;
however the HorizontalListView is highlighted in red and I get the error "Cannot resolve symbol HorizontalListView "
Java File
package com.xera.deviceinsight.home;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class SensorCharts extends Activity{
private LinearLayout lay;
HorizontalListView listview;
private double highest;
private int[] grossheight;
private int[] netheight;
private Double[] grossSal= {15000.0,15000.0,15000.25,15000.1,
15000.0,15000.0,15000.0,15000.0,
15000.25,15000.1,15000.0,15000.0};
private Double[] netSal = {12000.0,13000.0,14000.25,10000.1,
10000.0,9000.0,12000.0,13000.0,
14000.25,10000.1,10000.0,9000.0};
private String[] datelabel = {"Jan 12","Feb 12","Mar 12",
"Apr 12","May 12","Jun 12",
"Jul 12","Aug 12","Sep 12",
"Oct 12","Nov 12","Dec 12"};
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
setContentView(R.layout.main);
lay = (LinearLayout)findViewById(R.id.linearlay);
listview = (HorizontalListView) findViewById(R.id.listview);
List<Double> b = Arrays.asList(grossSal);
highest = (Collections.max(b));
netheight = new int[netSal.length];
grossheight= new int[grossSal.length];
//updateSizeInfo();
}
public class bsAdapter extends BaseAdapter
{
Activity cntx;
String[] array;
public bsAdapter(Activity context,String[] arr)
{
// TODO Auto-generated constructor stub
this.cntx=context;
this.array = arr;
}
public int getCount()
{
// TODO Auto-generated method stub
return array.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return array[position];
}
public long getItemId(int position)
{
// TODO Auto-generated method stub
return array.length;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=null;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.list, null);
DecimalFormat df = new DecimalFormat("#.##");
final TextView title = (TextView)row.findViewById(R.id.title);
TextView tvcol1 = (TextView)row.findViewById(R.id.colortext01);
TextView tvcol2 = (TextView)row.findViewById(R.id.colortext02);
TextView gt = (TextView)row.findViewById(R.id.text01);
TextView nt = (TextView)row.findViewById(R.id.text02);
tvcol1.setHeight(grossheight[position]);
tvcol2.setHeight(netheight[position]);
title.setText(datelabel[position]);
gt.setText(df.format(grossSal[position]/1000)+" k");
nt.setText(df.format(netSal[position]/1000)+" k");
tvcol1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(SensorCharts.this, "Month/Year: "+title.getText().toString()+"\nGross Sal: "+grossSal[position], Toast.LENGTH_SHORT).show();
}
});
tvcol2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(SensorCharts.this, "Month/Year: "+title.getText().toString()+"\nNet Sal: "+netSal[position], Toast.LENGTH_SHORT).show();
}
});
return row;
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
updateSizeInfo();
}
private void updateSizeInfo() {
/** This is onWindowFocusChanged method is used to allow the chart to
* update the chart according to the orientation.
* Here h is the integer value which can be updated with the orientation
*/
int h;
if(getResources().getConfiguration().orientation == 1)
{
h = (int) (lay.getHeight()*0.5);
if(h == 0)
{
h = 200;
}
}
else
{
h = (int) (lay.getHeight()*0.3);
if(h == 0)
{
h = 130;
}
}
for(int i=0;i<netSal.length;i++)
{
netheight[i] = (int)((h*netSal[i])/highest);
grossheight[i] = (int)((h*grossSal[i])/highest);
System.out.println("net width[i] "+netheight[i]+"gross width[i] "+grossheight[i]);
}
listview.setAdapter(new bsAdapter(this,datelabel));
}
}
this is part of my xml I where I have the horizontal listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/linearlay">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#000"
android:text="Bar Chart with out any jar"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:background="#ddd"
android:orientation="horizontal">
</RelativeLayout>
<com.xera.deviceinsight.home.HorizontalListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ddd"
/>
</LinearLayout>
Try to read this article which specifies how to use an HorizontalListView.
Declare your HorizontalListView in your XML and give it an id. Then you can use your element in your java functionality.
EDIT:
Here you have a tutorial about how implement easily a HorizontalListView. If you want a more customized version, read this.
There is a third option, which is here, where you can implement all the methods of HorizontalListView and use them (like mRect, setX, setY, onClickListener...).

How to get data from database when clicked on ListView

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?

Android ListView not being populated by custom ParseQueryAdapter

for an app I am making I am attempting to populate a listView with data obtained from parse.com using a custom parsequeryadapter subclass. Basically it just shows a blank activity when opening the activity.
Adapter code
package com.example.battlesim;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseObject;
public class LeaderboardAdapter extends ParseQueryAdapter<ParseObject> {
public Context context;
public LeaderboardAdapter(Context c) {
super(c, new ParseQueryAdapter.QueryFactory<ParseObject>(){
public ParseQuery<ParseObject> create(){
// public final ArrayList<String> leadersName;
// public final ArrayList<Integer> leadersScore;
ParseQuery<ParseObject> queryL = ParseQuery.getQuery("Character");
queryL = queryL.whereNotEqualTo("name", null);
queryL = queryL.orderByDescending("level");
queryL.setLimit(10);
try {
queryL.find();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return queryL;
// queryL.findInBackground(new FindCallback<ParseObject>() {
// public void done(List<ParseObject> scoreList, ParseException e) {
// if (e == null) {
// for(int i = 0; i < 10; i++){
// leadersName.add(scoreList.get(i).getString("name"));
// leadersScore.add(scoreList.get(i).getInt("level"));
// }
// } else {
// Log.d("level", "Error: " + e.getMessage());
// }
// }
}
});
this.context = c;
}
public View getItemView(ParseObject o, View convertView, ViewGroup parent){
View vi = convertView;
if(convertView == null) vi = View.inflate(getContext(), R.layout.board, null);
super.getItemView(o, convertView, parent);
TextView name = (TextView) vi.findViewById(R.id.name);
TextView level = (TextView) vi.findViewById(R.id.level);
name.setText(o.getString("name"));
level.setText(o.getInt("level"));
return vi;
}
}
Activity onCreate code
LeaderboardAdapter adapter = new LeaderboardAdapter(this);
adapter.loadObjects();
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
Board.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" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="25dip"/>
<TextView
android:id="#+id/level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="25dip"/>
</RelativeLayout>
Sorry if I formatted anything oddly or forgot to include anything. I'm new to StackExchange and somewhat new to Android programming
Replace queryL.whereNotEqualTo("name", null); with queryL.whereExists("name");

Categories