So i'm currently working on a app that i can use while training. What i'm trying to achieve here is to log what i'm doing everyday in so i can later on see how my progress is going..
This is what i have done so far.
Mainactivity
public class Mandag extends AppCompatActivity{
EditText O1,R1,S1,KG1;
Button Leggtil, logg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mandag);
Leggtil = (Button)findViewById(R.id.leggtil);
O1 = (EditText)findViewById(R.id.O1);
R1 = (EditText)findViewById(R.id.R1);
S1 = (EditText)findViewById(R.id.S1);
KG1 = (EditText)findViewById(R.id.KG1);
logg = (Button)findViewById(R.id.button);
Leggtil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences SF = getSharedPreferences("Trening", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = SF.edit();
editor.putString("O1",O1.getText().toString());
editor.putString("R1",R1.getText().toString());
editor.putString("S1",S1.getText().toString());
editor.putString("KG1",KG1.getText().toString());
editor.commit();
Toast.makeText(Mandag.this,"Lagt til i logg",Toast.LENGTH_LONG).show();
}
});
logg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Mandag.this, Logg.class);
startActivity(i);
}
});
}
Mainactivity Layout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Øvelse"
android:id="#+id/ovelse"
android:layout_weight="0.03"
android:layout_row="0"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Reps"
android:id="#+id/Reps"
android:layout_weight="0.03"
android:layout_row="0"
android:layout_column="1"
android:layout_marginLeft="0dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sets"
android:id="#+id/Sets"
android:layout_weight="0.03"
android:layout_row="0"
android:layout_column="2"
android:layout_marginLeft="0dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="KG"
android:id="#+id/KG"
android:layout_weight="0.03"
android:layout_row="0"
android:layout_column="3"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp" />
<EditText
android:layout_width="148dp"
android:layout_height="wrap_content"
android:id="#+id/O1"
android:layout_row="1"
android:layout_column="0" />
<EditText
android:layout_width="62dp"
android:layout_height="wrap_content"
android:id="#+id/R1"
android:layout_row="1"
android:layout_column="1" />
<EditText
android:layout_width="51dp"
android:layout_height="wrap_content"
android:id="#+id/S1"
android:layout_row="1"
android:layout_column="2" />
<EditText
android:layout_width="51dp"
android:layout_height="wrap_content"
android:id="#+id/KG1"
android:layout_row="1"
android:layout_column="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="logg"
android:id="#+id/button"
android:layout_row="27"
android:layout_column="0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leggtil"
android:id="#+id/leggtil"
android:layout_row="27"
android:layout_column="3" />
Log activity
public class Logg extends AppCompatActivity {
String O1, R1, S1, KG1;
private ArrayList<HashMap<String, String>> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logg);
ListView listView=(ListView)findViewById(R.id.listView);
list=new ArrayList<HashMap<String,String>>();
SharedPreferences SF = getSharedPreferences("Trening", Context.MODE_PRIVATE);
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy");
String date = df.format(Calendar.getInstance().getTime());
HashMap<String,String> dates=new HashMap<String, String>();
dates.put(FIRST_COLUMN, date.toString());
list.add(dates);
HashMap<String,String> form=new HashMap<String, String>();
form.put(FIRST_COLUMN, "Øvelse");
form.put(SECOND_COLUMN, "Reps");
form.put(THIRD_COLUMN, "Sets");
form.put(FOURTH_COLUMN, "KG");
list.add(form);
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(FIRST_COLUMN, O1 = SF.getString("O1",""));
temp.put(SECOND_COLUMN,R1 = SF.getString("R1",""));
temp.put(THIRD_COLUMN, S1 = SF.getString("S1",""));
temp.put(FOURTH_COLUMN, KG1 = SF.getString("KG1",""));
list.add(temp);
Loggene adapter=new Loggene(this, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
int pos = position + 1;
Toast.makeText(Logg.this, Integer.toString(pos) + " Clicked", Toast.LENGTH_SHORT).show();
}
});
}
Log listview layout
<ListView
android:layout_width="match_parent"
android:layout_height="617dp"
android:id="#+id/listView" />
Listview Activity
public class Loggene extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth;
public Loggene(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.logg_item, null);
txtFirst=(TextView) convertView.findViewById(R.id.ovelse);
txtSecond=(TextView) convertView.findViewById(R.id.Reps);
txtThird=(TextView) convertView.findViewById(R.id.Sets);
txtFourth=(TextView) convertView.findViewById(R.id.KG);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));
txtFourth.setText(map.get(FOURTH_COLUMN));
return convertView;
}
}
Listview Layout
<TextView
android:id="#+id/Sets"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1" />
<TextView
android:id="#+id/Reps"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="0.5" />
<TextView
android:id="#+id/KG"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1" />
Listview columns class
public class Ovelser {
public static final String FIRST_COLUMN="First";
public static final String SECOND_COLUMN="Second";
public static final String THIRD_COLUMN="Third";
public static final String FOURTH_COLUMN="Fourth";
}
Result
What i'm trying to do here is to get input text form the Mainactivity layout to the listview and to be sorted in columns. This part works perfectly. What i cannot figre out is how to add more "items". When i do this the data thats been saved (Trening) in SharedPrefs will be overwritten. So do how could i add more data ? is there perhaps another way i should do this? if so please tell!
As Youxian stated, your data is being overwritten when put in the same key. Because you are going to repeat this overriding process every day, you will not be able to get an accurate log of daily workout data. Instead, use database to store your data. Here is how shared prefs works:
(windowsphone.interoperabilitybridges.com)
As you can see in this diagram, they IsolatedStorageSettings is based off of the key/value pairs, which you are overriding right now. That is the way that the compiler even knows what data to get, by the key:
(kb4dev.com)
So again, I suggest you use either different keys to prevent overriding, or you use data base.
SharedPreference is like key and value, so you always put data in the same key(O1,R1,S1,KG1). The data you stored would be overwritten. if you want to use shared preference anyway, just put values in different keys (like add a counter after key name). and use getAll() method to show them in your list.
you can see these for more information about shared preference:
http://developer.android.com/intl/es/reference/android/content/SharedPreferences.html
http://developer.android.com/intl/es/reference/android/content/SharedPreferences.Editor.html
Using android SQLite database to do this might be a choice, learn more:
http://developer.android.com/intl/es/training/basics/data-storage/databases.html
Related
I have a class called AnimalMarker which should represent the bare minimum of a normal google maps Marker (latitude, longitutde, location) and an object Animal. And I'm using the Firebase Realtime Database to store those AnimalMarkers.
What I want to do, but don't know how to do it, is create a custom InfoWindow (I've created the new layout and an Adapter that should be passed in the MapActivity) that even though is binding to the google maps Markers, should take data from the corresponding AnimalMarker of that Marker.
The logic of my MapActivity is:
create an AnimalMarker using the latitude,longitute, and taking user input for adding an animal to it. now the AnimalMarker object has been created
add the AnimalMarker to the Firebase Realtime Database
when the DatabaseListener gets the update, it will call a method in the MapActivity to re-create the List of google-maps Markers and re-draw them.
I realise now that instead of saving just the google-maps Markers in a List, a Hashmap < AnimalMarker, Marker > would be better, and update the Hashmap when the database Listener notices the update But even so, I wouldn't know how to make the InfoWindowAdapter take the data from the associated AnimalMarker of a Marker.
Here is my code:
MapActivity
public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener {
...
private void initListeners() {
Log.d(TAG, "initListeners: initializing SearchText");
firebaseAuth = FirebaseAuth.getInstance();
geocoder = new Geocoder(MapActivity.this);
markersDatabase = new MarkersDatabase();
myMarkersList = new ArrayList<>();
allMarkersList = new ArrayList<>();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener(){
#Override
public void onMapLongClick(LatLng latLng) {
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String locationTitle = addresses.get(0).getAddressLine(0);
Log.d(TAG, "onMapLongClick: addresses = " + addresses.get(0));
AnimalMarker marker = new AnimalMarker(latLng.latitude, latLng.longitude, locationTitle, firebaseAuth.getCurrentUser().getUid());
markersDatabase.addMarker(marker);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(marker.getLatitude(), marker.getLongitude()), DEFAULT_ZOOM));
}
});
}
...
private void startMarkersListener() {
markersDatabase.readCurrentUserMarkers(new MarkersDatabaseListener() {
#Override
public void onCurrentUserMarkersCallBack(List<AnimalMarker> list) {
Log.d(TAG, "onCurrentUserMarkersCallBack: myMarkersList updated");
clearAllMyMarkers();
for (AnimalMarker animalMarker : list) {
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(animalMarker.getLatitude(), animalMarker.getLongitude()))
.title(animalMarker.getLocation())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.visible(myMarkersVisible));
Log.d(TAG, "onCurrentUserMarkersCallBack: created a marker at: " + marker.getTitle());
myMarkersList.add(marker);
}
}
#Override
public void onAllMarkersCallBack(List<AnimalMarker> list) {
Log.d(TAG, "onCurrentUserMarkersCallBack ----> onAllMarkersCallBack: should never reach here");
}
});
}
MarkerInfoWindowAdapter
public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter{
private final View mWindow;
private Context context;
public MarkerInfoWindowAdapter(Context context) {
this.context = context;
mWindow = LayoutInflater.from(context).inflate(R.layout.marker_info_window, null);
}
private void renderWindowText(Marker marker, View view) {
// example code to come here
String title = marker.getTitle();
TextView titleTextView = (TextView) view.findViewById(R.id.miwLocation);
if(!title.equals("")) {
titleTextView.setText(title);
}
}
#Override
public View getInfoWindow(Marker marker) {
renderWindowText(marker, mWindow);
return mWindow;
}
#Override
public View getInfoContents(Marker marker) {
renderWindowText(marker, mWindow);
return mWindow;
}
}
layout of my desired information in the custom InfoWindow:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/white_border"
android:orientation="horizontal"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/miwLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
android:layout_marginStart="150dp"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:maxLines="2"
android:text="miwLocation"
android:textColor="#000000"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:src="#drawable/dog_icon"
android:id="#+id/miwImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_below="#+id/miwLocation"
android:layout_alignParentStart="true"
android:layout_marginStart="18dp"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/miwAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/miwLocation"
android:layout_marginStart="30dp"
android:layout_marginTop="12dp"
android:layout_toEndOf="#+id/miwImage"
android:layout_toRightOf="#id/miwImage"
android:ellipsize="end"
android:maxLines="2"
android:text="miwAnimalName"
android:textColor="#000000"
android:textSize="17sp" />
<TextView
android:id="#+id/miwAnimalAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/miwAdultCB"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/miwImage"
android:text="3 yrs"
android:textColor="#000000"
android:textSize="20sp" />
<CheckBox
android:id="#+id/miwAdultCB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/miwAnimalName"
android:layout_marginLeft="20dp"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/miwImage"
android:text=" Adult"
android:textSize="20dp" />
<CheckBox
android:id="#+id/miwNeuteredCB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/miwAnimalName"
android:layout_marginLeft="20dp"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/miwAdultCB"
android:text=" Neutered"
android:textSize="20dp" />
</RelativeLayout>
</LinearLayout>
Image of it:
I've found the solution after understanding the answer in this post
custom info window adapter with custom data in map v2
The easiest approach would to create an anonymous Adapter and use the global HashMap< Marker, AnimalMarker > inside it.
Something like this
getMap().setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
// set layout, use Marker/AnimalMarker here
}
});
I have a project which shows list of blood donors using place search, i want to insert a call button in that list view for each user, i have no idea how to add it, Can you please help me with this? Screenshot 1: Screenshot 2: Each detail of the blood donor like name , blood group and phone are stored in each field in the server. "bld_phn" is the id of text view that shows phone number."phone" is the array string
code:
public class blood extends Activity {
AsyncHttpClient client;
JSONArray jarray;
JSONObject jobject;
RequestParams params;
ListView lv;
EditText enter;
Button done;
Button call;
ArrayList<String> place;
ArrayList<String>incharge;
ArrayList<String>email;
ArrayList<String>phone;
ArrayList<String>reg;
ArrayList<String>Bld;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.blood);
//prof=(EditText)findViewById(R.id.userProfile);
client = new AsyncHttpClient();
params = new RequestParams();
// submit=(Button)findViewById(R.id.submit);
lv = (ListView) findViewById(R.id.List_all_blood);
enter=(EditText)findViewById(R.id.enter_bld);
done=(Button)findViewById(R.id.enter_blood);
place = new ArrayList<String>();
incharge = new ArrayList<String>();
email = new ArrayList<String>();
phone = new ArrayList<String>();
reg = new ArrayList<String>();
Bld = new ArrayList<String>();
// final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl2);
// findViewById(R.id.rl1).setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(rl.getWindowToken(), 0);
//
// }
// });
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
place.clear();
incharge.clear();
email.clear();
phone.clear();
reg.clear();
String pl=enter.getText().toString();
params.put("place",pl);
client.get("http://srishti-systems.info/projects/accident/bloodsearch.php?", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String content) {
// TODO Auto-generated method stub
super.onSuccess(content);
System.out.println(content + "jjjjj");
try {
jobject = new JSONObject(content);
Log.e(content, "hgsfdh");
String s = jobject.optString("Result");
Log.e(content,"dsfds");
if(s.equals("success")){
// SharedPreferences pref=getApplicationContext().getSharedPreferences("pref",MODE_PRIVATE);
// temp=pref.getString("user","");
// String a = jobject.optString("PoliceDetails");
jarray =jobject.getJSONArray("BloodDoner");
for (int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
String FN = obj.getString("firstname");
place.add("First Name :" + FN);
String LN = obj.getString("lastname");
incharge.add("Second Name :" + LN);
String mail = obj.getString("email");
email.add("Email :" + mail);
String ph = obj.getString("phone");
phone.add("Phone :" + ph);
String bd = obj.getString("bloodgrp");
Bld.add("BLood Group :" + bd);
}
}
else
Toast.makeText(getApplicationContext(),"No Donors Found",Toast.LENGTH_LONG).show();
adapter adpt = new adapter();
lv.setAdapter(adpt);
} catch (Exception e) {
}
}
});
}
});
}
public void hideKeyboard(View view) {
InputMethodManager imm =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class adapter extends BaseAdapter {
LayoutInflater Inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return place.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Inflater=(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=Inflater.inflate(R.layout.blood_lst,null);
Viewholder holder=new adapter.Viewholder();
holder.pl=(TextView)convertView.findViewById(R.id.bld_name);
holder.pl.setText(place.get(position));
holder.in=(TextView)convertView.findViewById(R.id.bld_nm);
holder.in.setText(incharge.get(position));
holder.em=(TextView)convertView.findViewById(R.id.bld_em);
holder.em.setText(email.get(position));
holder.ph=(TextView)convertView.findViewById(R.id.bld_phn);
holder.ph.setText(phone.get(position));
holder.ph=(TextView)convertView.findViewById(R.id.bld_grp);
holder.ph.setText(Bld.get(position));
return convertView;
}
class Viewholder{
TextView pl;
TextView in;
TextView em;
TextView ph;
}
}
}
xml of the page :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rl2"
android:background="#9e9e9e">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/List_all_blood"
android:layout_below="#+id/enter_bld"
/>
<EditText
android:hint="enter place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_bld"
android:layout_weight="1"
android:layout_marginTop="49dp"
android:textColor="#000000"
android:textStyle="italic"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/enter_policebutton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="done"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:textColor="#FFFFFF"
android:background="#3F51B5"
android:layout_marginRight="34dp"
android:layout_marginEnd="34dp"
android:id="#+id/enter_blood"
style="#style/Widget.AppCompat.Button"
android:layout_alignBaseline="#+id/enter_bld"
android:layout_alignBottom="#+id/enter_bld"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/enter_blood"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="11dp"
android:text="Blood Doners" />
</RelativeLayout>
xml of the list :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9e9e9e">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="25dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_name" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginLeft="30dp"
android:textSize="15dp"
android:textColor="#000000"
android:id="#+id/bld_nm"
android:layout_below="#+id/bld_name" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_em" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_phn" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_grp" />
</TableLayout>
For call button in listview you can add call button icon in listview's row file like below:-
<Button
android:id="#+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call" />
Then in activity, you can write below code in on click of call button to call functionality in android:-
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("phone number"));
startActivity(callIntent);
phone number in above code is a string var in which you can add number which you want to call.
I hope it will help you.
Although a developer for more years than I can remember I'm new to Java/Android and the whole OOP thing... Yes we do still exist... shambling relics of a more sequential age...!!
Anyway I have a fragment which invokes a CursorAdapter to populate a ListView.
The ListView has several TextViews and two buttons on each row.
I have been trying to set up listeners on each of the buttons so far without success...
I've searched this forum (and others) and I've used several bits of code suggested by contributors..
From my research my biggest problem seems to be that I'm doing all this from a Fragment.
My question is how do I pass the base ListView id from the Fragment to the Adapter...???
My ListView Child XML...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_marginRight="#dimen/textViewMarginRight"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="12345678"
android:id="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="abcdef"
android:id="#+id/from_location"
android:layout_toRightOf="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Blanchardstown"
android:id="#+id/to_location"
android:layout_toRightOf="#+id/from_location"
/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/job_bid"
android:text="#string/joblist_bid"
android:layout_below="#+id/job_id"
android:layout_toLeftOf="#+id/job_details"
/>
<Button
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/job_details"
android:text="#string/joblist_details"
android:layout_below="#+id/to_location"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
My ListView Parent XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_marginRight="#dimen/textViewMarginRight"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="12345678"
android:id="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="abcdef"
android:id="#+id/from_location"
android:layout_toRightOf="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Blanchardstown"
android:id="#+id/to_location"
android:layout_toRightOf="#+id/from_location"
/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/job_bid"
android:text="#string/joblist_bid"
android:layout_below="#+id/job_id"
android:layout_toLeftOf="#+id/job_details"
/>
<Button
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/job_details"
android:text="#string/joblist_details"
android:layout_below="#+id/to_location"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
My Fragment Code
public class jobListFragment extends ListFragment
{
private final String m_LogcatTag = "assignment5";
public ListView m_jobListView;
public JobDataAdpter m_jobDataAdapter;
JobsDataSource m_datasource;
private SQLiteDatabase m_database;
CursorAdapter m_cursoradaptor;
public View m_jobListFragmentBaseView;
Cursor m_cursor;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
m_jobListFragmentBaseView = inflater.inflate(layout.joblistfragment, container, false);
ListView m_jobListView = (ListView)m_jobListFragmentBaseView.findViewById(android.R.id.list);
//Declare an object to handle database I-O and open a channel to the database
m_datasource = new JobsDataSource (getActivity().getApplicationContext());
m_datasource.open();
m_cursor = m_datasource.getAllJobs();
m_jobDataAdapter = new JobDataAdpter(getActivity().getApplicationContext(), m_cursor, 0);
m_jobListView.setAdapter(m_jobDataAdapter);
return m_jobListFragmentBaseView;
}
My Adapter Code
public class JobDataAdpter extends CursorAdapter
{
private final String mLogcatTag = "assignment5";
protected ListView mListView; THIS IS THE VARIABLE IN QUESTION
public JobDataAdpter(Context context, Cursor cursor, int flags )
{
super(context, cursor, 0);
}
protected static class RowViewHolder
{
public TextView m_job_bid;
public TextView m_job_details;
}
//End New Code\
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
View view = View.inflate(context, R.layout.jobslistlayout, null);
RowViewHolder holder = new RowViewHolder();
holder.m_job_bid = (TextView) view.findViewById(R.id.job_bid);
holder.m_job_details = (TextView) view.findViewById(R.id.job_details);
holder.m_job_bid.setOnClickListener(m_OnBidClickListener);
holder.m_job_details.setOnClickListener(m_OnDetailsClickListener);
view.setTag(holder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView m_job_IdView = (TextView) view.findViewById(R.id.job_id);
TextView m_from_LocationView = (TextView) view.findViewById(R.id.from_location);
TextView m_to_LocationView = (TextView) view.findViewById(R.id.to_location);
// Extract properties from cursor
long row_id = cursor.getLong((cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_ID)));
String m_job_id = cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_JOB_ID));
String m_From_Location = cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_JOB_FROM_LOCATION));
String m_To_Location = cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_JOB_TO_LOCATION));
// Populate fields with extracted properties
m_job_IdView.setText(m_job_id);
m_from_LocationView.setText(String.valueOf(m_From_Location));
m_to_LocationView.setText(String.valueOf(m_To_Location));
}
private View.OnClickListener m_OnBidClickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{ HERE IS WHERE THE VARIABLE IS USED
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(mLogcatTag, "Title clicked, row %d" + position);
}
};
private View.OnClickListener m_OnDetailsClickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(mLogcatTag, "Text clicked, row %d" + position);
}
};
}
OK guys .....That's it.... Hope you can help
I am working on an Android project in which I am currently working on chat functionality. Now, whenever an user sends a message, it is added in the ListView, which is populated by BaseAdapter. A new message is added by baseAdapterObject.add(item);.
Now, whenever an user sends a message, I am adding it directly to the already existing List and then waiting for a reply from the server confirming the message was delivered. For the first step, I would like to show a Gray checkmark, and for 2nd message received from server, I would like to show Blue checkmark.
Unfortunately, I don't know how to access the already populated list and change the background image of an ImageView. . Each message has a random-number, with which I can compare for which message I received confirmation.
Code :
public void recieveUpdatedMessageFromServer(String channelName, Map<String, Object> input){
String randomNumberFromServer = ((Map) input.get("data")).get("random").toString();
if (randomNumberFromServer.equals(randomNos)) {
messageRecieved = true;
randomNos = "";
}
chatMessagesAdapter.add(insertMap);
runOnUiThread(new Runnable() {
#Override
public void run() {
chatMessagesAdapter.notifyDataSetChanged();
}
});
public class ChatMessagesAdapter extends BaseAdapter {
private Activity activity = null;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void add(HashMap<String, String> item) {
data.add(item);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chat_messages_row, parent, false);
TextView chatText = (TextView) vi.findViewById(R.id.chatText);
ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
TextView firstName = (TextView) vi.findViewById(R.id.personName);
ImageView checkMark = (ImageView) vi.findViewById(R.id.checMarkChat);
HashMap<String, String> chatList;
chatList = data.get(position);
chatText.setText(chatList.get(ChatMessagesActivity.chatText));
checkMark.setBackgroundResource(R.drawable.blue_icon);
firstName.setText(chatList.get(ChatMessagesActivity.firstName));
if (!(chatList.get(ChatMessagesActivity.chatImageId).equals("0"))) {
Picasso.with(context).load(StaticRestTemplate.baseURL + "image/" + chatList.get(ChatMessagesActivity.chatImageId)).fit().into(userImage);
}
return vi;
}
}
}
chat_messages_row.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="130dp"
android:orientation="horizontal"
android:padding="2.5dip">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="125dp"
android:id="#+id/frameLayout2">
<ImageView
android:id="#+id/chatImage"
android:layout_width="107dp"
android:layout_height="107dp"
android:padding="2dp" />
</FrameLayout>
<TextView
android:id="#+id/chatText"
android:layout_width="230dp"
android:layout_height="76dp"
android:layout_gravity="right|center_vertical"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/frameLayout2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/personName"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/chatText"
android:layout_alignEnd="#+id/chatText"
android:layout_toRightOf="#+id/textView"
android:layout_toEndOf="#+id/textView"
/>
<ImageView
style="?android:attr/buttonStyleSmall"
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/checMarkChat"
android:background="#drawable/blue_icon"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/personName"
android:layout_alignEnd="#+id/personName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="49dp"
android:layout_marginStart="49dp"
android:layout_marginTop="208dp" />
</RelativeLayout>
I hope this much information is enuf. Kindly let me know if anything else required. Thank you. :-)
Consider using a class object to help.
For example, you can create a list of message objects:
class Message {
private String message;
private boolean gray_tick;
private boolean blue_tick;
....
}
Change your hashmap in your BaseAdapter to take in the corresponding object.
private ArrayList<HashMap<String, Message>> data;
From there, you can set your BaseAdapter to read these values and show the correct coloured ticks at the right time.
Hope this helps!
I have one list in which I have one image view .I need to show that image only when my one variable is true .Actually I make a custom adapter in which I have one variable "serviceAlertPresent" .If it is true I need to show image elese I don't want to show image on row.How I Will acheive this
Here is my code of each row .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#android:color/transparent"
android:padding="5dp" >
<TextView
android:id="#+id/item_platform"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:text="Ptf."
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/item_schDepart"
android:layout_width="35dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/item_platform"
android:layout_alignBottom="#+id/item_platform"
android:layout_toRightOf="#+id/item_platform"
android:text="dpt"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/item_arrival"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/item_schDepart"
android:layout_alignBottom="#+id/item_schDepart"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/item_expectdepart"
android:text="Arr."
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/item_expectdepart"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_below="#+id/item_schDepart"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/item_platform"
android:text="Expert"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/item_expertarrival"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/item_expectdepart"
android:layout_alignBottom="#+id/item_expectdepart"
android:layout_alignLeft="#+id/item_arrival"
android:text="exprt Arrival"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/item_stationName"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/item_arrival"
android:layout_alignBottom="#+id/item_arrival"
android:layout_marginLeft="17dp"
android:layout_toRightOf="#+id/item_expertarrival"
android:text="Des."
android:ellipsize="end"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/alertStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="0dp"
android:layout_toRightOf="#+id/item_stationName"
android:src="#drawable/alert_icon" />
</RelativeLayout>
here is custom adapter
public class CustomListAdapter extends BaseAdapter{
ArrayList<deparaturedaseboarddto> deparaturedaseboarddto;
private Context context;
public CustomListAdapter( Context context, ArrayList<deparaturedaseboarddto> deparaturedaseboarddto){
this.deparaturedaseboarddto=deparaturedaseboarddto;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return deparaturedaseboarddto.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return deparaturedaseboarddto.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = mInflater.inflate(R.layout.row_listitem, null);
}
final TextView platFormName = (TextView) v
.findViewById(R.id.item_platform);
final TextView schDepart = (TextView) v
.findViewById(R.id.item_schDepart);
final TextView expDepart = (TextView) v
.findViewById(R.id.item_expectdepart);
final TextView arrival = (TextView) v
.findViewById(R.id.item_arrival);
final TextView exparrival = (TextView) v
.findViewById(R.id.item_expertarrival);
final TextView stationName = (TextView) v
.findViewById(R.id.item_stationName);
final String platformValue = deparaturedaseboarddto.get(position).getPlatformNo();
final String schDepartValue= deparaturedaseboarddto.get(position).getSchDepart();
final String schExpectValue= deparaturedaseboarddto.get(position).getExpDepart();
final String arrivalValue= deparaturedaseboarddto.get(position).getDestSchArrival();
final String exparrivalValue= deparaturedaseboarddto.get(position).getDestSchArrival();
String stationNameValue= deparaturedaseboarddto.get(position).getDestinationStation().getStationName();
platFormName.setText(platformValue);
schDepart.setText(schDepartValue);
expDepart.setText(schExpectValue);
arrival.setText(arrivalValue);
exparrival.setText(exparrivalValue);
stationName.setText(stationNameValue);
return v;
}
public void referhList( ArrayList<deparaturedaseboarddto> deparaturedaseboarddto){
this.deparaturedaseboarddto=deparaturedaseboarddto;
notifyDataSetChanged();
}
}
I am asking this image view
<ImageView
android:id="#+id/alertStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="0dp"
android:layout_toRightOf="#+id/item_stationName"
android:src="#drawable/alert_icon" />
I need to show this when "serviceAlertPresent" .I will get value like that deparaturedaseboarddto.get(position).isServiceAlertPresent()
In the adapter get the imageView and set the visibilite to INVISIBLE or VISIBLE.
final ImageView alertStatus = (ImageView) v
.findViewById(R.id.alertStatus);
if (condition){
alertStatus.setVisibility(View.VISIBLE);
}
else{
alertStatus.setVisibility(View.INVISIBLE);
}
And when the condition change, you should call notifyDataSetChanged() of your adapter.
Hope it helps you!
You can check boolean values of serviceAlertPresent inside getView() method itself.
If it's true then use mImageView.setVisibility(View.VISIBLE) else remove the presence of it by using mImageView.setVisibility(View.GONE).
Note: When you use GONE, it will be invisible and at the same time it will not take any space, where as when you use INVISIBLE it will be invisible and will take space in layout.
In ImageView, set android:setVisiblity="gone"; by default.
show that image only when your variable is true.
like,
imageView.setVisibility(View.GONE);
final ImageView alertStatus= (ImageView) v.findViewById(R.id.alertStatus);
v.alertStatus.setVisibility(View.INVISIBLE);