How to apply ArrayAdapter parameters as programatically made layout? - java

For ArrayAdapter,
ArrayAdapter <String> arrayAdapter = new ArrayAdapter(Context , resId , viewId , String[])
We need to have resId and viewId but how can i use Custom programmatically made Android Views ??
Is there any way so that i can apply programatically made layouts in this ArrayAdapter ??
Thankyou !

I did not quite get the question, hope this helps:
How to get the view id
If you programatically created a view and want to get its id, you need to call this:
view.setId(View.generateViewId());
int id = view.getId();
Same goes for Layouts (classes that extend Viewgroup), because they are views (ViewGroup extends View).
Code example:
layout.setId(View.generateViewId());
view.setId(View.generateViewId());
ArrayAdapter<?> adapter = new ArrayAdapter(this, layout.getId(), view.getId());
How to apply an ArrayAdapter
Every object that extends AbsListView has a setAdapter()-Method, in that you can pass an ArrayAdapter.

Related

App crashes when setting background colour

Every time I run my app it crashes giving me a nullpointerexception, I want to programatically change my background depending on the scenario, here is my code:
Main Activity:
public class Activity extends AppCompatActivity {
ConstraintLayout layout;
String messageSafe = "Item is Safe for Consumption";
String messageUnSafe = "Item is NOT Safe for Consumption";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
layout = new ConstraintLayout(this);
if (matched.length == 0) {
layout.setBackgroundResource(R.drawable.background_safe);
setContentView(layout);
changeColor("#00FF00");
messageView.setText(messageSafe);
}
else{
layout.setBackgroundResource(R.drawable.background_unsafe);
setContentView(layout);
changeColor("#FF0000");
messageView.setText(messageUnSafe);
}
ListView listContains = (ListView) findViewById(R.id.lvItemsFound);
ArrayAdapter<String> contains = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, foundItems);
listContains.setAdapter(contains);
ListView listRestricted = (ListView) findViewById(R.id.lvItemsRestricted);
ArrayAdapter<String> found = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matched);
listRestricted.setAdapter(found);
}
You are losing reference to your old view because you changed the layout to a new ConstraintLayout object. This means you now don't have your ListView objects and other items in your XML because that View is gone. It's not the ContentView anymore. If you want to work on the existing layout, you need to give the root view an ID.
<constraintlayout android:id="#+id/container" ... />
Then you can reference that ID with findViewById(R.id.container) and use the object you get from it to change your background like you are doing.
Try this:
1. Give your root view an ID
2. Set a ConstraintLayout object with ConstraintLayout layout = findViewById(R.id.container) (Note: You can call it anything, not just container, I am just going off my example from above, since I gave it the ID 'container')
3. call setBackgroundResource() like you are doing.
4. No need to call setContentView() again, this was set in the beginning, and you do not want to reset it to a new view you just constructed like you were initially doing.
5. You shouldn't crash when trying to call setAdapter() to your ListView now because you don't have a reference to an object that isn't in your content view.
layout = (ConstraintLayout)findViewById(R.id.container);
if (matched.length == 0) {
layout.setBackgroundResource(R.drawable.background_safe);
changeColor("#00FF00"); //assuming this is some local function?
messageView.setText(messageSafe);
}
else{
layout.setBackgroundResource(R.drawable.background_unsafe);
changeColor("#FF0000");
messageView.setText(messageUnSafe);
}
You are trying to set the background by replacing the view of your activity (this is what setContentView() does). This causes a null pointer exception later because the old layout (defined in the XML) has been replaced, so your list view no longer exists.
Instead, you should get a reference to the existing root view (the ConstraintLayout, although if you're just setting background you can just reference it as a View, no need to be so specific), and set the background on it, like so:
findViewById(R.id.container).setBackgroundResource(R.drawable.unsafe);
You'll also need to give the containing layout an id in the existing layout XML:
<android.support.constraint.ConstraintLayout
android:id="#+id/container"
... etc.

ArrayAdapter with Json Parsing

i'm doing a system of news feed, so, i've a difficulty for adapter my ArrayAdapter insert value into ListView, with: "username, name, picture, content and others values" i'm newbie in Android Studio.
Searching the internet I found this function
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
But, i use ArrayList and ArrayAdapter:
ArrayList<Post> postList =
new JsonConverter<Post>().toArrayList(s, Post.class);
ArrayList<String> postador = new ArrayList<String>();
for(Post value: postList){
postador.add(value.id_postador);
postador.add(value.post_legenda);
if(value.post_foto != null) {
postador.add(value.post_foto);
}
postador.add(value.post_data);
postador.add(value.curtidas);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_list_item_1, postador
);
lvPost.setAdapter(adapter);
I tried it, but no success.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.list_item, postador, new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
There a method convert ListAdapter in ArrayAdapter or adapter my ArrayAdapter for ListAdapter?
If you are a newbie to Android, I would like to recommend few things to you.
1). Start Using RecyclerView from the very beginning instead of ListView. It is more advanced, flexible and efficient version of ListView. You can find a sample demo for the RecyclerView here and here
2). If you still want to use ListView. Then you further have two options, either to use BaseAdapter or ArrayAdapter.
a). Base Adapter as the name suggests, is a base class for all the adapters. If you need more flexibility, you can go with it. You can find the demo sample here and here
b). On the other hand, ArrayAdapter is a concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView.If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.To use something other than TextViews (like in your case) for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want. You can find the demo sample here and here.
Hope it will help you in future and also I suppose you will get answer to your question in the specified demo samples. Thanks and have a good day.. :)

build list from array and allow list to be clickable

I'm trying to build and Android app:
How can I build a list on screen from an array and have the list be clickable?
with a value of the name to be able to use later stored in a String.
What I have now.
String game_list[] = {"game_0","game_2","game_3","game_3","game_4","game_5"};
for(int i=0; i<game_list.length; i++){
myText = myText + game_list[i] +"\n";
}
myTextView.setText("");
myTextView.append(myText);
Also you can use a spinner and adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, game_list); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Here's a super simple example that I have used: http://www.javacodegeeks.com/2013/06/android-listview-tutorial-and-basic-example.html.
You basically need to make a listview object and add it to whatever view you happen to be using. Then you add "extends ListActivity" to the activity and add your list to the listactivity like so:
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,R.layout.file_row, this.directoryEntries);
ListView fileList = (ListView) findViewById(android.R.id.list);
fileList.setAdapter(directoryList);
Call:
protected void onListItemClick(ListView l, View v, int position, long id)
to associate actions with your listview elements
You can build that with ListView control in android and here very good tutorial about it to get more understand how to build it with the array or from any other data source like from database
http://www.vogella.com/tutorials/AndroidListView/article.html
feed be back in any thing not obvious for you

how to call ArrayAdapter constructer from Fragment in Android

I am trying to add a two-column ListView to my android app. When I created the project, I selected the option Fragment which creates that beautiful navigation by sliding to left and right. So my MainActivity extends FragmentActivity.
my problem is when I am trying to add AddayAdapter to ListView, the construstor of ArrayAdapter looks for a context object and I dont know to pass that.
here is the code where I get error
StableArrayAdapter adapter = new StableArrayAdapter(this, R.layout.row , list);
listview.setAdapter(adapter);
When I pass "this", it passes FragmentActivity because the activity extends FragmentActivity. but constructor need a "Context" object.
it gives this error message
"The constructor MainActivity.StableArrayAdapter(MainActivity.DummySectionFragment, int, ArrayList<String>) is undefined"
How can I pass Context object?
You are setting the adapter inside a fragment. Use
StableArrayAdapter adapter = new StableArrayAdapter(this.getActivity(), R.layout.row , list);
StableArrayAdapter adapter = new StableArrayAdapter(getContext(), R.layout.row , list);
listview.setAdapter(adapter);
Did you try passing something like this from your Fragment. Try either getContext() or getApplicationContext().

How to get TextView from ListView item?

I have following code for making ListView:
SimpleAdapter adapter=new SimpleAdapter(this, DictionaryDbWrapper.getInstance().getAllWords(),
android.R.layout.simple_list_item_2, new String[]{DictionaryDbHelper.WORD, DictionaryDbHelper.CATEGORY},
new int[]{android.R.id.text1, android.R.id.text2});
mList.setAdapter(adapter);
It works and show me elements, all correct. Also I have OnItemClickListener with following code for clicking by items:
View view=mList.getSelectedView();
if (view==null) {
Toast.makeText(UpdatingWordActivity.this, "1", Toast.LENGTH_LONG).show();
}
But mList.getSelectedView() returns me null also. Why?
UPDATE: why does this cast throw exception:
View v=(View)mList.getItemAtPosition(0);
The call to getSelectedView() is for when you use radio buttons with the listview. See CHOICE_MODE_SINGLE. getItemAtPosition() just calls getItem(position) on the underlying adapter; in your case it's a SimpleAdapter. That casting throws an exception because SimpleAdapter.getItem() isn't returning a view, it's returning (I believe) the Map of data that is at the given position in the adapter. Other adapters return other things for the getItem() method. For instance, the CursorAdapter returns a cursor.
See the answer above for the answer to the first question
Listview OnItemClickListener has View v as parameter, you need to use this parameter to get text.
Here is Android tutorial on this topic .

Categories