Displaying a selected row from a spinner - android

The app i'm making displays user input before saving it. One of the spinners gets data from a database. When i press the "review" button my app crashes (something about a NullPointException) on this line
final String estStatus = estType[row];
Here is the code.
private void displayReviewDetails() {
// Get what the user entered
Spinner estSpinner = (Spinner) findViewById (R.id.est_spinner);
Spinner spinner = (Spinner) findViewById (R.id.ratingSpinner);
EditText mealCost = (EditText) findViewById (R.id.editTextMealCost);
EditText mealType = (EditText) findViewById (R.id.editTextMealType);
EditText comments = (EditText) findViewById (R.id.editTextComments);
DatePicker rDate = (DatePicker) findViewById (R.id.datePicker1);
// final so we can reference them in the anonymous inner class below
int row = estSpinner.getSelectedItemPosition();
final String estStatus = estType[row];
int row1 = spinner.getSelectedItemPosition();
final String ratingStatus = estRating[row1];
final String strMealCost = mealCost.getText().toString();
final String strMealType = mealType.getText().toString();
final String strComments = comments.getText().toString();
final String rateDate = rDate.getDayOfMonth() + "/"
+ (rDate.getMonth() + 1) + "/" + rDate.getYear();
// Create and display the Alert dialog
new AlertDialog.Builder(this)
.setTitle("Details entered")
.setMessage(
"\n " + estStatus +
"\n " + ratingStatus +
"\n " + strMealCost +
"\n " + strMealType +
"\n " + strComments +
"\n " + rateDate )
.setNeutralButton("Back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing - it will just close when clicked
}
})
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// save the details entered if "Save" button clicked
saveReviews(estStatus, ratingStatus, strMealCost, strMealType,
strComments, rateDate);
}
}).show();

You can also use getSelectedItem().toString();

Related

AlertDialog not loading

I have a ListView and i have put an onClickListener to it. When i click it, it is supposed to run an AlertDialog but it does not seem to work. The AlertDialog is supposed to display a few strings which are in the ListView. here is the code I am using.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
PopUpAlert(id);
}
});
private void PopUpAlert(final long id) {
Cursor cursor = dbHelper.getAllReviewRows(id);
if (cursor.moveToFirst()) {
//Preparing variables to use in message from Establishment record in Database
final String SName = cursor.getString(dbHelper.COL_REV_STATION_NAME);
String Date = cursor.getString(SQL.COL_DATE);
String SFacility = cursor.getString(SQL.COL_REV_FACILITY);
String Rating = cursor.getString(SQL.COL_RATING);
String Comment = cursor.getString(SQL.COL_COMMENTS);
// building a drill down information message and displaying it in an Alert Dialog
new AlertDialog.Builder(this)
.setTitle("Facilities Review App")
.setMessage("You Selected:\n"
+ "Station Name: " + SName + "\n" + "Date: " + Date
+ "\n" + "Facility: " + SFacility + "\n" + "Rating: " + Rating
+ "\n" + "Comment: " + Comment)
.setPositiveButton("Add Image", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// calling method to add a review for that particular establishment
addImage(SName);
}
})
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// calling method to delete that particular establishment
}
});
}
}
you didn't call show() on your AlertDialog:
new AlertDialog.Builder(this)
.setTitle("Facilities Review App")
.setMessage("...")
.setPositiveButton(..)
.setNegativeButton(..)
.show();
Here you can find the documentation for AlertDialog.Builder.show()

Listview is not getting updated with notifyDataSetChanged method

I am trying to update my listview with notifyDataSetChanged() this method, but listview is not getting updated, if i press back button and go to previous activity and then again if i come in this activity then it is getting updated, i don't know why. I tried all possible solution but not getting proper solution. Please help Below is my code.
Here is a link which i tried
ListView not getting updated on calling notifyDataSetChanged()
notifyDataSetChanged() not working
notifyDataSetChanged Android ListView
notifyDataSetChanged not updating ListView
The event of notifyDataSetChanged()
public class Assignment extends Activity {
ListView mListView;
ImageView imageViewCrtAsnm;
String[] stg1;
List<String[]> names2 = null;
DataManipulator dataManipulator;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment);
imageViewCrtAsnm = (ImageView) findViewById(R.id.createassignment);
mListView = (ListView) findViewById(R.id.displaydata);
imageViewCrtAsnm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Assignment.this,
Assignment_Create.class);
startActivity(intent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Assignment.this);
alertDialogBuilder.setTitle("Delete Data");
alertDialogBuilder
.setMessage("Click yes to Delete Record!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
String[] delete = names2.get(position);
String idString = delete[0];
long idLong = Long.valueOf(idString);
Log.d("Deleting...", idLong + "");
dataManipulator.delete(idLong);
names2.remove(position);
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n"
+ "Descr : " + name[2]
+ "\n" + "Day's Left : "
+ name[3];
stg1[x] = stg;
x++;
}
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
dataManipulator = new DataManipulator(this);
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n" + "Descr : " + name[2] + "\n"
+ "Day's Left : " + name[3];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stg1);
mListView.setAdapter(new ArrayAdapter<String>(this, R.layout.check,
stg1));
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
ArrayAdapter makes a copy of your items that you pass to it in the constructor and uses that internally.
ArrayAdapter Source
So simply manipulating your original array means nothing to the adapter. You are notifying it that the data has changed when it has not changed at all, it still holds the original list you populated it with.
You need to either recreate the entire adpater again or use the clear, addAll, remove or insert methods to manipulate the data.
http://developer.android.com/reference/android/widget/ArrayAdapter.html
You are recreating your array when you remove data. Have you tried also recreating your adapter to use the new array?
I found solution for this.
Just use onResume method to call adapter class...
#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 = "Title : " + name[1] + "\n" + "Descr : " + name[2] + "\n"
+ "Day's Left : " + name[3];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this, R.layout.assignment_custom,
stg1);
mListView.setAdapter(adapter);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setBackgroundResource(R.drawable.assignment_icon);
adapter.notifyDataSetChanged();
adapter.setNotifyOnChange(false);
mListView.invalidateViews();
}
Just call this part of code in onResume method and you are done. But anyway thanks to all who have helped me. i am posting this answer here so may be other's can take benefit and not waste time like i did.

store an EditText value into SQLite database line by line

i made an EditText that displayed value with multiple line like this...
i want to keep that value in a SQLite database. this is the code i use:
export.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final View export_layout = getLayoutInflater().inflate(R.layout.export_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setView(export_layout);
builder.setTitle("Input new DB");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
editText1 = (EditText) export_layout.findViewById(R.id.editText1);
String table = editText1.getText().toString();
String val = textStatus.getText().toString();
db.execSQL("create table "+table+"(ANY text)");
db.execSQL("insert into "+table+" values('"+val+"')");
}
});
builder.setNegativeButton("back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
TextStatus is an EditText where the value is displayed like the image above. editText1 is where the user input the table name.
the problem is when i save the value, the whole value is inserted into one cell. i want the value to be separated per line then inserted into a single cell for each line.
is there any way to do that?
edit:
this is how i set the text in TextStatus:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (size > 0) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String bssid = scanresult.BSSID;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + bssid + "," + rssiString + "\n");
}
unregisterReceiver(x); //stops the continuous scan
textStatus.append("------------"+j+"\n");
j++;
}
}
};
Try Scanner:
Scanner scanner = new Scanner(val);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Insert the line here
}
Update: This is how it should looks like in your codes
editText1 = (EditText) export_layout.findViewById(R.id.editText1);
String table = editText1.getText().toString();
String val = textStatus.getText().toString();
db.execSQL("create table "+table+"(ANY text)");
Scanner scanner = new Scanner(val);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
db.execSQL("insert into "+table+" values('"+line+"')");
}

Retrieving values from input texts android

I am trying to retrieve the values from the edit text input boxes and store them in a database. I am getting a null pointer exception and I am not sure why. Thanks in advance for the help :)
This is my code where I am retrieving the values and passing them as parameters to be stored in the database:
public class MyPage extends Activity {
final Context context = this;
public String stringName;
public int intAge;
public int intWeight;
public int intHeight;
public String stringGoal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_page);
final Button button = (Button) findViewById(R.id.btn_addInfo);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialogue_userinfo);
dialog.setTitle("Add Your Information");
Button dialogButton = (Button) dialog.findViewById(R.id.btnDone);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText textName = (EditText)findViewById(R.id.txtName);
stringName = textName.getText().toString();
EditText textAge = (EditText)findViewById(R.id.txtAge);
intAge = Integer.parseInt(textAge.getText().toString());
EditText textWeight = (EditText)findViewById(R.id.txtWeight);
intWeight = Integer.parseInt(textWeight.getText().toString());
EditText textHeight = (EditText)findViewById(R.id.txtHeight);
intHeight = Integer.parseInt(textHeight.getText().toString());
EditText textGoal = (EditText)findViewById(R.id.txtGoal);
stringGoal = textGoal.getText().toString();
DatabaseAccess();
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
}
});
}
private void DatabaseAccess(){
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting User
Log.d("Insert: ", "Inserting ..");
db.addUser(new User(stringName, intAge, intWeight, intHeight, stringGoal));
//db.addUser(new User("Peter Parker", 23, 50, 150, "Hi"));
// Reading all users
Log.d("Reading: ", "Reading all contacts..");
List<User> users = db.getAllUsers();
for (User us : users) {
String log = "Id: "+us.getId()+" ,Name: " + us.getName() + " ,Age: " + us.getAge()
+ " ,Weight: " + us.getWeight() + " ,Height: " + us.getHeight()
+ " ,Goal: " + us.getGoal()
+ " ,BMI: " + us.getBmi();
Log.d("Name: ", log);
}
}
}
if All EditText's inside Dialog dialogue_userinfo layout then use Dialog instance for initializing EditText's instances on Button click. do it as:
EditText textName = (EditText)dialog.findViewById(R.id.txtName);
stringName = textName.getText().toString();
EditText textAge = (EditText)dialog.findViewById(R.id.txtAge);
intAge = Integer.parseInt(textAge.getText().toString());
//....same for others...
getText will return Editable Object. If your edittext has no any characters, it maybe return the null Object. So you have to check whether getText() return a null object.
if(youreditView.getText() != null ) {
String content = youreditView.getText().toString();
}

Deleting items on listview together with the database [ANDROID]

I have have checked every problem here in relation to my own. The codes are totally different in the one I'm using IMHO. I have coded everything up to this point. I've read that in deleting the data in the database is just by passing the position, the problem is the auto-generated id in the database is not the same with the position being passed. All I'm trying to achieve is after deleting the item in list view, the item in the database will also be deleted.
The code from database in getting all the data:
public ArrayList<String> getData() {
String[] columns = new String[] { KEY_ID, KEY_CLIENT_NAME,
KEY_PRODUCT_NAME, KEY_SUPPLIER_PRICE, KEY_BS_PRICE, KEY_QTY,
KEY_TOTAL_AMOUNT };
Cursor c = sql.query(DB_TABLE, columns, null, null, null, null, null);
ArrayList<String> result = new ArrayList<String>();
int id = c.getColumnIndex(KEY_ID);
int cName = c.getColumnIndex(KEY_CLIENT_NAME);
int pName = c.getColumnIndex(KEY_PRODUCT_NAME);
int suppPrice = c.getColumnIndex(KEY_SUPPLIER_PRICE);
int bsPrice = c.getColumnIndex(KEY_BS_PRICE);
int qty = c.getColumnIndex(KEY_QTY);
int totalAmount = c.getColumnIndex(KEY_TOTAL_AMOUNT);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result.add("ID: " + c.getInt(id) + "\n" + "CLIENT NAME: "
+ c.getString(cName) + "\n" + "PRODUCT NAME: "
+ c.getString(pName) + "\n" + "SUPPLIER PRICE: "
+ c.getString(suppPrice) + "\n" + "RETAIL PRICE: "
+ c.getString(bsPrice) + "\n" + "QUANTITIY: "
+ c.getString(qty) + "\n" + "TOTAL: "
+ c.getString(totalAmount) + "\n");
}
return result;
}
The code in retrieving the data:
sql = new SQLDatabase(this);
sql.open();
ArrayList<String> data = sql.getData();
sql.close();
The code the the deletion should be executed:
protected void onListItemClick(View view, int position, long id) {
Log.i("TAG", "onListItemClick id=" + position + id);
AlertDialog.Builder builder = new AlertDialog.Builder( Delete.this);
builder.setMessage("WHAT DO YOU WANT TO DO?");
builder.setNegativeButton("DELETE", new
DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int which) { }
// DELETE CODE HERE
});
builder.setNeutralButton("CANCEL", new
DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int which) { }
// DO NOTHING
});
builder.setCancelable(false); AlertDialog alertdialog =
builder.create(); alertdialog.show();
}
Add Tag to the column you inserted and use same tag value while delete operation in both list and DB.

Categories

Resources