Messing with ListView in Android - android

Good day to everyone, I am new to Android, I keep on messing with ListView. The code below wont work! I dont know why. Please let me know where's the mistake.
Main Activity.java
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ListView listView = (ListView) findViewById(R.id.listView);
ArrayList<String> data = new ArrayList<String>();
data.add("Follow Me!");
data.add("This is now.");
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,data);
listView.setAdapter(adapter);
setContentView(R.layout.activity_main);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</LinearLayout>
After running the above code, my adroid device will show a dialogue saying:
"Sorry!
The application CodeGenerator has stopped unexpectedly. System failed to repair the error. Please use other software."
Please help!

The setContentView(R.layout.activity_main); line should be immediately after super.onCreate(savedInstanceState);.
What this
setContentView(R.layout.activity_main);
line does is it basically displays the screen (your android xml to the user). Now when you do
ListView listView = (ListView) findViewById(R.id.listView);
You are trying to get your ListView from your xml in your java code. But if you dont set the content itself, then there is no ListView and hence your application is crashing.

Anyway, I changed the code, and its running now. Here's the code:
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ListView listView = (ListView) findViewById(R.id.listView);
ArrayList<String> data = new ArrayList<String>();
data.add("Follow Me!");
data.add("This is now.");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
setListAdapter(adapter);
}
}
Still a mystery for me, why my first code did not work! If anyone can explain that, please let me know! Thank you!

Related

Why my app containing listView is crashing?

My app contains only 2 files one is MainActivity.java and activity_main.xml file. I wanted to use to listView to display a list of string but for some my app is crashing continuously.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add("Akshay");
arrayList.add("Akshay");
arrayList.add("Akshay");
arrayList.add("Akshay");
arrayList.add("Pandey");
arrayList.add("Akshay");
arrayList.add("Akshay");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,0,arrayList);
ListView listView=(ListView) findViewById(R.id.list_item);
listView.setAdapter(adapter);
}
}
Error
Your app is crashing because you are passing 0 as the second argument to your ArrayAdapter constructor. This is the "layout resource id" that your list will use for each item, so it needs to be something real.
The Android platform comes with some resources for this purpose built in, like android.R.layout.simple_list_item_1. You could try that. Change this line:
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,0,arrayList);
to this instead:
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
More information can be found in the developer guide: https://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews
You can't set the second argument of ArrayAdapter to 0. The constructor expects a valid resource. You need to set it to something like this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.id.my_resource_view, arrayList);

Listview is empty

I have the following codes as below. I am trying to run a simple list view all with not error and output is empty white screen.
MainActivity.java
public class MainActivity extends ActionBarActivity {
String[] stateArray = {"jh","kd"};
private ListView stateListView;
private ArrayAdapter<string> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stateListView = (ListView) findViewById(R.id.state_list);
arrayAdapter = new ArrayAdapter<string>(this,android.R.layout.simple_list_item_1);
stateListView.setAdapter(arrayAdapter);
}
}
activity_main.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.lab4_1.MainActivity" >
<ListView
android:id="#+id/state_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
Al works fine no error and the emulator just show empty which screen nothing inside. What could be missing?
Try this way
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stateArray);
Passed your Array as third argument of ArrayAdapter
For more information go to AndroidListView/Vogella
You have not passed your actual data in your adapter that is why its showing listview empty. Simple pass your stateArray as last parameter of your adapter as below:
Change your adapter line as below:
String[] stateArray = {"jh","kd"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stateArray);
Make your <string> as <String> you need to make your 'S' capital.
Note: The <String> part of it all means that the ArrayAdapter will be working with String[] data (the paths parameter). In other words, each element in the array will be a String.
It is empty because you are not submitting the dataset to the Adapter
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
Change it in
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stateArray);
Here you can find the documentation
Change
arrayAdapter = new ArrayAdapter<string>(this,android.R.layout.simple_list_item_1);
to
arrayAdapter = new ArrayAdapter<string>(this,android.R.layout.simple_list_item_1,stateArray );
Use like this
adapter.setAdapter(new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,stringarray));
Try this
arrayAdapter = new ArrayAdapter<string>(this,android.R.layout.simple_list_item_1,stateArray);
this is empty because you are not passing any data to adapter, the adapter acts as a bridge and is responsible of making the view see this See Adapter
See these examples Examples this will help you.
Best of luck!
First of all you definition of the generics on the ArrayList are wrong. It needs to say ArrayList<String>. Note the capital S.
You need to add Items to you list. The UI Designer is adding sample items automatically, that might have confused you into thinking there would already be items.
Try adding something like arrayAdapter.add("Test"); at the end of you onCreate().
If that works you can either add your stateArray using:
arrayAdapter.addAll(stateArray)
Full MainActivity.java:
package com.example.test;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] stateArray = {"jh","kd"};
private ListView stateListView;
private ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stateListView = (ListView) findViewById(R.id.state_list);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
stateListView.setAdapter(arrayAdapter);
arrayAdapter.add("Test");
arrayAdapter.addAll(stateArray);
}
}

PullToRefreshListView and getItemAtPosition

I'm trying to use PullToRefreshListView instead my standard ListView however, it did not work for me as a beginner, the listView is using an adapter and inflating xml item file into the listview,
when i replaced my listview wih
</com.handmark.pulltorefresh.library.PullToRefreshListView>
the listview becomes empty, no items are loaded
onItemClickListener()
when i replace the listview from ListView to PullToRefreshListView, i don't get the getItemAtPosition option,
so how can i add an onItemClickListener() if i can't get the position?
list_fragment.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="match_parent"
android:orientation="vertical" >
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="#+id/CarsList"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
my Activity.xml extends Activity
public class MainActivity extends Activity implements AsyncCallBack {
PullToRefreshListView myList;
CustomList cl;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (PullToRefreshListView) findViewById(R.id.CarsList);
...
That's the part of the code... getApiJsonArray is a listener which gets excuted on onPostExecute()
#Override
public JSONArray getApiJsonArray(JSONArray results) {
if (dialog != null) {
dialog.dismiss();
}
ArrayList<CarsItems> carsItems;
try {
carsItems = getCarsList(results);
cl = new CustomList(this, carsItems);
myList.setAdapter(cl);
myList.setOnItemClickListener(new OnItemClickListener() {
problem is in dimensions, the fill_parent is the problem, i check and it worked
By default when you copy and paste the pulltorefresh code into your project you get this :
<com.markupartist.android.widget.PullToRefreshListView
android:id="#+id/android:list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
i hesitated to ask someone on stackoverflow cuz i frustrated with importing it and updating the support version.....etc
however when you copy the code directly into your project you get a blank list or no list at all
simply change the height and width to something else like match_parent, this should be a straight forward answer for beginners like me.
and if you get a problem not finding the getItemAtPosition() for the setOnItemClickListener() method in the list try to call it inside that method (the setOnItemClickListener())
like that
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object item = a.getItemAtPosition(position);
..
hope this will help beginners like me! :)
try to trace your code
Log.i("MyApp","Results = "+results.toString());
carsItems = getCarsList(results);
inside CustomList after you set the items inside the adapter add
notifyDataSetChanged(); <-- without this no elements will appear

Adding new elements to the top of the ListView

I'm writing an IM client and I need to download (from filesystem or network) and show new elements at the top of ListView (it is history of messages -- older messages are at the top, newer -- at the bottom). I implemented my own Adapter for ListView but I can't add new elements at the beginning of the list and redraw it. (notifyDataSetChanged() isn't good for me, because indexes of messages in ListView changes and android can't redraw it normally).
How do other apps do something similar?
I don't create special code for it, I am simply creating new Adapter for my ListView:
messagesListView.setAdapter(new MessagesListAdapter(this));
And redefine getView() and getCount() method in MessagesListAdapter (extends ArrayAdapter now).
My XML for ListView is
<ListView
android:id="#+id/dialog_messages_list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginTop="#dimen/title_height">
</ListView>
And my XML for one element (one message) is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/dialogMessageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:background="#drawable/dialog_message_in"
/>
<TextView
android:id="#+id/dialogMessageDatetime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
May be you need other code?
EDIT: I tried
messagesListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList));
(new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
arrayList.add(0, "qwer");
}
}).start();
But it also not seems good. I tried to call ((ArrayAdapter<String>)messagesListView.getAdapter()).notifyDataSetChanged(); in thread, but it makes exception.
I suggest reversing the order of the List to display the newest result first.
Run this example:
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] array = {"oldest", "older", "old", "new", "newer"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, array);
Collections.reverse(list);
// When you want to add new Strings, put them at the beginning of list
list.add(0, "newest");
ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}
}
You don't have to override anything in the ArrayAdapter or ListView this way.
you can programmatically add some views in the class associated with your list view. For example:
To add stuff to a layout and make new elements:
TextView tv = new TextView(getApplicationContext());
EditText edit = new EditText(getApplicationContext());
relative.addView(tv);
relative.addView(edit);
This is to manipulate an existing element in the xml layout:
final TextView tv = (TextView) v.findViewById(R.id.listItem);
tv.setText("This an item I am changing");
If you look at some of the related questions, they will give your more information on this. But you can also checkout other people's custom listviews and adapters online. This one is really nice: http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

setlistadapter problem I don't know how this works at all

I'm having trouble with the setListAdapter(). It tells me to just create the method because it doesn't know anything about it. I'm, for now, just trying to get a list to populate and I don't even know what this code is doing.
public class PassScreen extends Activity {
TextView selection;
ArrayList<String> items = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.passwordscreen);
selection=(TextView)findViewById(R.id.selection);
try {
InputStream in=getResources().openRawResource(R.raw.words);
DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in,null);
NodeList words=doc.getElementsByTagName("word");
for (int i =0;i<words.getLength();i++){
items.add(((Element)words.item(i)).getAttribute("value"));
}
in.close();
}
catch (Throwable t){
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
}
public void onListItemClick(ListView parent, View v, int position, long id){
selection.setText(items.get(position).toString());
}
}
As you can see I have and xml file that I'm using. That looks just like what the book looks like but then again I copy and pasted the setListAdapter() so I guess that's not all that helpful.
If you could also show me what the setListAdapter() is doing that would be great. I can't seen to understand what google is talking about.
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"/>
</LinearLayout>
And some of the words xml:
<words>
<word value="lorem"/>
<word value="ipsom"/>
<word value="dolor"/>
</words>
Also can you explain what's going on? I don't understand the setListAdapter() at all. Or just point to Googles white paper. I can't find it. It's not like I know how to look that stuff up anyway.
setListAdapter() isn't a method you can call on an Activity (it is available on ListActivity but you're not using that). You're going to have to add a ListView into your layout (/res/layout/passwordscreen) and then find it and call setAdapter on that.
e.g.
ListView lv = (ListView) findViewById(R.id.mylistview);
lv.setAdapter(.....);
Hey That's because of base class, your base class should be:
public class yourClassName extends ListActivity{
Not class yourClassName extends Activity{
When you call setListAdapter this must extend ListActivity probably you class just extends Activity.
I saw it on some other post and it works for me!!

Categories

Resources