inserting call button in list view - java

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.

Related

How to add multiple values inside 1 list view and style it approriatle

I want to be able to add multiple values on a list but properly style the list view.
For example right now the list view will look like this:
namepostcodedate
which is because of the following code
ListArray.add(jobs.get(finalJ).customer.getName() + job.getPostcode() + job.getDate());
The way that I am currently adding the values in the ListArray doesn't seem ideal but I am not sure if there is another way to do this and display the list formated?
This is my list_item file
<?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="horizontal"
android:padding="5dip">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TableRow
android:id="#+id/rows2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ddOrangeLight"
android:showDividers="middle">
<!-- android:divider="?android:attr/dividerHorizontal"-->
<TextView
android:id="#+id/customerNameView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginStart="4sp"
android:layout_marginTop="10dp"
android:layout_marginEnd="4sp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</RelativeLayout>
My adapter class
public class SearchableAdapter extends BaseAdapter implements Filterable {
private List<String>originalData = null;
private List<String>filteredData = null;
private final LayoutInflater mInflater;
private final ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<String> data) {
this.filteredData = data ;
this.originalData = data ;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.uName = (TextView) convertView.findViewById(R.id.customerNameView);
// holder.uPostCode = (TextView) convertView.findViewById(R.id.postCode);
// holder.UDateTime = (TextView) convertView.findViewById(R.id.dateTimeView);
// Bind the data efficiently with the holder.
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// If weren't re-ordering this you could rely on what you set last time
// holder.text.setText(filteredData.get(position));
holder.uName.setText(filteredData.get(position));
// holder.uPostCode.setText(filteredData.get(position));
// holder.UDateTime.setText(filteredData.get(position));
return convertView;
}
static class ViewHolder {
TextView uName;
// TextView uPostCode;
// TextView UDateTime;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
Fragment class
public class CompletedJobsFragment extends Fragment {
AppActivity a;
String search;
TableLayout tableLayout;
Vehicle vehicle;
ListView listView;
SearchableAdapter arrayAdapter;
EditText searchInput;
List<String> ListArray = new ArrayList<String>();
ArrayList<ListItem> results = new ArrayList<>();
ListItem repairDetails = new ListItem();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_completed_jobs,container,false);
a = (AppActivity) getActivity();
assert a != null;
tableLayout = (TableLayout) v.findViewById(R.id.completedJobsTable);
Button clear = v.findViewById(R.id.btnClearTextCarReg);
searchInput = v.findViewById(R.id.txtEditSearchCarReg);
listView = v.findViewById(R.id.list__View);
search = searchInput.getText().toString().trim();
clear.setOnClickListener(av -> searchInput.setText(""));
// Button searchButton = v.findViewById(R.id.btnSearchVehicleReg);
arrayAdapter = new SearchableAdapter(getContext(),ListArray);
listView.setAdapter(arrayAdapter);
listView.setClickable(true);
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
arrayAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
JobRepository jobRepository = new JobRepository(a.getApplication());
VehicleRepository vehicleRepository = new VehicleRepository(a.getApplication());
jobRepository.findCompleted().observe(getViewLifecycleOwner(), jobs -> {
for (int j = 0; j < jobs.size(); j++) {
if (jobs.get(j).job == null) {
continue;
}
int finalJ = j;
vehicleRepository.findByJob(jobs.get(j).job.getUuid()).observe(getViewLifecycleOwner(), vehicles -> {
for (int vh = 0; vh < vehicles.size(); vh++) {
if (vehicles.get(vh).vehicle == null) {
continue;
}
vehicle = vehicles.get(vh).vehicle;
Job job = jobs.get(finalJ).job;
ListArray.add(jobs.get(finalJ).customer.getName() + job.getPostcode() + job.getDate());
View viewToAdd = arrayAdapter.getView(finalJ, null, null);
TableRow[] tableRows = new TableRow[jobs.size()];
tableRows[finalJ] = new TableRow(a);
tableRows[finalJ].setId(finalJ + 1);
tableRows[finalJ].setPadding(0, 20, 0, 20);
tableRows[finalJ].setBackgroundResource(android.R.drawable.list_selector_background);
tableRows[finalJ].setBackgroundResource(R.drawable.table_outline);
tableRows[finalJ].setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT
));
tableRows[finalJ].addView(viewToAdd);
tableLayout.addView(tableRows[finalJ], new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT
));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text or do whatever you need.
// Toast.makeText(getContext(), "asd", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString(JOB_ID, job.getUuid().toString());
bundle.putString(CUSTOMER_NAME, jobs.get(finalJ).customer.getName());
// bundle.putString(JOB_DATE, sdf.format(job.getDate()));
Fragment fragment = new ViewCustomerInformationFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
}
});
}
});
return v;
}
Fragment xml file
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imageViewBGhm"
android:scaleType="center"
android:orientation="vertical"
android:background="#color/white">
<TextView
android:id="#+id/txtTitle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="180dp"
android:text="#string/completed_jobs"
android:textColor="#color/ddGrey"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.375"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/txtEditSearchCarReg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/txtTitle2"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="16dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="16dp"
android:ems="12"
android:inputType="textPersonName"
android:paddingStart="5dp"
android:paddingEnd="10dp"
android:paddingBottom="22dp"
android:textAlignment="textStart"
android:textSize="18sp" />
<TableRow
android:id="#+id/tableTitleRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtEditSearchCarReg"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="20dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="6dp"
android:background="#color/lightGrey"
android:divider="?android:attr/dividerHorizontal"
android:showDividers="middle"
android:visibility="visible">
<TextView
android:id="#+id/txtCustomerNameTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginStart="4sp"
android:layout_marginTop="10dp"
android:layout_marginEnd="4sp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/customer_name_hc"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtPostcodeTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/postcode_placeholder"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtDateTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/date"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtTimeTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginEnd="20sp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/enquiry_vat_value"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
</TableRow>
<ListView
android:id="#+id/list__View"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="#id/tableTitleRow"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:visibility="visible" />
<TableLayout
android:id="#+id/completedJobsTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/txtEditSearchCarReg"
android:layout_marginStart="2dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="2dp"
android:layout_marginBottom="2dp"
android:stretchColumns="0,1,2"
android:visibility="gone">
</TableLayout>
<Button
android:id="#+id/btnClearTextCarReg"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignTop="#+id/txtEditSearchCarReg"
android:layout_alignParentEnd="true"
android:layout_marginStart="175dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="20dp"
android:background="#drawable/ic_outline_cancel_24"
android:backgroundTint="#color/ddOrange"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground" />
<Button
android:id="#+id/btnSearchVehicleReg"
style="#style/DDButtons"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/txtEditSearchCarReg"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="14dp"
android:background="#drawable/custom_buttons"
android:drawableStart="#drawable/ic_outline_search_24"
android:drawablePadding="12dp"
android:letterSpacing="0.2"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:singleLine="true"
android:text="#string/search_postcode"
android:textAlignment="textStart"
android:textSize="18sp"
android:textStyle="bold"
android:visibility="gone"/>
</RelativeLayout>

listview not getting displayed

I am trying to filter data from database and display filtered data into listview using cursor. Unfortunately, the cursor is returned from the query isn't empty but the items not getting displayed in the activity.And moreover, there's no error being displayed in the logcat.
My search_results.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search__results);
lview = (ListView) findViewById(R.id.list);
Intent intent = getIntent();
String from = intent.getStringExtra("from");
String to = intent.getStringExtra("to");
// String date = intent.getStringExtra("date");
// String clas = intent.getStringExtra("class");
myrailway = new no.nordicsemi.android.nrftoolbox.myRailwayAdapter(this);
// Cursor cursor = myrailway.getTrainDetails(from, to);
String[] FROM = null;
String[] TO = null;
String[] TRAINNAME = null;
String[] TRAINNO = null;
String[] DEPART = null;
String[] ARRIVAL = null;
Cursor cursor = myrailway.getTrainDetails(from, to);
if(cursor != null) {
Log.e("ERROR","NON EMPTY CURSOR");
int count = 0;
if (cursor.moveToFirst()) {
Log.e("ERROR","ENTERED LOOP");
do {
String stnfrom = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_STNFROM));
String stnto = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_STNTO));
String trainname = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_NAME));
String trainno = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_TRAINNUM));
String depart = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_DEPART));
String arrival = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_ARRIVAL));
FROM[count] = stnfrom; Log.e("fr",stnfrom);
TO[count] = stnto; Log.e("too",stnto);
TRAINNAME[count] = trainname; Log.e("trainanme",trainname);
TRAINNO[count] = trainno; Log.e("trainno",trainno);
DEPART[count] = depart; Log.e("depart",depart);
ARRIVAL[count] = arrival; Log.e("arrival",arrival);
count = count + 1;
cursor.close();
} while (cursor.moveToNext());
lviewAdapter = new ListViewAdapter(this, FROM, TO, DEPART, ARRIVAL, TRAINNAME, TRAINNO);
lview.setAdapter(lviewAdapter);
}
}
else
Log.e("ERROR","EMPTY CURSOR");
}
My ListViewAdapter.java:
public class ListViewAdapter extends BaseAdapter {
Activity context;
String from[];
String to[];
String depart[];
String arrival[];
String trainname[];
String trainno[];
private no.nordicsemi.android.nrftoolbox.myRailwayAdapter myrailway;
public ListViewAdapter(Activity context, String[] from, String[] to, String[] depart, String[] arrival, String[] trainname, String[] trainno) {
super();
this.context = context;
this.from = from;
this.to = to;
this.depart = depart;
this.arrival = arrival;
this.trainname = trainname;
this.trainno = trainno;
}
#Override
public int getCount() {
return depart.length;
}
#Override
public Object getItem(int i) {
return depart[i];
}
#Override
public long getItemId(int i) {
myrailway = new no.nordicsemi.android.nrftoolbox.myRailwayAdapter(this.context);
Long recc= Long.valueOf(0);
Cursor c= myrailway.getpass(trainname[i]);
if(c!=null)
{
c.moveToFirst();
recc=c.getLong(0);
}
return recc;
}
private class ViewHolder {
TextView txtfrom;
TextView txtto;
TextView txttrainno;
TextView txttrainname;
TextView txtdepart;
TextView txtarrival;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null)
{
view = inflater.inflate(R.layout.listview_items, null);
holder = new ViewHolder();
holder.txtfrom = (TextView) view.findViewById(R.id.from);
holder.txtto = (TextView) view.findViewById(R.id.to);
holder.txttrainno = (TextView) view.findViewById(R.id.trainno);
holder.txttrainname = (TextView) view.findViewById(R.id.trainname);
holder.txtdepart = (TextView) view.findViewById(R.id.depart);
holder.txtarrival = (TextView) view.findViewById(R.id.arrival);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
holder.txtfrom.setText(from[position]);
holder.txtto.setText(to[position]);
holder.txttrainno.setText(trainno[position]);
holder.txttrainname.setText(trainname[position]);
holder.txtdepart.setText(depart[position]);
holder.txtarrival.setText(arrival[position]);
return view;
}
}
My search_results.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="no.nordicsemi.android.nrftoolbox.Search_Results">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</RelativeLayout>
My listview_items.xml:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="0dip" android:layout_gravity="top"
>
<TableRow>
<TextView
android:id="#+id/from"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:textColor="#000000"
android:layout_span="1"
/>
<TextView
android:id="#+id/to"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:textColor="#000000"
android:layout_span="1"
/>
</TableRow>
<TableRow>
<TextView
android:text=""
android:id="#+id/trainno"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
<TextView
android:text=""
android:id="#+id/trainname"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
</TableRow>
<TableRow>
<TextView
android:text=""
android:id="#+id/depart"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
<TextView
android:text=""
android:id="#+id/arrival"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
</TableRow>
</TableLayout>
<Button
android:id="#+id/book"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:onClick="book"
android:text="BOOK">
</Button>
</TableRow>
</TableLayout>
Now, the cursor isn't empty but the listview is not displayed by the listview adapter.
Can someone point out the error in the code??
Please use this.
#Override
public int getCount() {
//here too;
return depart.lenght;
}
#Override
public Object getItem(int i) {
//there is error: repalce return null; with
return depart[i];
}
#Override
public long getItemId(int i) {
//change this too
return depart[i].getId();
}
I can see 2 reasons that this may happen:
You arrays are not filled with data/or filled with empty data and that the reason they are not presented. (less likely because you would receive a null pointer exception when you try to access a null location in the array)
Your row layout doesn't show data parameters. (I will be
on this reason, please show you row layout XML(listview_items.xml) so that we could check
it)
Check: Make a check and print to the log all the data from 6 the arrays for every row before you set the data in the getView method.
getCount(), getItem() and getItemId() are not set properly.
getCount() should return the number of items in the arraylist;
getItem() should return the item at the given position from the arraylist;
getItemId() should return the internal id of the item if it has one, or the position of the item in the array or an hash number of the item.

Add Progress bar while data loading from database

I use volley library to get data from database i use this code
public class R_arabic extends AppCompatActivity {
RequestQueue requestQueue;
ListView listView;
ArrayList<listitem_gib> listitems = new ArrayList<listitem_gib>();
String name, img, url, num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_arabic);
listView = (ListView) findViewById(R.id.listView);
TextView textView_Title = (TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
String story_type = intent.getStringExtra("story_type");
switch (story_type) {
case "arabic":
textView_Title.setText("arabic");
break;
case "romance":
textView_Title.setText("romance");
break;
case "motrgm":
textView_Title.setText("motrgm");
break;
case "ro3b":
textView_Title.setText("ro3b");
break;
case "siasa":
textView_Title.setText("siasa");
break;
}
String url = "http://grassyhat.com/android/" + story_type + ".php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
listitems.add(new listitem_gib(id, name, img, url, num));
}
} catch (JSONException e) {
e.printStackTrace();
}
listAllItme();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(R_arabic.this, "no connection", Toast.LENGTH_LONG).show();
} else {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
showad++;
if (showad >= 5) {
showad = 0;
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
i want to add progress bar while data loading to avoid blank page
sorry i'm new in android and i google for that and don't get useful answer
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kamal.ahmed.rewaya.R_arabic"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#drawable/bg"
tools:showIn="#layout/app_bar_r_arabic">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:id="#+id/textView2" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingRight="#dimen/activity_horizontal_margin"
android:divider="#drawable/div1"
android:dividerHeight="35dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="gone">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
Add progressBar in your activity_r_arabic
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
add ProgessBar progressBar; as global variable in your activity
and initialise it as
progressBar = (ProgessBar) findViewById(R.id.progress_bar);
and then In onResponse(JSONObject response) method add following line
progressBar.setVisibility(View.GONE)
EDIT
Make your linearLayout visible in xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
and inside onResponse(JSONObject response) method add following line
progress_layout.setVisibility(View.GONE)

how to show default list in spinner in android

Recently I developed one app. In this, The values are retrieved from the MySQL data base into the spinner. The problem is that it crashes when internet is not present. My intention is, if the internet is not present show default values. Otherwise if the internet is available show the values from MySQL database.
public class MilkProduction extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private EditText quantity;
private Button submit, cancel;
private TextView date_time;
Calendar calander;
SimpleDateFormat simpleDateFormat;
String time;
private AutoCompleteTextView animal_id;
private List<Animal> fruits ;
Boolean isInternetPresent = false;
private ConnectionDetector cd;
private Spinner spinner1;
private String shift_id;
private String product;
String shiftid="",intime="",outtime="";
//JSON Array
private JSONArray result;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private Animal item ;
private Animal animal=new Animal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.milk_production);
animal_id = (AutoCompleteTextView) findViewById(R.id.edt_animal_id);
quantity = (EditText) findViewById(R.id.edt_milkproduction_quan);
date_time = (TextView) findViewById(R.id.txt_timt_date_year);
submit = (Button) findViewById(R.id.btn_prodc_submit);
calander = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
time = simpleDateFormat.format(calander.getTime());
date_time.setText(time);
date_time.setTextSize(15);
students = new ArrayList<String>();
spinner1 = (Spinner) findViewById(R.id.spinner);
spinner1.setOnItemSelectedListener(this);
cd = new ConnectionDetector(getApplicationContext());
//Calling the method that will fetch data
proautocomplete();
prodropdown();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
insertUser();
}
else{
showAlertDialog(MilkProduction.this, "Internet not available",
"Internet is not available in this device", false);
}
}
});
}
private void prodropdown() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser1( new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
String detailsString = Others.getStringFromRetrofitResponse(response);
try {
//Parsing the fetched Json String to JSON Object
JSONObject j = new JSONObject(detailsString);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
private void getStudents(JSONArray j) {
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MilkProduction.this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
private String getShiftid(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
// name = json.getString(Config.TAG_NAME);
name = animal.setShiftid(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getIntime(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
// course = json.getString(Config.TAG_COURSE);
course= animal.setIntime(json.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getOuttime(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
// session = json.getString(Config.TAG_SESSION);
session= animal.setOuttime(json.getString(Config.TAG_SESSION));
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String spin = parent.getItemAtPosition(position).toString();
//Setting the values to textviews for a selected item
shiftid=(getShiftid(position));
intime=(getIntime(position));
outtime=(getOuttime(position));
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
shiftid="";
intime="";
outtime="";
}
private void insertUser() {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading","Please wait...",false,false);
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser(
animal_id.getText().toString(),
quantity.getText().toString(),
date_time.getText().toString(),
spinner1.getSelectedItem().toString(),
" ",
shiftid,
intime,
outtime,
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
loading.dismiss();
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MilkProduction.this, output, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
loading.dismiss();
Toast.makeText(MilkProduction.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
}
Layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/mm"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/dairy_layout_height"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:layout_marginTop="25dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:background="#drawable/corner3"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="13dp"
android:layout_gravity="center"
>
<TextView
android:id="#+id/heder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Milk Production"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="5dp"
android:textSize="25sp"
android:textColor="#color/textcolour"
/>
<View
android:layout_width="250dp"
android:layout_height="2dip"
android:background="#023e64"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_shfit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shift : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
android:layout_marginTop="12dp"
/>
<Spinner
android:layout_width="160dp"
android:layout_height="50dp"
android:id="#+id/spinner"
android:layout_gravity="center_horizontal"
android:spinnerMode="dialog"
android:prompt="#string/shift_prompt"
android:background="#android:drawable/btn_dropdown"
android:entries="#array/android_dropdown_arrays1"
style="#android:style/Widget.Holo.Light.Spinner"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Animal : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<AutoCompleteTextView
android:id="#+id/edt_animal_id"
android:layout_width="160dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:layout_alignParentLeft="true"
android:ems="10"
android:text="">
</AutoCompleteTextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_milk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<EditText
android:id="#+id/edt_milkproduction_quan"
android:layout_width="121dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:inputType="number"
android:ems="10"
/>
<TextView
android:id="#+id/txt_milk_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Lts."
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
>
<TextView
android:id="#+id/btn_prodc_submit"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="#dimen/button_sub_txt_size"
android:layout_margin="#dimen/button_layout_margin"
android:background="#drawable/btnbackground"
android:textColor="#color/textcolour"
/>
</LinearLayout>
</LinearLayout>
</ScrollView>
I think should try something like that to show the default values if no internet, else get the values of the sql
if(cd.isConnectingToInternet()){
prodropdown();
}else{
//Setting adapter to show the items in the spinner
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("default value 1");
spinnerArray.add("default value 2");
spinnerArray.add("default value 3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
}

Listview and sharedprefs

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

Categories