how to set textview inside dialog box on item click - android

Here is my code, that I am trying to do since last two days. All I can see is the listView in mainActivity and when the listitem is clicked a alertdialog box appears without any datas from database in textView. I think Cursor cursor is not working, that is why I cannot reach to my goal. Could anyone suggest me some good solution for this problem? Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creating a main list view
final ArrayList<String> getTrainingsList = new ArrayList<String>();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getTrainingsList);
ListView mylist = (ListView) findViewById(R.id.traininglistView);
mylist.setAdapter(adapter);
String Path = DB_PATH + DB_NAME;
//opening an existing database
final SQLiteDatabase db = SQLiteDatabase.openDatabase(Path, null, 0);
final String selectQuery = "SELECT * FROM training";
//Getting a cursor to fetch data from the database
final Cursor c = db.rawQuery(selectQuery, null);
Log.d("TAG","cursor found");
c.moveToFirst();
Log.d("TAG","Cursor moved to first");
if(c !=null){
//If there are contents in the database,
//then c!=null, so using do-while loop access data in database
do{
String title = c.getString(c.getColumnIndex("title"));
//String description = c.getString(c.getColumnIndex("description"));
//String title_date = title+":"+date;
getTrainingsList.add(title);
c.moveToNext();
}while(!c.isAfterLast());
//update the list
adapter.notifyDataSetChanged();
//closing the database after use
//db.close();
}
//Below is the code to alert alert dialogue window on item clicked
final TextView view1 = (TextView)findViewById(R.id.dialogTextView);
Cursor cursor = db.query(TABLE_TRAINING, new String[] { TRAINING_ID,
TRAINING_TITLE, TRAINING_DESCRIPTION, TRAINING_DATE, TRAINING_LOCATION },
TRAINING_ID + "=?",
new String[] { String.valueOf(TRAINING_ID) }, null, null, null, null);
Log.d("TAG","cursor found again");
if(cursor.getCount() > 0) {
cursor.moveToFirst();
String title = cursor.getString(cursor.getColumnIndex("title"));
String description = cursor.getString(cursor.getColumnIndex("description"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String location = cursor.getString(cursor.getColumnIndex("location"));
String allinfos = title+"\n"+description+"\n"+date+"\n"+location;
view1.setText(allinfos);
Log.d("TAG","Successfully set");
}
mylist.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long _id) {
AlertDialog.Builder b= new AlertDialog.Builder(MainActivity.this);
b.setTitle("Title");
b.setView(view1);
b.setPositiveButton("Proceed to training", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(MainActivity.this, TraineeActivity.class));
}
});
b.setNegativeButton("Back to List", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alertDialog = b.create();
alertDialog.show();
}
});
}`

Try to create a new textview instead of finding it in your activity layout.
That textView is already added to your layout maybe because of that you are not able to add it to your dialog
Try this:
//Below is the code to alert alert dialogue window on item clicked
final TextView view1 = new TextView(this);
Cursor cursor = db.query(TABLE_TRAINING, new String[] { TRAINING_ID,
TRAINING_TITLE, TRAINING_DESCRIPTION, TRAINING_DATE, TRAINING_LOCATION },
TRAINING_ID + "=?",
new String[] { String.valueOf(TRAINING_ID) }, null, null, null, null);
Log.d("TAG","cursor found again");
if(cursor.getCount() > 0) {
cursor.moveToFirst();
String title = cursor.getString(cursor.getColumnIndex("title"));
String description = cursor.getString(cursor.getColumnIndex("description"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String location = cursor.getString(cursor.getColumnIndex("location"));
String allinfos = title+"\n"+description+"\n"+date+"\n"+location;
view1.setText(allinfos);
Log.d("TAG","Successfully set");
}
mylist.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long _id) {
AlertDialog.Builder b= new AlertDialog.Builder(MainActivity.this);
b.setTitle("Title");
b.setView(view1);
b.setPositiveButton("Proceed to training", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(MainActivity.this, TraineeActivity.class));
}
});
b.setNegativeButton("Back to List", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alertDialog = b.create();
alertDialog.show();
}
});

You have to set the text after the dialog has been created and after calling alertDialog.show().

Related

when mesg box exits it returns to prevoius activyty

I got code from stack overflow to bring up a mesg box.
When I call up a mesga box in activty ActGetKey, it goes back to the starting acticty MainActivity, after the exit button is pressed.
mesg box code:
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
code for MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
keyDB db;
db = new keyDB(this);
db.setUp();
cPassKey mPassKey = new cPassKey("mysec","mypublic","myphase");
db.updateExchange("ted2", mPassKey);
Cursor cursor =db.selectKey("ted2");
// get keys in current pos of database
cPassKey mret=db.loadRecord(cursor);
String name;
Cursor test =db.selectKey("ted1");
name = test.getString(2);
name = test.getString(3);
cursor = db.selectRecords();
int id; String ted;
if (cursor != null)
{
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
} while (cursor.moveToNext());
cursor.close();
}
}
public void sendMessage(View view) {
// Intent intent = new Intent(this, ActGetKey.class);
Intent intent = new Intent(this, ActGetKey.class);
startActivity(intent);
}
}
code for ActGetKey Activity
public class ActGetKey extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String selItem=null;
long d=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_get_key);
keyDB db;
db= new keyDB(this);
Cursor cursor=db.selectRecords();
String ted="na";
int id=0;
if (cursor != null) {
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
// fill up spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
if (cursor != null) {
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
categories.add(ted);
} while (cursor.moveToNext());
cursor.close();
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// set selected item
spinner.setSelection(0);
}
}
public void Update3(View view)
{
d++;
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey=(String)temp.getText().toString();
if (isValidString(strPublicKey))
{
msbox( getString(R.string.badtext), "Text for publick key is invalid");
return;
}
temp = findViewById(R.id.publicKey);
String strPrivetKey=(String)temp.getText().toString();
temp = findViewById(R.id.publicKey);
String strKeyPhrase=(String)temp.getText().toString();
// check for bad dada
}
boolean isValidString( String test)
{
if (test==null)
return false;
return true;
}
public void Update2(View view) {
// put keys in keyclass
msbox("kkk","kjjh");
if (true)
return;
keyDB db;
db= new keyDB(this);
cPassKey mPassKey = getKeys();
db.updateExchange(selItem, mPassKey);
// pus keyclass in data base
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
selItem = parent.getItemAtPosition(position).toString();
keyDB db;
db= new keyDB(this);
Cursor cursor =db.selectKey(selItem);
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
boolean loadKeys(cPassKey mPassKey)
{
EditText temp;
temp = findViewById(R.id.publicKey);
temp.setText(mPassKey.publickKey);
temp = findViewById(R.id.secretKey);
temp.setText(mPassKey.secretKey);
temp = findViewById(R.id.phraseKey);
temp.setText(mPassKey.phraseKey);
return true;
}
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
cPassKey getKeys()
{
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey= temp.getText().toString();
temp = findViewById(R.id.secretKey);
String StrSecretKey= temp.getText().toString();
temp = findViewById(R.id.phraseKey);
String StrPhraseKey= temp.getText().toString();
cPassKey mPassKey = new
cPassKey( StrSecretKey,strPublicKey, StrPhraseKey);
return mPassKey;
}
}
public class ActGetKey extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String selItem=null;
long d=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_get_key);
keyDB db;
db= new keyDB(this);
Cursor cursor=db.selectRecords();
String ted="na";
int id=0;
if (cursor != null) {
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
// fill up spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
if (cursor != null) {
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
categories.add(ted);
} while (cursor.moveToNext());
cursor.close();
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// set selected item
spinner.setSelection(0);
}
}
public void Update3(View view)
{
d++;
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey=(String)temp.getText().toString();
if (isValidString(strPublicKey))
{
msbox( getString(R.string.badtext), "Text for publick key is invalid");
return;
}
temp = findViewById(R.id.publicKey);
String strPrivetKey=(String)temp.getText().toString();
temp = findViewById(R.id.publicKey);
String strKeyPhrase=(String)temp.getText().toString();
// check for bad dada
}
boolean isValidString( String test)
{
if (test==null)
return false;
return true;
}
public void Update2(View view) {
// put keys in keyclass
msbox("kkk","kjjh");
if (true)
return;
keyDB db;
db= new keyDB(this);
cPassKey mPassKey = getKeys();
db.updateExchange(selItem, mPassKey);
// pus keyclass in data base
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
selItem = parent.getItemAtPosition(position).toString();
keyDB db;
db= new keyDB(this);
Cursor cursor =db.selectKey(selItem);
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
boolean loadKeys(cPassKey mPassKey)
{
EditText temp;
temp = findViewById(R.id.publicKey);
temp.setText(mPassKey.publickKey);
temp = findViewById(R.id.secretKey);
temp.setText(mPassKey.secretKey);
temp = findViewById(R.id.phraseKey);
temp.setText(mPassKey.phraseKey);
return true;
}
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
cPassKey getKeys()
{
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey= temp.getText().toString();
temp = findViewById(R.id.secretKey);
String StrSecretKey= temp.getText().toString();
temp = findViewById(R.id.phraseKey);
String StrPhraseKey= temp.getText().toString();
cPassKey mPassKey = new
cPassKey( StrSecretKey,strPublicKey, StrPhraseKey);
return mPassKey;
}
}
That is because of the finish() method inside the onClickListener. Finish() doesn't cancel the dialog, it finishes the activity. Use dismiss() if you are trying to hide the dialog

Android - How to refresh dynamically listview after adding/deleting items from database

I'm new in Android. I have the same problem as described here...I am trying to manage a simple list in an Android application. The contents of the list are maintained in a SQLite database. When the user selects and holds on a specific row, a context menu appears with a "Open/Delete" option. When they select "Delete", the row is deleted from the database, but the view does not refresh. When I back out of the application and get back in, the appropriate row has been removed. So, I know the row is deleted, it's just the ListView that doesn't refresh. The same with adding new item to the database. I searched solution, but not yet find. Appreciate any help.
Activity class:
public class ProjectsActivity extends Activity {
private RMProject rmProject = null;
private RMProjectDBHelper projectDBHelper = null;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rmProject = new RMProject();
projectDBHelper = new RMProjectDBHelper(this);
final ListView lv = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<>(this, R.layout.list_item, getProjectNames());
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProjectsActivity.this);
builder.setTitle("What to do with project?");
builder.setPositiveButton("Open", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ProjectsActivity.this, OpenProjectActivity.class);
//todo: send project information as parameter
startActivity(intent);
}
});
//**!!!Here I delete project item from database!!!**
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selected = ((TextView) view.findViewById(R.id.list_textView)).getText().toString();
int projId = projectDBHelper.findIdByName(selected);
projectDBHelper.deleteProject(projId);
Toast toast=Toast.makeText(getApplicationContext(), "Project "+selected+" deleted", Toast.LENGTH_SHORT);
toast.show();
//**call getProjectNames and notifydataSetChanged**
getProjectNames();
adapter.notifyDataSetChanged();
}
});
builder.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_item) {
final Dialog dialog = new Dialog(ProjectsActivity.this);
dialog.setContentView(R.layout.add_proj);
dialog.setTitle("Введите название проекта:");
dialog.setCancelable(false);
Button okBtn = (Button) dialog.findViewById(R.id.btn_create_proj);
Button cancelBtn = (Button) dialog.findViewById(R.id.btn_cancel_proj);
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editProjName = (EditText) dialog.findViewById(R.id.edit_proj_name);
String projName = editProjName.getText().toString();
if (rmProject == null) {
rmProject = new RMProject();
}
rmProject.setName(projName);
if (projectDBHelper == null) {
projectDBHelper = new RMProjectDBHelper(ProjectsActivity.this);
}
projectDBHelper.addProject(rmProject);
dialog.dismiss();
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
private String[] getProjectNames() {
LinkedList<RMProject> projects = (LinkedList<RMProject>) projectDBHelper.getAllProjects();
String[] names = new String[projects.size()];
int i = 0;
for (RMProject p : projects) {
names[i++] = p.getName();
}
return names;
}
}
Fragment with custom DbHelper class:
public class RMProjectDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "RM_DB";
private static final String TABLE_PROJECT = "PROJECT";
private static final String[] COLUMNS = {"id_project", "project_name"};
private static final int DB_VERSION = 1;
public RMProjectDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
//.....some code...
public void deleteProject(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PROJECT, "id_project = ?", new String[]{String.valueOf(id)});
db.close();
Log.d("deleteProject with id: ", Integer.toString(id));
}
public int findIdByName(String name){
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT PROJECT.id_project FROM PROJECT WHERE PROJECT.project_name = '"+name+"'";
Cursor cursor = db.rawQuery(selectQuery,null);
int id=-1;
while (cursor.moveToNext()){
id = cursor.getInt(cursor.getColumnIndex("id_project"));
Log.i("LOGGING:"," FIND ID BY NAME: ID="+id);
}
return id;
}
on delete action fetch the data once again and then again call adapter.notifyDataSetChanged it will work

How to update list-view data at run time in android

I have list-view with check-box which loads data from database. And i have a button too, when i press a button spinner is popping up with 2 messages "EDIT" and "DELETE". Delete is working perfectly fine. and if i select Edit option and press OK then Edit-Text is coming in alert window with two button Ok and Cancel.
Now i want that Whatever i enter in edit-text and press Ok button a list-view data which is selected (Checked) should update with new text whatever i have entered in edit-text. So how to achieve this. Please help me. Any help would be appreciated. Thanks in advance.
My code for creating Database:
public class DataManipulatorClass {
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "mydatabaseclass.db";
private static final int DATABASE_VERSION = 1;
static final String TABLE_NAME = "newtableclass";
private static Context context;
static SQLiteDatabase db;
OpenHelper openHelper = null;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME
+ "(classname) values (?)";
public DataManipulatorClass(Context context) {
DataManipulatorClass.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulatorClass.context);
DataManipulatorClass.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulatorClass.db.compileStatement(INSERT);
//this.db = openHelper.getWritableDatabase();
}
public long insert(String classname) {
this.insertStmt.bindString(1, classname);
return this.insertStmt.executeInsert();
}
public void close() {
if (openHelper != null) {
openHelper.close();
}
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME,
new String[] { "id", "classname" }, null, null, null, null,
"classname asc");
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long rowId) {
/** this method deletes by id, the first column in your database */
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY, classname TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
My Activity class:
public class Classes extends Activity implements OnClickListener {
ImageView imageViewNewClass, imageViewDelete;
ListView mListView;
String[] stg1;
List<String[]> names2 = null;
DataManipulatorClass dataManipulator;
ArrayAdapter<CharSequence> adapterSpinner;
ArrayAdapter<String> adapter;
/** Sliding Menu */
boolean alreadyShowing = false;
private int windowWidth;
private Animation animationClasses;
private RelativeLayout classesSlider;
LayoutInflater layoutInflaterClasses;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classes);
imageViewNewClass = (ImageView) findViewById(R.id.newclass);
imageViewDelete = (ImageView) findViewById(R.id.deletemenu);
mListView = (ListView) findViewById(R.id.displaydata);
Display display = getWindowManager().getDefaultDisplay();
windowWidth = display.getWidth();
display.getHeight();
layoutInflaterClasses = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageViewDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
deleteMenuSpinner();
}
private void deleteMenuSpinner() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Classes.this);
final Spinner spinnerDelete = new Spinner(Classes.this);
alertDialog.setView(spinnerDelete);
adapterSpinner = ArrayAdapter.createFromResource(Classes.this,
R.array.delete_menu,
android.R.layout.simple_spinner_item);
adapterSpinner
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDelete.setAdapter(adapterSpinner);
alertDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Delete operation code.....
}
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Classes.this);
final EditText updateClass = new EditText(
Classes.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
updateClass.setLayoutParams(lp);
alertDialogBuilder.setView(updateClass);
alertDialogBuilder
.setTitle("Edit Operation");
alertDialogBuilder
.setMessage("Enter New Class Name")
.setCancelable(false)
.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
}
})
.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder
.create();
alertDialog.show();
}
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
findViewById(R.id.skirrmenu).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!alreadyShowing) {
alreadyShowing = true;
openSlidingMenu();
}
}
});
imageViewNewClass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Classes.this, Class_Create.class);
startActivity(intent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
// Toast.makeText(getApplicationContext(),
// "Listview item clicked", Toast.LENGTH_LONG).show();
SparseBooleanArray sp = mListView.getCheckedItemPositions();
StringBuffer str = new StringBuffer();
for (int i = 0; i < sp.size(); i++) {
if (sp.valueAt(i) == true) {
String s = ((TextView) mListView.getChildAt(i))
.getText().toString();
str = str.append(" " + s);
}
}
Toast.makeText(Classes.this,
"Selected items are " + str.toString(),
Toast.LENGTH_LONG).show();
// Intent intent = new Intent(Classes.this, PlayAudio.class);
// startActivity(intent);
}
});
dataManipulator = new DataManipulatorClass(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Class Name : " + name[1];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this,
R.layout.custom_list_item_multiple_choice, stg1);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setBackgroundResource(R.drawable.assignmentheader);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (dataManipulator != null)
dataManipulator.close();
}
}
You can try to use adapter.notifyDataSetChanged() when OK button pressed. But it will update whole list. If this is what you need, then here is the solution.
To update one list item you can try this:
private void updateView(int index, String updateText){
View v = yourListView.getChildAt(index -
yourListView.getFirstVisiblePosition());
TextView someText = (TextView) v.findViewById(R.id.sometextview);
someText.setText(updateText);
}

Set List Adapter CheckBox and Multi Choice Alert Dialog

I am creating a chat app so I need to implement the broadcast feature, I have placed an AlertDialog within a button of another AlertDialog - so that when the user wants to add contact(s) or select all the contact names from the simple cursor adapter they are returned.
My problem is that when the contacts button is clicked the ListView shows the contact names correctly but when I click both the "Done" or "Select All" buttons, they produce a NullPointerException error instead of the checked names. Please help - thanks in advance.
Code is below for the callBroadcast() function
void callBroadcast()
{
// get broadcast.xml view
LayoutInflater li = LayoutInflater.from(context);
View broadPop = li.inflate(R.layout.broadcast, null);
contacts = (Button) broadPop.findViewById(R.id.contacts);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(broadPop);
final EditText userInput = (EditText) broadPop.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
result.setText(userInput.getText());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// creating an alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// showing
alertDialog.show();
contacts.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
LayoutInflater li = LayoutInflater.from(context);
final View contactList = li.inflate(R.layout.be_sponge_contacts, null);
SimpleCursorAdapter listAdapter;
ListView contact_list = (ListView) findViewById( R.id.contactList );
String[] selectionArgs = null;
String[] projection = new String[]{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+" COLLATE LOCALIZED ASC";
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP+"='"+("1")+"'";
ContentResolver cr = getContentResolver();
final Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
String[] from = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int[] to = new int[] {R.id.rowTextViewChecked};
listAdapter = new SimpleCursorAdapter(Chats.this, R.layout.simplerow_checked, cur, from, to);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setAdapter(listAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
selected = (CheckBox) contactList.findViewById(R.id.rowTextViewChecked);
if (selected.isChecked())
{
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(Chats.this, name+" was chosen", Toast.LENGTH_SHORT).show();
}
}
})
.setNeutralButton("Select All", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
selected = (CheckBox) contactList.findViewById(R.id.rowTextViewChecked);
//setting all to be checked
selected.setChecked(true);
if (selected.isChecked())
{
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(Chats.this, name+" was chosen", Toast.LENGTH_SHORT).show();
selected.setChecked(true);
}
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// creating an alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// showing
alertDialog.show();
}
});
test = (TextView) broadPop.findViewById(R.id.namesChosen);
}

Android dialog box populate from Database

I want to get list of items inside my dialog box form database.
I have "mylist" that is on Mainactivity. When I click one list item, I want the lists of
items inside dialogbox.
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
ArrayList<String> getdialoglist = new ArrayList<String>();
final ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getdialoglist);
ListView dialoglist = (ListView) findViewById(R.id.dialogListView);
dialoglist.setAdapter(adapter1);
String[] sColumns = {"_id", "title","description","date","location","trainer_id"};
final Cursor cursor = db.query("training", sColumns, null, null, null, null, null);
mylist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long _id) {
builder.setTitle("Title");
builder.setCursor(cursor, null, null);
builder.setAdapter(adapter1, null);
builder.create();
builder.show();
}
});
I managed to fetch the list of Items from the pre-populated database and onItemClick appears dialogbox with more information about the items. Hope it might help you :)
public class MainActivity extends Activity{
private ListView trainingListView;
private ListAdapter trainingListAdapter;
private ArrayList<Training> trainingArrayList;
//Lists that contain title of trainings
ArrayList<String> titleList = new ArrayList<String>();
DatabaseHelper helper = new DatabaseHelper(this);
//private static final String DB_PATH = "data/data/com.Areva.areva_attendance/databases/";
final Context context = this;
// Database Name
//private static String DB_NAME = "attendance.sqlite";
private Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trainingListView = (ListView) findViewById(R.id.traininglistView);
trainingArrayList = new ArrayList<Training>();
// Create a list that contains only title of the training
trainingListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getTrainingsList());
trainingListView.setAdapter(trainingListAdapter);
trainingListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long id) {
// arg2 = the id of the item in our view (List/Grid) that we clicked
// arg3 = the id of the item that we have clicked
final Training data = trainingArrayList.get(arg2);
Toast.makeText(getApplicationContext(), "You clicked on position : " + arg2 + " and ID : " + id, Toast.LENGTH_LONG).show();
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(data.getTitle());
TextView description = (TextView) dialog.findViewById(R.id.textView1);
description.setText("Description: "+ data.getDescription());
TextView date = (TextView) dialog.findViewById(R.id.textView2);
date.setText("Date: "+ data.getDate());
TextView location = (TextView) dialog.findViewById(R.id.textView3);
location.setText("Location: "+ data.getLocation());
Button back_btn = (Button) dialog.findViewById(R.id.button1);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
Button start_btn = (Button) dialog.findViewById(R.id.button2);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, TraineeActivity.class);
//intent.putExtra("data",trainingListView.getSelectedItem().toString());
intent.putExtra("trainingId", Training.getId());
intent.putExtra("title", data.getTitle().toString());
MainActivity.this.startActivity(intent);
}
});
dialog.show();
}
});
}
#SuppressWarnings("deprecation")
private ArrayList<String> getTrainingsList() {
//Open database helper Class
DatabaseHelper helper = new DatabaseHelper(this);
// Then we need to get a readable database
SQLiteDatabase db = helper.getReadableDatabase();
//Cursor cursor = db.rawQuery("SELECT t.* FROM training t JOIN attendance a ON t._id=a.training_id=?;",
// new String[] {Integer.toString(training_id)});
final String selectQuery = "SELECT * FROM training";
//Getting a cursor to fetch data from the database
final Cursor cursor = db.rawQuery(selectQuery, null);
startManagingCursor(cursor);
while(cursor.moveToNext()){
Training training = new Training();
training.setId(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.TRAINING_ID)));
training.setTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_TITLE)));
training.setDescription (cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_DESCRIPTION)));
training.setDate(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_DATE)));
training.setLocation(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_LOCATION)));
//String Trainer_id = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_TRAINER_ID));
//Pass to the arraylist
trainingArrayList.add(training);
// But we need a List of String to display in the ListView also.
//That is why we create "titleList"
titleList.add(training.getTitle());
}
return titleList;
}
}

Categories

Resources