Not getting Text from EditText in custom Alert Builder View Layout - java

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);

Related

Press enter button in keyboard should redirect to OK button in AlertDialog

I'm trying to create a application where a code gets added to a custom array list.
User enters the code while clicking plus icon.
I need to restrict the user to a single line
I tried to use android:maxLines="1 but it still doesn't work when I press enter.
My question is how do I redirect ENTER button to the AlertDialog's OK button
Here is my Main Activity:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Boolean itIsEmpty = Boolean.FALSE;
EditText editText;
private static final String TAG = "Main Activity";
ArrayList<CodeId> codeArray = new ArrayList<>();
CodeIdListAdapter arrayAdapter;
public void addCodeReal(){
CodeId newCodeId = new CodeId(editText.getText().toString());
codeArray.add(newCodeId);
arrayAdapter.notifyDataSetChanged();
saveData();
Log.d(TAG, "onClick: " + newCodeId.toString());
}
public void addCode (View view){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter code to add").setMessage("Search below to find and add the code");
final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog,null);
builder.setView(customLayout);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
editText = customLayout.findViewById(R.id.editText);
editText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getAction() == KeyEvent.KEYCODE_ENTER)){
if (editText.getText().toString() == ""){
return false;
}else{
addCodeReal();
}
}
return false;
}
});
addCodeReal();
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(codeArray);
editor.putString("task list", json);
editor.apply();
Log.d(TAG, "saveData: " + codeArray.size());
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<CodeId>>() {}.getType();
ArrayList<CodeId> mCodeArray;
mCodeArray = gson.fromJson(json, type);
if (mCodeArray == null) {
mCodeArray = new ArrayList<>();
}
for(int i = 0; i< mCodeArray.size();i++){
Log.d(TAG, "loadData: " + mCodeArray.get(i));
codeArray.add(mCodeArray.get(i));
arrayAdapter.notifyDataSetChanged();
}
Log.d(TAG, "loadData: " + codeArray.size());
}
private void deleteData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
sharedPreferences.getString("task list", null);
Editor prefsEditor = sharedPreferences.edit();
prefsEditor.remove("task list");
while(itIsEmpty){
int i = 0;
i++;
if(prefsEditor.equals(null)){
Log.d(TAG, "deleteData: if part" + codeArray.get(i));
itIsEmpty = Boolean.TRUE;
}else{
Log.d(TAG, "deleteData: else part" + codeArray.get(i));
prefsEditor.remove("task list");
}
}
prefsEditor.commit();
Log.d(TAG, "deleteData: after clear");
codeArray.clear();
Log.d(TAG, "deleteData: before clear");
arrayAdapter.notifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
Toolbar toolbar = findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, login_activity.class));
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).apply();
arrayAdapter = new CodeIdListAdapter(this,codeArray);
//ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1, codeList);
listView.setAdapter(arrayAdapter);
Log.d(TAG, "onCreate: loadData func working");
loadData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.front_page_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.action_del:
deleteData();
Toast.makeText(this, "Cleared!", Toast.LENGTH_SHORT).show();
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is my activity_main.xml
<?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=".MainActivity">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton3"
android:layout_width="109dp"
android:layout_height="58dp"
android:layout_marginStart="286dp"
android:layout_marginTop="596dp"
android:layout_marginEnd="11dp"
android:layout_marginBottom="25dp"
android:clickable="true"
android:onClick="addCode"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.33"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.19"
app:srcCompat="#android:drawable/ic_input_add" />
<ListView
android:id="#+id/listView"
android:layout_width="368dp"
android:layout_height="613dp"
android:layout_marginTop="39dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_main"
android:layout_width="411dp"
android:layout_height="51dp"
android:layout_marginBottom="21dp"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintBottom_toTopOf="#+id/listView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

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"

my UI isn't working (buttons)

I have an app and all of a sudden my user interface stopped working the share button works and also the options menu but for some odd reason my buttons stopped working they don't click or do anything . is it due to possibly the extending of my OptionsMenu class ? I have no idea why ? Does this happen often I tries to freshly build my project but no use . I have my MainActivity Class here
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.Button;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.EditText;
import android.widget.AdapterView;
import android.widget.TextView;
import java.io.*;
import android.content.*;
import android.view.*;
import android.media.*;
import javax.security.auth.*;
import android.util.*;
import android.widget.AdapterView.*;
import java.net.*;
import org.apache.http.util.*;
import android.webkit.*;
import java.text.*;
import android.graphics.*;
import android.widget.TextView.*;
import android.text.*;
import android.widget.ActionMenuView.*;
import android.view.MenuItem.*;
import android.widget.*;
import android.content.Intent;
import android.net.*;
import java.util.*;
import java.nio.channels.*;
import java.nio.*;
import android.*;
public class MainActivity extends OptionsMenu
{
private MusicPlayer musicPlayer;
private String pos = "";
private FileManager fm;
private BlueTheme BlueTheme;
private PinkTheme PinkTheme;
private Downloader downloader;
private EditTextCustomizable etc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
musicPlayer = new MusicPlayer(new MediaPlayer());
fm = new FileManager(this,this);
BlueTheme = new BlueTheme(this,this ,fm);
PinkTheme = new PinkTheme(this,this,fm);
etc = new EditTextCustomizable(this , BlueTheme , PinkTheme);
etc.customize();
Button rewind = (Button)findViewById(R.id.rewind);
rewind.setText("<");
Button fwd = (Button)findViewById(R.id.fwd);
fwd.setText(">");
ListView downloadsList = (ListView) findViewById(R.id.downloads);
downloadsList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3){
ListView downloadsList = (ListView) findViewById(R.id.downloads);
pos = downloadsList.getItemAtPosition(position).toString();
musicPlayer.InitPlay(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/" + pos);
}});
}
public void Play(View view){
musicPlayer.Play();
EditText search = (EditText)findViewById(R.id.search);
musicPlayer.SearchResult(search.getText().toString());
}
public void Pause(View view){
musicPlayer.Pause();
}
public void Stop(View view){
musicPlayer.Stop();
}
public void Rewind(View view){
musicPlayer.Rewind();
}
public void Fwd(View view){
musicPlayer.Fwd();
}
public void onDownloadClick(View view){
EditText bar = (EditText)findViewById(R.id.search);
String downloadFile = bar.getText().toString();
downloader.DownloadURL(downloadFile);
}
}
And here is the OptionsMenu class where I am extending Activity note that I am not using AppCompatActivity .
package com.mycompany.myapp;
import android.view.*;
import android.app.*;
import android.net.*;
import java.util.*;
import android.widget.ListView;
import android.content.*;
import java.io.*;
import android.widget.*;
import android.*;
public class OptionsMenu extends Activity
{
private MusicPlayer musicPlayer;
private FileManager fm;
private BlueTheme blueTheme;
private PinkTheme pinkTheme;
private final int blue = Menu.FIRST;
private final int pink = blue + 1;
private int items = 0;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
fm = new FileManager(this,this);
blueTheme = new BlueTheme(this,this,fm);
pinkTheme = new PinkTheme(this,this,fm);
fm.ListFiles();
menu.clear();
MenuInflater inflator = getMenuInflater();
inflator.inflate(R.menu.sidebar_menu, menu);
SubMenu subMenu = menu.addSubMenu("Themes");
subMenu.add(0 , blue , 0 , "Blue");
subMenu.add(0, pink , 1, "Pink");
items = subMenu.getItem().getItemId();
// tool bar menu
ArrayList<Uri> al = new ArrayList<Uri>();
ArrayList<Uri> emailAl = new ArrayList<Uri>();
MenuItem mi = menu.findItem(R.id.searchable);
MenuItem share = menu.findItem(R.id.share);
mi.setIcon(android.R.drawable.ic_search_category_default);
SearchView searchView = (SearchView) menu.findItem(R.id.searchable).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
ShareActionProvider sap = (ShareActionProvider) share.getActionProvider();
Intent intentShare = new Intent(Intent.ACTION_SEND_MULTIPLE);
Intent intentEmail = new Intent(Intent.ACTION_SEND_MULTIPLE);
intentShare.setType("audio/mp3");
intentEmail.setType("audio/mp3");
Uri uri = null;
Uri uriEmail = null;
//FileInputStream in = null;
//FileOutputStream out = null;
//try{
// for(File file : downloads){
// uri = Uri.fromFile(file);
// in = new FileInputStream(file);
// File outFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), file.getName()); // IMPORTANT! You need to create your file object separately, so you can then pass it to intent as well..
// out = new FileOutputStream(outFile);
// byte[] buf = new byte[1024];
// int len;
// while ( (len = in.read(buf, 0, buf.length)) != -1){
// out.write(buf, 0, len);
// }
// in.close();
// out.flush();
// out.close();
// uriEmail = Uri.fromFile(outFile); // Here you passed the parent directory file.. Pass newly created file object ..
// al.add(uri);
// emailAl.add(uriEmail);
// }
// } catch(IOException e){
// e.printStackTrace();
// }
//for(File file : fm.GetDownloadFiles()){
// uriEmail = Uri.fromFile(fm.exportFile(file));
//}
emailAl.add(uriEmail);
intentShare.putParcelableArrayListExtra(Intent.EXTRA_STREAM,al );
intentEmail.putParcelableArrayListExtra(Intent.EXTRA_STREAM,emailAl);
intentEmail.putExtra(Intent.EXTRA_SUBJECT , "Subject");
intentEmail.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sap.setShareIntent(intentShare);
sap.setShareIntent(intentEmail);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId()){
case R.id.playlist:
break;
case blue:
blueTheme.Blue();
break;
case pink:
pinkTheme.Pink();
break;
case R.id.muteoption:
musicPlayer.MuteVolume();
break;
case R.id.unmuteoption:
musicPlayer.UnMuteVolume();
break;
default:
return super.onOptionsItemSelected(item);
// TODO: Implement this method
}
return super.onOptionsItemSelected(item);
}
}
I can post up more code if requested. And will reedit if not clear enough thank you
EDITED
Here is the layout XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="4dp"
android:showAsAction="always"
android:windowActionBar="false"
android:theme="#android:style/Theme.Holo.Light"
/>
<TextView
android:id="#+id/downloadsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/downloadButton"
android:text="#string/downloadButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:onClick="onDownloadClick"
/>
<EditText
android:id="#+id/search"
android:hint="Do something"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="#id/downloadButton"
android:background="#android:color/transparent"
android:paddingBottom="20dp"
android:paddingTop="20dp"/>
<Button
android:id="#+id/pause"
android:text="#string/pause"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="Pause"
android:layout_centerInParent="true"
android:layout_below="#id/search"
/>
<Button
android:id="#+id/play"
android:text="#string/play"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="Play"
android:layout_toRightOf="#id/pause"
android:layout_below="#id/search"/>
<Button
android:id="#+id/stop"
android:text="#string/stop"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="Stop"
android:layout_toLeftOf="#id/pause"
android:layout_below="#id/search"/>
<Button
android:id="#+id/rewind"
android:text="#string/rewind"
android:layout_height="wrap_content"
android:layout_width="50dp"
android:onClick="Rewind"
android:layout_toLeftOf="#id/stop"
android:layout_below="#id/search"/>
<Button
android:id="#+id/fwd"
android:text="#string/fwd"
android:layout_height="wrap_content"
android:layout_width="50dp"
android:onClick="Fwd"
android:layout_toRightOf="#id/play"
android:layout_below="#id/search"/>
<ListView
android:id="#+id/downloads"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/rewind"
/>
</RelativeLayout>
Paste your layout xml if possible. I guess it's caused by something (maybe some parent view) interrupted the focus, so the child view button can't get focus.

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?

data is not visible in listview

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.

Categories