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;
Related
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.
I'm aware that this is very simple question but I'm a newbie in Android development so please go easy on me.
Problem that I have is in one of the fragments (AsyncTask specifically) that lays in my main activity.
AsyncTask sends out data to php script which then returns according data in json format. This is then processed and saved to jsonlist array. Up until post execute everything works fine data is downloaded, processed etc. However when program reaches post execute problems start to pop out. And basically i'm unable to list out all the data from jsonlist to listview
//setting up an array
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
//creating list view variable
ListView listview;
//Define work in progress dialog
private ProgressDialog mProgressDialog;
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait");
// Set progressdialog message
mProgressDialog.setMessage("Fetching data...");
mProgressDialog.setIndeterminate(false);
}
#Override
protected Boolean doInBackground(String... params) {
//To do in the background
//Define variable of JSON parser type
JSONParser jParser = new JSONParser();
//Pass url to json parser class to fetch and save it into array variable
JSONArray json = jParser.getJSONFromUrl(url);
//loop from 0 to length of an array by increasing by 1
for (int i = 0; i < json.length(); i++) {
//Try and catch routine to prevent any crashes
try {
//Get an object defined in { ... } in original json file
JSONObject c = json.getJSONObject(i);
//Separate object by obtaining values for each of the sections
String vtitle = c.getString(title);
String vcontent = c.getString(content);
String vuser = c.getString(user);
HashMap<String, String> map = new HashMap<String, String>();
//Fill up an array with data extracted
map.put(title, vtitle);
map.put(content, vcontent);
map.put(user, vuser);
//Add values into jsonlist
jsonlist.add(map);
} catch (JSONException e)
{
//In case of any error Stack trace will be returned
e.printStackTrace();
}
}
//Once everything has been done return null value
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
//listview = (ListView) findViewById(R.id.list);
// Set the adapter to the ListView
//listview.setAdapter(adapter);
//Get rid off dialog when operation of fetching data has been done
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
As you can see i have tried the commented code but listview = (ListView) findViewById(R.id.list); returns following error:
Cannot resolve method findViewById(int)
which prevents me from executing program. This is very upsetting because I literally have all the data i need in an array but only one line of code stops me from displaying it.
I have also tried:
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
setListAdapter(adapter);
lv = getListView();
But as in previous case error of unresolved method is returned. Which is due to the fact that fragment is extended by fragment and adding anything to it crashes it
public class Fragment2 extends Fragment, ListActivity {...}
Add this to your code in Fragment2 class.
private ListView listview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container, false);
listview = (ListView) v.findViewById(R.id.R.id.list);
return v;
}
Since you are in a Fragment you have to call getView() before findViewById, like this
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
listview = (ListView) getView().findViewById(R.id.list);
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);
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);
I was looking at this code while surfing through Stackoverflow
CODE::
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String DISTANCE = "distance";
static String RATING = "rating";
static String FLAG = "flag";
static String PRICE= "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("--------------URL----------");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("ARRAY");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("collegeNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("collegeTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("collegeIMAGE"));
map.put(MainActivity.DISTANCE, jsonobject.getString("collegeDISTANCE"));
map.put(MainActivity.RATING, jsonobject.getString("collegeRATING"));
map.put(MainActivity.PRICE, jsonobject.getString("collegePrice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
My Question is Why we use collection in android ?
What is the use ?
Why a hashmap is added to ArrayList in the above code ?
Can't we directly set views in android without collection,( I tried
it dosent work when dealing with group of key,value pairs)
.
~ I am a newbie so please go easy on with answers to my questions
I'm not sure how to answer your first 2 questions about collections... but I'll give it a shot.
1, 2) Collections are good for keeping groups of information lumped together and accessible through 1 variable. They also make it very easy to iterate over them, which makes them ideal for things like ListView adapters since that is also a list (or a collection).
Consider the following if you dont have an array
String var1 = "hi1";
String var2 = "hi2";
String var3 = "hi3";
String var4 = "hi4";
String var5 = "hi5";
String var6 = "hi6";
String var7 = "hi7";
String var8 = "hi8";
String var9 = "hi9";
// do something with the variables
Toast.makeText(this, var1, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var2, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var3, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var4, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var5, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var6, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var7, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var8, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var9, Toast.LENGTH_SHORT).show();
Now consider this, if you have arrays:
ArrayList<String> vars = new ArrayList<String(9);
for (int i = 1; i <= 9; i++)
{
vars.add("hi" + i);
Toast.makeText(this, vars.get(i), Toast.LENGTH_SHORT).show();
}
Much, much easier to work with.
3) The Hashmap is added to the array because the author wanted to keep a collection of separate name/value pairs. You can't have multiple keys with the same value in a Hashmap, so if you want that then you have to make a new Hashmap. The adding them to an array was to keep it neat, and then allowed the author to pass the array to a ListView adapter for displaying the values to the user using Android's built-in mechanism.
Basically the author created this Hierarchy:
item1
name
type
flag
distance
rating
price
item2
name
type
flag
distance
rating
price
item3
name
type
flag
distance
rating
price
...etc...
So when the ListView iterated over the array, each separate collection of hashmap values will be available to a new listview item for displaying.
4) You can set values directly, but working with adapters in ListViews makes it much less of a chore. You create an array, pass the array to the listview, and bada-bing-bada-boom, there's your list. Otherwise you will be creating ListView items and setting the display text all yourself for each item. In a similar way to why collections are useful when you have many variables of the same type, passing that collection to a ListView makes it much, much easier to code, maintain, and troubleshoot, not to mention that it just works!
I hope this helps! We are all beginners once :)
This piece of code will go populate an ListView, there are several ways to do that. I believe in this case, the coder is SimpleAdapter http://developer.android.com/reference/android/widget/SimpleAdapter.html.
Some think like:
// In This case the value os NAME is shown on android.R.id.text1 (TextView)
// and PRICE is shown on android.R.id.text2 (TextView)
String[] from = new String[]{MainActivity.NAME, MainActivity.PRICE}; // Map keys
int[] to = new int[]{android.R.id.text1, android.R.id.text2}; // List Layout item views
SimpleAdapter adapter = new SimpleAdapter(context, arraylist, android.R.layout.simple_list_item_2, String[] from, int[] to);
listview.setAdapter(adapter);