Listview item background color change - json

I want to change the list-view item background color without onitemclick() method. Because at first i've to check item data and based on that it will change the color . How should i do it ?

listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
if(items.get(position).getSomething().equals(Something){
// If your condition fulfills then change background color
listView.getChildAt(position).setBackgroundColor(#55667788);
}
}
});
EDIT:
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.row_counter, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.tv_name);
viewHolder.number = (TextView) convertView
.findViewById(R.id.tv_number);
viewHolder.row = (TextView) convertView
.findViewById(R.id.rel_row);
convertView.setTag(viewHolder);
}
holder = (ViewHolder) convertView.getTag();
currentModel = list.get(position);
holder.name.setText(currentModel.getName());
holder.number.setText(currentModel.getNumber());
if(holder.name.equals("SOMETHING")){
holder.row.setBackgroundColor("#55667788");
}else{
holder.row.setBackgroundColor("#000000");
}
return convertView;
}

Related

how to open specific/different Activity in the recyclerview whose data is from json using volley

I want to open new activity that is different in each recyclerview item.
I have read and I do not need an image item here : How to open a different activity on recyclerView item onclick
This is my Adapter
public class B001Adapter extends RecyclerView.Adapter {
private Context context;
private LayoutInflater inflater;
List<B001Data> udata = Collections.emptyList();
public B001Adapter(Context context, List<B001Data> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.udata = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.datab001, parent, false);
MyHolder holder = new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder = (MyHolder) holder;
final B001Data current = udata.get(position);
myHolder.device_name.setText(current.device_name);
myHolder.mac_address.setText(current.mac_address);
myHolder.status.setText("Status:" + String.valueOf(current.status));
}
#Override
public int getItemCount() {
return udata.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView device_name, mac_address, status;
public MyHolder(View itemView) {
super(itemView);
context = itemView.getContext();
device_name = (TextView) itemView.findViewById(R.id.txt_device_name);
mac_address = (TextView) itemView.findViewById(R.id.txt_mac_address);
status = (TextView) itemView.findViewById(R.id.txt_status);
}
public void onClick(AdapterView<?> parent, View view, int position {
final Intent intent;
switch (getAdapterPosition()){
case 0:
intent = new Intent(context, MainActivity.class);
break;
case 1:
intent = new Intent(context, B001FacilityM.class);
break;
case 2:
intent = new Intent(context, B001HRD.class);
break;
default:
intent = new Intent(context, B001home.class);
break;
}
context.startActivity(intent);
}
}
}
I use volley to get Json data displayed on the recyclerView. Looking for your advice. Thanks
First You Should assign id to layout file (R.layout.datab001),
find out id using findViewsById in MyHolder() constructor
and then set onClickListener to layout like myHolder.layout.setOnClickListener(....);
in onBindViewHolder().
or check other answer
RecyclerView onClick

How to get data by json on xamarin android

public async override void OnActivityCreated (Bundle savedInstanceState)
{
base.OnActivityCreated (savedInstanceState);
lst = View.FindViewById<ListView> (Resource.Id.lstHome);
var result = await json.GetStringbyJson ("https://api-v2.soundcloud.com/explore/Popular+Music?tag=out-of-experiment&limit=20&linked_partitioning=1");
if (result != null)
{
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<TrackModel.RootObject> (result);
lst.Adapter = new TrackAdapter(Activity, items.tracks);
}
}
public class TrackAdapter:BaseAdapter
{
LayoutInflater _inflater;
List<TrackModel.Track> _tracks;
public TrackAdapter(Context context, List<TrackModel.Track> tracks)
{
_inflater=LayoutInflater.FromContext(context);
_tracks=tracks;
}
public override TrackModel.Track this[int index]
{
get{ return _tracks [index]; }
}
public override int Count{
get{ return _tracks.Count; }
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView,ViewGroup parent)
{
View view = convertView ?? _inflater.Inflate (Resource.Layout.ExploreFragment, parent, false);
var track = _tracks [position];
var viewHolder = view.Tag as TrackViewHolder;
if (viewHolder == null) {
viewHolder.Title = view.FindViewById<TextView> (Resource.Id.textviewItems);
viewHolder.SubTitle = view.FindViewById<TextView> (Resource.Id.textviewSubItem);
viewHolder.Image = view.FindViewById<ImageView> (Resource.Id.image);
view.Tag = viewHolder;
}
viewHolder.Title.Text = track.title;
viewHolder.SubTitle.Text = track.track_type;
Android.Net.Uri uri = Android.Net.Uri.Parse (track.artwork_url);
viewHolder.Image.SetImageURI(uri);
return view;
}
}
public class TrackViewHolder:Java.Lang.Object
{
public TextView Title{ get; set;}
public TextView SubTitle{get;set;}
public ImageView Image{ get; set;}
}
public override TrackModel.Track this[int index]. It get a error is makred as an overdie but no suitable indexer found to overide.
I want to take data from json up listview on xamarin android.
If it is unviersal app then it easy to use.
The way you want to set the adapter for your listview will not work that way.
Setting the adapter property of the listview inside the foreach loop is totally wrong. The same applies to your textviews.
You need to implement a custom adapter that loads a layout for each of your track list item. Your custom adapter could look like the following example I've written out of my mind with out further testing. But it implements the required methods a custom adapter needs to implement.
The important part is the GetView method that returns your track layout every time the listview ask for a new item to represent. To keep the app memory down it uses the ViewHolder pattern, which isn't required if you want to use the RecycleView.
public class TrackAdapter : BaseAdapter<Tracks>
{
LayoutInflater _inflater;
List<Tracks> _tracks;
public TrackAdapter(Context context, List<Tracks) tracks)
{
_inflater = LayoutInflater.FromContext(context);
_tracks = tracks;
}
public override Tracks this [int index]
{
get { return _tracks[index]; }
}
public override int Count
{
get { return _tracks.Count; }
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView ?? _inflater.Inflate(Resource.Layout.TrackListItem, parent, false);
var track = _tracks[position];
var viewHolder = view.Tag as TrackViewHolder;
if (viewHolder == null)
{
viewHolder = new TrackViewHolder();
viewHolder.Title = view.FindViewById<TextView>(Resource.Id.textviewItems);
viewHolder.Subtitle = view.FindViewById<TextView>(Resource.Id.textviewSubItems);
viewHolder.Image = view.FindViewById<ImageView>(Resource.Id.image);
view.Tag = viewHolder;
}
viewHolder.Title.Text = track.title;
viewHolder.SubTitle.Text = track.track_type;
viewHolder.Image.SetImageURI(Uri(track.artwork_url));
return view;
}
class TrackViewHolder : Java.Lang.Object
{
public TextView Title { get; set; }
public TextView SubTitle { get; set; }
public ImageView Image { get; set; }
}
}
The layout will contain your title, subtitle and image and could easily build with a normal layout file.
In your fragment you then create a new instance for TrackAdapter pass the context and the list of tracks you want to be shown in the listview.
public override void OnActivityCreated (Bundle savedInstanceState)
{
base.OnActivityCreated (savedInstanceState);
lst = View.FindViewById<ListView> (Resource.Id.lstHome);
var result = json.GetStringbyJson ("https://api-v2.soundcloud.com/explore/Popular+Music?tag=out-of-experiment&limit=20&linked_partitioning=1");
if (result != null)
{
var items = JsonConvert.DeserializeObject<TrackModel.RootObject> (result);
lst.Adapter = new TrackAdapter(Activity, items.tracks);
}
}

Add view created dynamically to convertview in expandable listview android

This is my first question, I need to add dynamically textViews to convertView that is returned in getChildView() method expandable, but I can not do in any way..
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ViewHolderChild holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_line, null);
holder = new ViewHolderChild();
holder.txNumeroSolicitacao = (TextView) convertView.findViewById(R.id.textViewNumeroSolicitacao);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
holder.txNumeroSolicitacao.setText(String.valueOf(getChild(groupPosition,childPosition).getNumero()));
//if my log list isn't empty, I want add a textview dynamically to view
if(!getChild(groupPosition,childPosition).getLog().isEmpty()) {
holder.textViewResponse = new TextView(context);
RelativeLayout.LayoutParams alignParentLeft = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
alignParentLeft.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
holder.textViewResponse.setLayoutParams(alignParentLeft);
((ViewGroup) convertView).addView(holder.textViewResponse);
}
return convertView;
}
But I can not add the textView to convertView. The application always returns unexpected behaviour.
You might add the TextView in child_line.xml with android:visibility="gone", and set it's visibility in getChildView according to if the current line's bound object's log is empty.

How to create my own arrayAdapter for listView - Android [duplicate]

This question already has answers here:
BaseAdapter class wont setAdapter inside Asynctask - Android
(4 answers)
Closed 9 years ago.
I am trying to create my own arrayAdapter so I can place multiple textviews inside of a listview. I have searched everywhere and can not find a way to do it. I am new to this and not so sure how to handle it. So far I have an asynctask that gathers 3 strings in a JSON method. These strings are what I want placed in the textViews but I have no idea how to do so, here is my current code.
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
private ArrayAdapter<String> mAdapter = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
final String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
ArrayList<String> myList = new ArrayList<String>();
class MyClassAdapter extends ArrayAdapter<String> {
private Context context;
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
super(context, textViewResourceId, items);
this.context = context;
}
public View getView(int position, View convertView) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
String item = getItem(position);
if (item!= null) {
// My layout has only one TextView
TextView commentView = (TextView) view.findViewById(R.id.listComment);
TextView usernameView = (TextView) view.findViewById(R.id.listPostedBy);
TextView NumberView = (TextView) view.findViewById(R.id.listNumber);
// do whatever you want with your string and long
commentView.setText(comments);
NumberView.setText(numbers);
usernameView.setText(usernames);
}
return view;
}
}
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
new loadComments().execute();
This code does not work but I think I am on the right track.
Let us say, you create a class that hold your information about the comments instead of creating three related Arrays :
class Commentary
{
public String username;
public String comment;
public int commentaryIndex;
}
The BaseAdapter can take a List as a parameter whereas the ArrayAdapter wouldn't.
class MyRealAdapter extends BaseAdapter
{
private List<Commentary> comments;
public MyRealAdapter(List<Commentary> comments )
{
this.comments = comments;
}
#Override
public int getCount() {
return comments.size();
}
#Override
public Object getItem(int index) {
return comments.get(index);
}
#Override
public long getItemId(int index) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Commentary c = (Commentary) getItem(position);
//c.username, c.comment, c.commentaryIndex
// create the view and stuff
return null;
}
}
As you can see, you again have the getView method but now you can retrieve your complete objet and not just a String.
There is a couple more method to override, but as you can see it's very simple.
You might need to pass other argument like a Context or a LayoutInflater to the constructor, but it's not mandatory.
EDIt :
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
ArrayList<Commentary> comments = new ArrayList<commentary>();
for ( int i=0; i<commentArray.length(); i++ ) {
Commentary c = new Commentary();
c.username = usernameArray.getString(i);
c.comment = commentArray.getString(i);
c.commentaryIndex = Integer.parseInt(numberArray.getString(i));
comments.add(c);
}
MyRealAdapter adapter = new MyRealAdapter(comments);

Google Maps Compass crashes with onPause & onCreate (removing them works but I don't have compass)

If I comment the onPause compass.disable and onResume compass.Enable apps start and work but I don't have the compass on my Google map.
On the other hand if I uncomment these two line the apps don't even show. Like is blocked, then I again comment this two line and emulator again work. So somewhere is problem with compass but I don't see where, any help.
MapView map;
MyLocationOverlay compass;
MapController controller;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
long start;
long stop;
int x, y;
int latit;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);// dodao za favicon
setContentView(R.layout.activity_main);
setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.logo);
map = (MapView) findViewById(R.id.mvMain);
map.setBuiltInZoomControls(true);
this.setTitle("EasyMaps=QRZ");
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(MainActivity.this, map);
overlayList.add(compass);
controller = map.getController();
GeoPoint point = new GeoPoint((int) (47.975 * 1E6), (int) (17.056 * 1E6));
controller.animateTo(point);
controller.setZoom(17);
d = getResources().getDrawable(R.drawable.icon);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null) {
latit = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(latit, longi);
OverlayItem overlayitem = new OverlayItem(ourLocation, "Location", "Location");
CustomPinpoint custom = new CustomPinpoint(d, MainActivity.this);
custom.insertPinpoint(overlayitem);
overlayList.add(custom);
} else {
Toast.makeText(MainActivity.this, "Provider not avaiable!", Toast.LENGTH_SHORT).show();
}
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
super.onResume();
compass.enableCompass();//Problem
lm.requestLocationUpdates(towers, 500, 1, this);
}
#Override
protected void onPause() {
super.onPause();
compass.disableCompass();//Problem
lm.removeUpdates(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
start = e.getEventTime();
x = (int) e.getX() + 11;
y = (int) e.getY() - 15;
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop = e.getEventTime();
}
if (stop - start > 1500) {
// to do action
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Option panel");
alert.setMessage("Choose an option!");
alert.setButton("Put flag", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayitem = new OverlayItem(touchedPoint, "Flag", "Flag");
CustomPinpoint custom = new CustomPinpoint(d, MainActivity.this);
custom.insertPinpoint(overlayitem);
overlayList.add(custom);
}
});
alert.setButton2("Get address", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if (address.size() > 0) {
String display = "";
for (int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++) {
display += address.get(0).getAddressLine(i) + "\n";
}
Toast t3 = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t3.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// Nista
}
}
});
alert.setButton3("View", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (map.isSatellite()) {
map.setSatellite(false);
map.setStreetView(true);
} else {
map.setStreetView(false);
map.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
latit = (int) (l.getLatitude() * 1E6);
longi = (int) (l.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(latit, longi);
OverlayItem overlayitem = new OverlayItem(ourLocation, "Location", "LOcation");
CustomPinpoint custom = new CustomPinpoint(d, MainActivity.this);
custom.insertPinpoint(overlayitem);
overlayList.add(custom);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
You may want to use different names. What you call "compass" is actually your location, and it will certainly behave differently from a compass - it will mostly point in a different direction, for starters.
Before you try to enable or disable the MyLocation overlay, you need to check if it is actually non-null.
if (mMyLocationOverlay != null)
mMyLocationOverlay.disableMyLocation();