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"
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 am new to Android and building a simple To do List.
In a custom layout for an Alert Builder View, I want to retreive the user input in two EditText fields from this custom layout.
This is the custom view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="118dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/describe"
android:textColor="#A4C639" />
<EditText
android:id="#+id/task_description"
android:layout_width="155dp"
android:layout_height="wrap_content"
android:gravity="top|left"
android:inputType="textMultiLine|textAutoComplete|textAutoCorrect|textCapSentences"
android:lines="4"
android:minLines="2"
android:hint="#string/text_hint"
android:imeOptions="actionNext|actionDone"
android:scrollbars="horizontal" />
<requestFocus />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView2"
android:layout_width="118dp"
android:layout_height="92dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/when"
android:textColor="#A4C639" />
<EditText
android:id="#+id/task_date"
android:layout_width="155dp"
android:layout_height="wrap_content"
android:gravity="top|left"
android:inputType="date"
android:imeOptions="actionNext|actionDone"
android:scrollbars="horizontal" />
<requestFocus />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/task_relevance"
android:textColor="#A4C639" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/task_favourite"
/>
<!--
<Button
android:layout_width="64dp"
android:layout_height="wrap_content"
android:text="#string/save"
android:id="#+id/describetaskButton"
android:onClick="saveEntryClickFunction"
android:layout_weight="0.14" />-->
</LinearLayout>
</LinearLayout>
This is the Main Activity:
package com.example.TodoList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.example.TodoList.db.TaskContract;
import com.example.TodoList.db.TaskDBHelper;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import static com.example.TodoList.R.id.task_description;
import static com.example.TodoList.db.TaskContract;
public class MainActivity extends ListActivity {
private ListAdapter listAdapter;
private TaskDBHelper helper;
private Toolbar toolbar;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText inputField = new EditText(this);
builder.setNegativeButton("Abbrechen", null);
switch (item.getItemId()) {
case R.id.action_detail_task:
Intent TaskActivityIntent = new Intent(getApplicationContext(),
TaskActivity.class);
startActivity(TaskActivityIntent);
return true;
case R.id.action_add_task:
LayoutInflater inflater = (this).getLayoutInflater();
builder.setTitle("Eine Aufgabe hinzufügen");
builder.setMessage("Was möchten Sie erledigen? Bitte benennen Sie die Aufgabe");
builder.setView(R.layout.custom_view);
final View view=inflater.inflate(R.layout.custom_view, null);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
View v = (View) view.getParent();
final EditText taskDescription;
taskDescription = (EditText)view.findViewById(R.id.task_description);
taskDescription.getText().toString().trim();
Log.d("EditText TaskDate", taskDescription.getText().toString().trim());
final EditText taskDate;
taskDate = (EditText) view.findViewById(R.id.task_date);
taskDate.getText().toString().trim();
Log.d("EditText TaskDate", taskDate.getText().toString().trim());
final CheckBox taskFavourite;
taskFavourite = (CheckBox) view.findViewById(R.id.task_favourite);
if (taskFavourite.isChecked()) {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(Columns.FAVOURITE, String.valueOf(taskFavourite));
db.insertWithOnConflict(TaskContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
} else {
Log.d("Task Activity", "Checkbox is not checked");
}
Log.d("Task Text", taskDescription.getText().toString().trim());
Log.d("Task Date", taskDate.getText().toString().trim());
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK_DESCRIPTION, task_description);
values.put(Columns.DATE, String.valueOf(taskDate));
//values.put(Columns.FAVOURITE, String.valueOf(taskFavourite));
db.insertWithOnConflict(TaskContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
db.close();
}
});
builder.create().show();
return true;
case R.id.action_remove_task:
builder.setTitle("Eine Aufgabe entfernen");
builder.setMessage("Wurde die Aufgabe bereits erledigt?");
View checkBoxView = View.inflate(this, R.layout.checkbox, null);
CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox);
builder.setView(checkBoxView);
builder.setNegativeButton("Entfernen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TABLE,
Columns.TASK,
Columns.TASK_DESCRIPTION,
Columns.TASK_STATUS,
Columns.DATE,
Columns.FAVOURITE,
task);
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
sqlDB.close();
updateUI();
}
});
builder.create().show();
return true;
default:
return false;
}
}
public void onDoneCheckBoxClick(View view) {
Log.d("onDoneCheckBoxClick", "First Check Box Click Function");
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TABLE,
TaskContract.Columns.TASK,
task);
sqlDB.execSQL(sql);
sqlDB.close();
updateUI();
}
public void DetailClick(View view) {
Intent TaskActivityIntent = new Intent(getApplicationContext(),
TaskActivity.class);
startActivity(TaskActivityIntent);
}
private void updateUI() {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TABLE,
new String[]{Columns._ID, Columns.TASK, Columns.DATE,
Columns.TASK_STATUS
},
null, null, null, null, null
);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{Columns.TASK, Columns.DATE, Columns.TASK_STATUS},
new int[]{R.id.taskTextView,R.id.taskDateView,R.id.task_favourite},
0
);
this.setListAdapter(listAdapter);
}
public void onDetailViewClick(View view) {
Intent TaskActivityIntent = new Intent(getApplicationContext(),
TaskActivity.class);
startActivity(TaskActivityIntent);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.TodoList/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.TodoList/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
I am not receiving any logged input from the EditText in the logcat.
Any hints or help would be very appreciated!
You're using a view that is different from the one that's in the dialog.
Try casting the dialogInterface to Dialog:
taskDescription = (EditText) ((Dialog) dialogInterface).findViewById(R.id.task_description);
I just want to identify that which groupView has been clicked from an expandableListView. Cause I want to send the clicked groupView's text to another activity. I have also seen this link, but it didn't solve my problem.
Identifying the group that has been clicked in an expandableListView
I also tried by sending the groupPosition and it still didn't solve my problem.
Here is my code.
CategoryList.java:
package com.remindme.sayem.remindme;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class CategoryList extends AppCompatActivity {
private ExpandableListView categoryListView;
private CategoryListAdapter categoryListAdapter;
List<String> listDataHeader;
HashMap<String, List<String> > listDataChild;
int group_size, child_size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_list);
categoryListView = (ExpandableListView) findViewById(R.id.categoryListView);
prepareListData();
categoryListAdapter = new CategoryListAdapter(this, listDataHeader, listDataChild);
categoryListView.setAdapter(categoryListAdapter);
categoryListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if(categoryListAdapter.getChildrenCount(groupPosition) == 0){
Intent intent = new Intent(CategoryList.this, ItemEditorActivity.class);
intent.putExtra("GROUP_POSITION", groupPosition);
startActivity(intent);
}
return false;
}
});
}
private void prepareListData(){
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String> >();
// Adding group data
listDataHeader.add("Pharmacy");
listDataHeader.add("Super Shop");
listDataHeader.add("Stationery Shop");
listDataHeader.add("Market");
listDataHeader.add("Hotel");
listDataHeader.add("Hardware shop");
listDataHeader.add("Computer Accessories Shop");
listDataHeader.add("Others");
// Adding child data
List<String> pharmacy = new ArrayList<String>();
pharmacy.add("a");
pharmacy.add("a");
pharmacy.add("a");
pharmacy.add("a");
pharmacy.add("a");
List<String> super_shop = new ArrayList<String>();
List<String> stationery_shop = new ArrayList<String>();
List<String> market = new ArrayList<String>();
List<String> hotel = new ArrayList<String>();
List<String> hardware_shop = new ArrayList<String>();
List<String> computer_accessories_shop = new ArrayList<String>();
List<String> others = new ArrayList<String>();
listDataChild.put(listDataHeader.get(0), pharmacy);
listDataChild.put(listDataHeader.get(1), super_shop);
listDataChild.put(listDataHeader.get(2), stationery_shop);
listDataChild.put(listDataHeader.get(3), market);
listDataChild.put(listDataHeader.get(4), hotel);
listDataChild.put(listDataHeader.get(5), hardware_shop);
listDataChild.put(listDataHeader.get(6), computer_accessories_shop);
listDataChild.put(listDataHeader.get(7), others);
}
public class CategoryListAdapter extends BaseExpandableListAdapter{
private Context _context;
private List<String> _listDataHeader; // Header titles
private HashMap<String, List<String> > _listDataChild; // Child Items
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
public CategoryListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listDataChild;
}
#Override
public int getGroupCount() {
group_size = this._listDataHeader.size();
return group_size;
}
#Override
public int getChildrenCount(int groupPosition) {
child_size = this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
//CategoryList.this.group_size = groupPosition;
return child_size;
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.category_item, null);
}
TextView categoryItem = (TextView) convertView.findViewById(R.id.categoryItem);
categoryItem.setText(getGroup(groupPosition).toString());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.item_name, null);
}
TextView itemName = (TextView) convertView.findViewById(R.id.itemName);
itemName.setText(getChild(groupPosition, childPosition).toString());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
ItemEditorActivity.java:
package com.remindme.sayem.remindme;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ItemEditorActivity extends AppCompatActivity implements View.OnClickListener{
EditText itemEditorEditText;
Button doneButton;
Button addDataButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_editor);
itemEditorEditText = (EditText) findViewById(R.id.itemEditorEditText);
doneButton = (Button) findViewById(R.id.doneButton);
addDataButton = (Button) findViewById(R.id.addDataButton);
addDataButton.setOnClickListener(this);
doneButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addDataButton:
String itemEditorString = itemEditorEditText.getText().toString();
ItemListDatabase itemListDatabase = new ItemListDatabase(ItemEditorActivity.this);
itemListDatabase.open();
if (getIntent().getIntExtra("GROUP_POSITION", 0) == 0)
{
itemListDatabase.insertDataIntoPharmacy(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 1){
itemListDatabase.insertDataIntoSuperShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 2){
itemListDatabase.insertDataIntoStationeryShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 3){
itemListDatabase.insertDataIntoMarket(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 4){
itemListDatabase.insertDataIntoHotel(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 5){
itemListDatabase.insertDataIntoHardwareShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 6){
itemListDatabase.insertDataIntoComputerAccessoriesShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
itemListDatabase.close();
break;
case R.id.doneButton:
Intent intent = new Intent(ItemEditorActivity.this, CategoryList.class);
startActivity(intent);
break;
}
}
}
activity_category_list.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="com.remindme.sayem.remindme.CategoryList"
>
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/categoryListView"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:dividerHeight="0.5dp"
android:divider="#7AA410"
/>
</RelativeLayout>
activity_item_editor.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" 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.remindme.sayem.remindme.ItemEditorActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/itemEditorEditText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="Add Data"
android:id="#+id/addDataButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="DONE"
android:id="#+id/doneButton" />
</LinearLayout>
</RelativeLayout>
category_item.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="wrap_content"
android:padding="15dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textAllCaps="false"
android:textColor="#7AA410"
android:text="Large Text"
android:paddingLeft="30dp"
android:id="#+id/categoryItem" />
</LinearLayout>
item_name.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="wrap_content"
android:padding="15dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textAllCaps="false"
android:text="Medium Text"
android:id="#+id/itemName" />
</LinearLayout>
EDIT_CODE
I made this change of categoryListView.setOnGroupClickListener() method inside the CategoryList.java.
categoryListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if(categoryListAdapter.getChildrenCount(groupPosition) == 0){
Intent intent = new Intent(CategoryList.this, ItemEditorActivity.class);
String text = categoryListAdapter.getGroupText(groupPosition);
intent.putExtra("GROUP_POSITION", text);
Toast.makeText(CategoryList.this, "Group Position: " + text, Toast.LENGTH_LONG).show();
startActivity(intent);
}
return false;
}
});
Also I added a new function getGroupText() in the CategoryListAdapter class inside the CategoryList.java.
public String getGroupText(int groupPosition){
return this._listDataHeader.get(groupPosition).toString();
}
After that I edited the ItemEditorActivity.java like this.
package com.remindme.sayem.remindme;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ItemEditorActivity extends AppCompatActivity implements View.OnClickListener{
EditText itemEditorEditText;
Button doneButton;
Button addDataButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_editor);
itemEditorEditText = (EditText) findViewById(R.id.itemEditorEditText);
doneButton = (Button) findViewById(R.id.doneButton);
addDataButton = (Button) findViewById(R.id.addDataButton);
addDataButton.setOnClickListener(this);
doneButton.setOnClickListener(this);
}
#Override
protected void onPause() {
super.onPause();
finish();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addDataButton:
ItemListDatabase itemListDatabase = new ItemListDatabase(this);
String itemEditorString = itemEditorEditText.getText().toString();
ItemNameClass itemNameClass = new ItemNameClass(itemEditorString);
String group_position = getIntent().getStringExtra("GROUP_POSITION");
if (group_position.equals("Pharmacy"))
{
itemListDatabase.insertDataIntoPharmacy(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Super Shop")) {
itemListDatabase.insertDataIntoSuperShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Stationery Shop")) {
itemListDatabase.insertDataIntoStationeryShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Market")) {
itemListDatabase.insertDataIntoMarket(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Hotel")) {
itemListDatabase.insertDataIntoHotel(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Hardware Shop")) {
itemListDatabase.insertDataIntoHardwareShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Computer Accessories Shop")){
itemListDatabase.insertDataIntoComputerAccessoriesShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
break;
case R.id.doneButton:
Intent intent = new Intent(ItemEditorActivity.this, CategoryList.class);
startActivity(intent);
break;
}
}
}
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?
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.