Error comming on maketext in toast - java

public void onClick(View v) {
{
if (db==null) db = new DB(AddStation.this);
if(v.getId()==R.id.ADD ) {
String code = Scode.getText().toString().trim();
String name = SName.getText().toString().trim();
String fac = SFac.getText().toString().trim();
if(name.equals("")){
Scode.setError("Invalid name");
return;
}
if (code.equals("")){ Scode.setError("Invalid email");
return;
}
if (db.addStudent(code, name, fac))
Toast.makeText(AddStation.this, "Student added", Toast.LENGTH_SHORT).show();
else if (v.getId()==R.id.See) {
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_LONG).show();
//Log.v("EditText", db.getAllStudents().toString());
}
}
}
db.close();
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_SHORT).show();
}
}
AddStation is my Fragment name. how to solve this ?
this toast is retriving database and can u guys tell me how to bring data into a dropdown box or gridview instead of a toast. thanks!

Look at the last two lines. First you called db.close();, then called db.getAllStudents(), so ARE YOU KIDDING?
But if not this caused error, then post you logcat trace
PS:check your AddStation, is it extended from Activity or its descendants? If not, extend your AddStation from Activity or its descendants.

You can display this data in List/Spinner, for this you had to add these widgets in your layout. You can populate this data as
1. ListView
ListView listView = (ListView) findViewById(R.id.mylist);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item, listRecords);
listView.setAdapter(arrayAdapter);
2. Spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, listRecords);
spinner.setAdapter(arrayAdapter);

Related

Data Won't Save To Shared Preferences

Layout
Hi! So I've been trying to make a basic note app and I've run into a wall. I've spent hours trying to get my data to save to my sharedPreferences, but no matter what I try it doesn't seem to work. I've added logs to the app so we can examine what is happening.
LOGS:
02-22 18:27:56.767 4929-4929/com.example.jackson.collegeplanner I/TEST: notesSet didn't return null!
(When I click the addnote button)
02-22 18:29:54.500 4929-4929/com.example.jackson.collegeplanner I/TEST: newNote added to notesSet
Code:
public class Schedule extends AppCompatActivity {
ArrayList<String> notes = new ArrayList<>();
// SharedPreferences sharedPreferences = this .getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences myPref = this.getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = myPref.getStringSet("NN", null);
if(notesSet != null){
notes.addAll(notesSet);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "notesSet didn't return null!");
}
else{
notesSet = new HashSet<String>();
notesSet.add("Ya note's set is empty");
notes.addAll(notesSet);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "noteSet returned null");
}
myPref.edit().putStringSet("NN", notesSet).apply();
}
public void AddNote(View view){
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
EditText editText = (EditText) findViewById(R.id.editText);
String newNote = editText.getText().toString();
SharedPreferences myPref = this.getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = myPref.getStringSet("NN", null);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
notesSet.add(newNote);
Log.i("TEST", "newNote added to notesSet");
notes.clear();
notes.addAll(notesSet);
editText.setText("");
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setAdapter(arrayAdapter);
}
}
You can use
if(myPref.edit().putStringSet("notes", set).commit())
Log.d(TAG , "SAVED");
else
Log.d(TAG , "Not Saved");
To check if shared preferences were actually saved.
in your code change
`
if(set == null){
set = new HashSet<String>();
notes.add("Initial Notes");
set.addAll(notes);
}
`
to
`
if(set == null){
set = new HashSet<String>();
notes.add("Initial Notes");
set.addAll(notes);
myPref.edit().putStringSet(set).apply();
}
`
the answer is from a duplicate post I made and it was answered there.
Oh, I just remembered a catch with String Sets in SharedPreferences that you're probably coming up against. (I admit I didn't really test your code very thoroughly when I did it.) You cannot try to modify the Set you get from getStringSet() and then save it back. You need to instantiate a new one, and pass that to putStringSet(). In your code, a simple fix would be: Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));. – Mike M.

Android Spinner Doesn't Return Id Properly

I'm having a difficulty in spinner android, more specifically in the data saving part.
First, I'm going to tell you what is the purpose behind the code below.
I want to create a spinner that user can choose which planet to buy, then when he/she hits the submit button, a toast will appear saying "You wanted to buy: ...." then followed by a purchase summary like username & price.
However, in the middle of the process I'm having a hard time to save the id of each spinner's element.
Every time I chose "Earth" (id= 1) & hit submit, the toast will always refer back to "Mars" which has id = 0. So it seems that the problem is my submit button will always reset the chosen id.
I intentionally set planetSpinner() method to return int, thus I could always track down the "id" being returned. But again, the submit button would always make it shows to id = 0.
Can anyone help me? I would really appreciate that. Thank you.
Spinner Code (MainActivity.java)
public int planetSpinner(){
context = this;
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
cSpinner = (Spinner) findViewById(R.id.coffee_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cSpinner.setAdapter(dataAdapter);
cSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You selected: " + cSpinner.getItemAtPosition(position), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_LONG).show();
}
});
return cSpinner.getSelectedItemPosition();
}
Submit Purchase Code (MainActivity.java)
public void submitOrder(View view){
Toast.makeText(MainActivity.this, "You wanted to buy: " + planetSpinner(), Toast.LENGTH_LONG).show();
displayMessage(confirmationOrder(userName, price));
}
public class MySpinner extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.coffee_spinner);
spinner.setOnItemSelectedListener(this);
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
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);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Have you try this:
Toast.makeText(MainActivity.this, "You selected: " + categories.get(position), Toast.LENGTH_LONG).show();
It is because the spinner was reinitialized everytime you call the function. Thus, the selected value was the first item, that is why your function always returns 0. Hope that helps.

Android: Checking If Arraylist is Empty JSON

Im using https://github.com/thest1/LazyList as my listview
i wonder how will i check if the listview is Empty or when null?
this is the sample codes from the post Execute
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
// Close the progressdialog
mProgressDialog.dismiss();
}
Please help !
I tried this code from what i've searched
if(!arraylist.isEmpty()){
listview = (ListView) findViewById(R.id.listOrderSummary);
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
//o_total.setText("aaa");
// Close the progressdialog
mProgressDialog.dismiss();
}else{ String msg = "No records found in Database!";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
Intent home_in = new Intent ( OrderSum.this,
Home.class );
startActivity(home_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
but i still got the error
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject"
To check if a listView is null:
listView != null;
To check if a listView dont have elements:
listView.getAdapter().getCount()<=0;

Information from another activity

I've been searching my problem but i can't find anything that helps my case.
I have an activity with a ListView where you can see names of people in a Database and when you click in one of the name it should go to another activity to show the details but it crashes when i click the name. Code above:
First Activity:
Code that shows all the names in ListView is working
myview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "clicked", 3000).show();
setContentView(R.layout.fragment_vertodos);
lv=(ListView) findViewById(R.id.listone);
Cursor cursor=mydb.rawQuery("SELECT * FROM teste;", null);
if(cursor.moveToFirst()){
Toast.makeText(getApplicationContext(), "Nome:", 3000).show();
data.clear();
do{
data.add(cursor.getString(cursor.getColumnIndex("name")));
}while (cursor.moveToNext());
ArrayAdapter <String> adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,data);
lv.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "DATA NOT AVAILABLE", 3000).show();
}
cursor.close();}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position,long id) {
// TODO Auto-generated method stub
String name = (String) l.getItemAtPosition(position);
List<String> emailLists = new ArrayList<String>();
emailLists.add(cursor.getString(cursor.getColumnIndex("email")));
String email = emailLists.get(position);
Intent intent = new Intent(MainActivity.this, Detalhes.class);
intent.putExtra("name",name);
intent.putExtra("email",email);
startActivity(intent);
}
});
My question is now. i created a second activity that get's the information but it's giving an error:
Second Activity:
txname = (TextView)findViewById(R.id.txtnome);
txmail = (TextView)findViewById(R.id.txtmail);
Bundle b = getIntent().getExtras();
if(b!=null){
String n =(String) b.get("name");
String m =(String) b.get("email");
txname.setText(n);
txmail.setText(m);
}
The first error is:
java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor
The first error is: java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor
Issue is your trying to type cast the String to Cursor at this line
Cursor detalhes = (Cursor) l.getItemAtPosition(position);
getItemAtPosition will return the data associated with the specified position in the list.
So, in your case your have passed List<String> data as the data for the list items. so each item will have as string object
String name = (String) l.getItemAtPosition(position);
If you need to pass the email of that items. You can create a ArrayList for email and add it from database like this.
List<String> emailLists = new ArrayList<String>();
And, add the emails into the list
data.add(cursor.getString(cursor.getColumnIndex("email")));
Now, When the item selected, get the email from the ArrayList
String email = emailLists.get(position);
I suspect you are setting an ArrayAdapter<String> to your ListView, so in the following line, l.getItemAtPosition(position) returns a String, not a Cursor, and the cast fails.
Cursor detalhes = (Cursor) l.getItemAtPosition(position);

Not Able to delete listItem from ListView Android

I am using this code in order to do this, but it is not functional at this point. I can select the checkbox, and when I click the button, nothing happens.
SimpleAdapter adapter;
List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>();
ListView listthings;
...
cb = (CheckBox)findViewById(R.id.checkBox1);
adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout,
from, to);
listthings.setAdapter(adapter);
listthings.setOnItemClickListener(this);
deleteButton = (Button) findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(this);
...
public void onClick(View v) {
if (v == this.deleteButton) {
// Toast.makeText(this, "delete clicked", Toast.LENGTH_SHORT).show();
deleteCheckedItems();
}
}
...
private void deleteCheckedItems() {
int count = this.listthings.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.listthings.isItemChecked(i)) {
painItems.remove(i);
adapter.notifyDataSetChanged();
listthings.invalidateViews();
}
}
Any help appreciated. Thank You in advance.
1) do not put adapter.notifyDataSetChanged(); into your loop but after deleteCheckedItems();
2) Why did you use: listthings.invalidateViews(); ? You can remove this line, this will redraw your list
3) why havn't you accepted my answer here: How to implement check box in listView Android to delete listItems
4) have you tested a toast after painItems.remove(i); that will show you if items are really removed? Or maybe just after calling deleteCheckedItems(), display the new painItems to see if everything worked

Categories

Resources