I used this code for a button, after that I am in the Contacts Activity:
btnPhonebook.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent pb = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(pb, 1);
}
});
After that, there is a contact list with many contacts. Now I want that, whenever I clicked to a contact, a dialog is displayed. How can I do that. Could anyone help me because currently I have no issue how to make it. I have tried with this code but it did not work.
Dialog dialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a phone number");
ListView lp = new ListView(this);
lp.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, _listPhoneNumber));
builder.setView(lp);
dialog = builder.create();
Also I put the above code in onActivityResult() method.
Thanks in advance.
Instead of using the Built in Intent to display contacts.. why don't you build the List yourself and then do what you plan to do.
OR
Did you set your dialog to .show()?
It is very simple,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your loading code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
You cannot show Dialog in native Contacts app.
However you can fetch Contacts by yourself and show them in a ListView with CheckBox and proceed to next step.
Here is a simplest ListView to show contacts. you can edit it by yourself.
I Have did this in my application how we can get contact detail from listview ,
using this Data you can Display your dialog.
lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView <? > arg0, View arg1, int position, long arg3) {
Object o = lv.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), o.toString(), Toast.LENGTH_LONG).show();
String infoString = o.toString();
String arr[] = infoString.split(",");
String names[] = arr[1].split("=");
id = Integer.parseInt(names[1]);
System.out.println("info" + id);
db = dh.getReadableDatabase();
String select = "select * from '" + dh.tablename + "' WHERE adb_id='" + id + "' ";
Cursor c = db.rawQuery(select, null);
if (c.moveToFirst()) {
name.setText(c.getString(1));
address.setText(c.getString(2));
contact.setText(c.getString(3));
}
}
});
If you want to use dialog in contact then you have to make your own custom layout for contact.. See below code for example...
on button click
public static final int NUMBER_SELECT = 1;
Intent intent = new Intent(clsBlockNumbers.this,CallLog_Activity.class);
startActivityForResult(intent,NUMBER_SELECT);
in the same Activity write/make onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case NUMBER_SELECT:
if (resultCode == RESULT_OK) {
String number = data.getStringExtra("SelectedNumber");
if(number == null)
{
Toast.makeText(this, "No Record found: ", Toast.LENGTH_LONG).show();
}
else
{
//Your code
}
break;
}
}
}
CallLog_Activity.java
package com.demo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class CallLog_Activity extends Activity implements OnItemClickListener
{
ArrayList<String> strAyyNumber,strAyyType,listNumber, strType, strAyyName ;
private CallLogListAdapter adapter ;
CallLog callLog;
String noType;
ListView listCallLog;
private String[] listCallLog_arr={};
Cursor cursor;
String strArr;
TextView tv, tv1, txtEmptyMsg;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.calllog_list);
callLog = new CallLog();
listCallLog = (ListView)findViewById(R.id.list);
strAyyNumber = new ArrayList<String>();
strAyyType = new ArrayList<String>();
strAyyName = new ArrayList<String>();
listNumber = new ArrayList<String>();
strType = new ArrayList<String>();
System.out.println("In Call log list activity");
try
{
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"),
projection,
selection,
selectionArgs,
sortOrder);
if (cursor != null)
{
//Loop through the call log.
while (cursor.moveToNext())
{
//Common Call Log Items
String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
strAyyNumber.add(callNumber);
String callType = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
strAyyType.add(callType);
String callName = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
strAyyName.add(callName);
}
for(int i=0;i<strAyyNumber.size();i++)
{
String no = strAyyNumber.get(i).toString();//.concat("\n").concat(strAyyType.get(i).toString());
Log.d("No length ", "No length ::" + no.length());
listNumber.add(no);
}
listCallLog_arr = listNumber.toArray(new String[listNumber.size()]);
Log.d("size", "list listCallLog_arr"+ listCallLog_arr.length);
if(!listNumber.isEmpty())
{
listCallLog.setVisibility(View.VISIBLE);
adapter = new CallLogListAdapter(CallLog_Activity.this,R.layout.calllog_list_row, listCallLog_arr,strAyyNumber,strAyyType,strAyyName);
listCallLog.setAdapter(adapter);
}
else
{
txtEmptyMsg = (TextView)findViewById(R.id.txtEmptyMsg);
txtEmptyMsg.setVisibility(View.VISIBLE);
txtEmptyMsg.setText("No Record found Press Back to Continue");
}
listCallLog.setOnItemClickListener(this);
}
listCallLog.setOnItemClickListener(this);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
{
String o = arg0.getItemAtPosition(position).toString();
Intent returnIntent = new Intent();
StringBuffer sb = new StringBuffer(o);
sb.reverse().setLength(10);
Log.d("Item click", "String buffer"+ sb);
String revercenum = sb.toString().trim();
Log.d("Item click", "revercenum "+ revercenum);
StringBuffer sb1 = new StringBuffer(revercenum);
sb1.reverse();
Log.d("Item click", "sb1 "+ sb1);
String revercenum1 = sb1.toString().trim();
revercenum1.replace("+", "");
Log.d("Item click", "revercenum 1"+ revercenum1);
returnIntent.putExtra("SelectedNumber",revercenum1.replace("+", ""));
setResult(RESULT_OK,returnIntent);
finish();
}
}
colllog_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:visibility="gone"
/>
<TextView android:id="#+id/txtEmptyMsg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:textStyle="bold"
android:textSize="25dp"
android:text=""
android:visibility="gone"
/>
</LinearLayout>
colllog_list_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="fill_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtCallLogName"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:textSize="20dp" android:layout_margin="10dp"
android:layout_weight="1" />
<TextView
android:id="#+id/txtCallLogNumber"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:textSize="20dp" android:layout_weight="1"
android:layout_marginLeft="10dp" android:layout_marginBottom="10dp"
android:layout_marginTop="5dp" android:layout_marginRight="10dp" />
</LinearLayout>
<TextView
android:id="#+id/txtCallLogType"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:textSize="12dp" android:layout_marginBottom="10dp"
android:layout_marginTop="10dp" android:layout_marginRight="10dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
CallLogListAdapter.java
package com.Demo;
import java.util.ArrayList;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CallLogListAdapter extends ArrayAdapter<Object>
{
private static final String TAG = "CallLogListAdapter";
private LayoutInflater inflater = null;
private int resource;
private Activity activity;
CallLog callLog ;
String[] strTemp;
ArrayList<String> arrayItem = new ArrayList<String>();
ArrayList<String> ayyType = new ArrayList<String>();
ArrayList<String> tempType = new ArrayList<String>();
ArrayList<String> ayyName = new ArrayList<String>();
ArrayList<String> tempName = new ArrayList<String>();
ArrayList<String> tempName1 = new ArrayList<String>();
ArrayList<String> tempNo = new ArrayList<String>();
String strType, strName, strName1, strNo ;
String[] tmpName, tmpName1, tmpNo;
public CallLogListAdapter(Activity activity, int resorce, String[] strTemp, ArrayList<String> arryListNumber, ArrayList<String> arryListType, ArrayList<String> arryListName)
{
super(activity, resorce,strTemp);
this.resource = resorce;
this.activity = activity;
this.strTemp = strTemp;
Log.d("in adapter", "In Adapter");
arrayItem = arryListNumber;
ayyType = arryListType;
ayyName = arryListName;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Log.d("in adapter", "In get View");
ViewHolder holder;
if (convertView == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(resource, parent, false);
holder = new ViewHolder();
holder.txtName = (TextView)convertView.findViewById(R.id.txtCallLogName);
holder.txtNumber = (TextView)convertView.findViewById(R.id.txtCallLogNumber);
holder.txtType = (TextView)convertView.findViewById(R.id.txtCallLogType);
holder.txtName.setVisibility(View.VISIBLE);
try
{
for(int i=0;i<ayyName.size();i++)
{
strName = ayyName.get(i);
Log.d("in get view in ", "Name is: **"+ strName);
tempName.add(strName);
}
tmpName = tempName.toArray(new String[tempName.size()]);
if(tmpName[position] == null)
{
holder.txtName.setVisibility(View.GONE);
}
else
{
holder.txtName.setVisibility(View.VISIBLE);
holder.txtNumber.setTextSize(12);
holder.txtName.setText(""+ tmpName[position]);
}
}
catch (NullPointerException e)
{
e.printStackTrace();
}
for(int i=0;i<arrayItem.size();i++)
{
strNo = arrayItem.get(i);//.toString();
Log.d("in get view in ", "Number is: **"+ strNo);
tempNo.add(strNo);
}
String[] tmpNo = tempNo.toArray(new String[tempNo.size()]);
Log.d("in get view ", "Number is String[]** : "+ tmpNo[position]);
holder.txtNumber.setText(""+ tmpNo[position]);
for(int i=0;i<ayyType.size();i++)
{
strType = ayyType.get(i).toString();
if(strType.equalsIgnoreCase("1"))
{
strType = "Incoming Call";
}
else if(strType.equalsIgnoreCase("2"))
{
strType = "Outgoing Call";
}
else if(strType.equalsIgnoreCase("3"))
{
strType = "Missed Call";
}
tempType.add(strType);
}
String[] tmpType = tempType.toArray(new String[tempType.size()]);
holder.txtType.setText(""+ tmpType[position]);
convertView.setTag(holder);
} else {
holder=(ViewHolder)convertView.getTag();
}
return convertView;
}
public static class ViewHolder
{
private TextView txtNumber, txtType, txtName;
}
}
I hope it may be help you.. :)
Related
I'm new in android and also new in English sorry my bad English...
I have learned android course at the academy.
My sentence may be wrong because it is written through a translator. I hope you understand with a generous heart.
Here's what I want:
If I click 15 days in Calendar View,
It is hoped that only the 15th day information will be shown in the Recyclerview. If I click on another date in calenderview, for example, 20 days, I hope that the 15th item will disappear and only the 20th item view will be displayed.
Here's what I'm trying to do.
When I click a date in a calendar view, I want to see the Item View corresponding to that date.
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.util.Calendar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Calender extends AppCompatActivity {
// CalendarView myCalenderView;
// TextView schedule1, schedule11;
String a, b, c;
static String data1;
long Now;
Date date;
java.text.SimpleDateFormat mFormat = new SimpleDateFormat("YYYY_MM_dd");
TextView datetext;
Context mcontext;
private String getTime() {
Now = System.currentTimeMillis();
date = new Date(Now);
return mFormat.format(date);
}
private ArrayList<calenderArrayList> mArrayList = new ArrayList<>();
private ArrayList<calenderArrayList> bArrayList = new ArrayList<>();
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static String TAG = "recyclerview_example";
//private ArrayList<calenderArrayList> mArrayList;
//ArrayList 선언
calendarAdapter mAdapter = new calendarAdapter(this, mArrayList);
//mAdapter 선언
// calendarAdapter bAdapter = new calendarAdapter(this, bArrayList);
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calender);
Log.d("스케쥴선택액티비티", "OnCreate()실행");
SharedPreferences calender_load = getSharedPreferences("calender", MODE_PRIVATE);
calender_load.getInt("save_size", 0);
int calender_size = calender_load.getInt("save_size", 0);
Log.d("시작시b사이즈1", "" + calender_size);
Log.d("시작시b사이즈1", "" + bArrayList.size());
Log.d("시작시m사이즈1", "" + mArrayList.size());
if (calender_size != 0) {
for (int i = 0; i < calender_size; i++) {
calenderArrayList calender = new calenderArrayList(calender_load.getString("save_date" + i, ""), calender_load.getString("save_work" + i, ""), calender_load.getString("save_place" + i, ""), calender_load.getBoolean("save_box" + i, false));
if (calender.number_exam.equals(data1)) {
Log.d("불러오기값", "" + calender_load.getString("save_date" + i, ""));
bArrayList.add(calender);
mArrayList.add(calender);
}
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
} else if (calender_size == 0) {
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
//recycler_view라는 id를 가진 recycler_view를 mRecyclerView로 지정해준다.
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), 1));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//RecyclerView 내에 Item view들의 크기를 측정하고 위치를 지정
//언제 item view를 재사용해야하는지에 대한 정책을 결정하고 결정.
//mArrayList = new ArrayList<>();
mAdapter = new calendarAdapter(this, mArrayList);
//RecyclerView 내에 보여지는 view 들에 date set을 binding 시켜주는 역할.
//binding? 데이터 끼리 묵어준다?
mRecyclerView.setAdapter(mAdapter);
//mRecyclerView의 Adapter를 mAdapter로 set한다.
//set? 지정한다. 놓다. 위치하다.
// myCalenderView = (CalendarView) findViewById(R.id.calendar);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// Toast.makeText(getApplicationContext(), "onStart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnStart()실행");
Log.d("스케쥴선택액티비티", "OnResume()실행");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// Toast.makeText(getApplicationContext(), "onResume()", Toast.LENGTH_SHORT).show();
final CalendarView calendar = (CalendarView) findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
data1 = year + "/" + (month + 1) + "/" + dayOfMonth;
String a = data1 + dayOfMonth;
Log.d("날짜", "" + a);
ArrayList<calenderArrayList> dayofMonth = new ArrayList<>();
Log.d("어떤 이름으로?", "" + dayofMonth);
if (dayofMonth.size() != 0) {
SharedPreferences load = getSharedPreferences("" + data1, MODE_PRIVATE);
}
/* if(mArrayList.size()!=0) {
for (int i=0; i<mArrayList.size() ; i++) {
SharedPreferences save11 = getSharedPreferences("save", MODE_PRIVATE );
SharedPreferences.Editor save_editor = save11.edit();
save_editor.putBoolean("save_box"+i+mArrayList.get(i).number_exam, mArrayList.get(i).selected );
save_editor.putString("save_date"+i+mArrayList.get(i).number_exam, mArrayList.get(i).number_exam);
save_editor.putString("save_work"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam);
save_editor.putString("save_place"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam2);
save_editor.putInt("save_size"+mArrayList.get(i).number_exam, mArrayList.size());
save_editor.commit();
}
}
mArrayList.clear();
if(mArrayList.size()!=0)
{
for (int i =0; i<mArrayList.size(); i++){
if(mArrayList.get(i).number_exam.equals(data1)){
}
}
}*/
//int a = dayOfMonth;
Toast.makeText(Calender.this, year + "/" + (month + 1) + "/" + dayOfMonth, Toast.LENGTH_SHORT).show();
Log.d("리사이클러뷰 실행 전", "실행 전");
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
Log.d("리사이클러뷰 실행 후", "실행 후");
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
//TextView ee = findViewById(R.id.number_exam);
Log.d("사이즈 측정 실행 전", "실행 전");
ArrayList<calenderArrayList> calenderArrayLists = new ArrayList<>();
Log.d("실행11111", mAdapter.getItemCount() + "");
Log.d("뭐가 들어있나?", "" + mArrayList);
Log.d("뭐가 들어있나?", "" + mArrayList.size());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(1).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(2).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(3).number_exam.toString());
if (mArrayList.size() != 0) {
Log.d("if구문 실행됨?", "" + mArrayList.size());
//1. 일단 뷰 자체를 초기화 해주어야함.
//2. 초기화 된 뷰에 다시 mArrayList에서 선정 된 정보를 다시 나타내주어야한다.
/* for(int i = 0; i<mArrayList.size(); i++){
Log.d("얼마?", ""+i);
Log.d("for 구문 작동?실행", "여기까진 접속?");
if(mArrayList.get(i).number_exam.toString().contains(a)){
Log.d("뭐가 들어있나? 실행여부", ""+mArrayList.get(i).number_exam.toString());
a = mArrayList.get(i).number_exam;
b = mArrayList.get(i).content_exam;
c = mArrayList.get(i).content_exam2;
//mArrayList.add(mArrayList.get(i));
}
}*/
}
}
});
Button buttonInsert_exam = (Button) findViewById(R.id.exam_button);
//button 클릭시 발생하는 이벤트를 나타낸다. 여기서는 입력하기 버튼 클릭시 발생하는 상황.
buttonInsert_exam.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Calender.this);
View view = LayoutInflater.from(Calender.this)
.inflate(R.layout.activity_calender_edit_box, null, false);
builder.setView(view);
final Button ButtonSubmit_exam = (Button) view.findViewById(R.id.button_dialog_submit_exam);
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
// final EditText editTextKorean = (EditText) view.findViewById(R.id.edittext_dialog_korean);
ButtonSubmit_exam.setText("입력하기");
number_exam.setText(data1);
final AlertDialog dialog = builder.create();
dialog.show();
//dialog에 나타나는 입력하기 버튼을 눌렀을 때 발생하는 상황
ButtonSubmit_exam.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strID = number_exam.getText().toString();
String strID2 = content_exam.getText().toString();
String strID3 = content_exam2.getText().toString();
//number와 content view에 입력한 문자열을 strID, strID2에 담는다.
//String strKorean = editTextKorean.getText().toString();
calenderArrayList dict = new calenderArrayList(strID, strID2, strID3);
bArrayList.add(0, dict);
mArrayList.add(0, dict); //첫 줄에 삽입
//mArrayList.add(dict); //마지막 줄에 삽입
mAdapter.notifyDataSetChanged(); //변경된 데이터를 화면에 반영
Log.d("b사이즈", "" + bArrayList.size());
Log.d("m사이즈", "" + mArrayList.size());
dialog.dismiss();
//dialog를 종료 시켜준다.
}
});
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Toast.makeText(getApplicationContext(), "onPause()", Toast.LENGTH_SHORT).show();
SharedPreferences calendersave = getSharedPreferences("calender", MODE_PRIVATE);
SharedPreferences.Editor calendersaveeditor = calendersave.edit();
//calenderArrayList calenderArrayList = new calenderArrayList();
if (bArrayList.size() != 0) {
for (int i = 0; i < bArrayList.size(); i++) {
calendersaveeditor.putBoolean("save_box" + i, bArrayList.get(i).selected);
calendersaveeditor.putString("save_date" + i, bArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work" + i, bArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place" + i, bArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", bArrayList.size());
calendersaveeditor.commit();
Log.d("종료시b사이즈", "" + bArrayList.size());
Log.d("종료시m사이즈", "" + mArrayList.size());
}
} else if (bArrayList.size() == 0) {
calendersaveeditor.clear();
calendersaveeditor.commit();
}
Log.d("스케쥴선택액티비티", "OnPause()실행");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
// Toast.makeText(getApplicationContext(), "onStop()", Toast.LENGTH_SHORT).show();
/*
* if(mArrayList.size()!=0){
for(int i = 0; i< mArrayList.size(); i++){
calendersaveeditor.putBoolean("save_box"+i, mArrayList.get(i).selected);
calendersaveeditor.putString("save_date"+i, mArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work"+i, mArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place"+i, mArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", mArrayList.size());
calendersaveeditor.commit();
}
}
else if(mArrayList.size()==0){
calendersaveeditor.clear();
calendersaveeditor.commit();
}
*/
Log.d("스케쥴선택액티비티", "OnStop()실행");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
// Toast.makeText(getApplicationContext(), "onRestart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnRestart()실행");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Toast.makeText(getApplicationContext(), "onDestroy()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnDestroy()실행");
}
}
First you need to add new entry in your existing mArrayList as i am can see from your code you are adding all existing entries again but not new entry.
After that you need to set adapter again with new mArrayList only then you will be able to see new data in your recycler view.
I do not understand why last contact is added to the first card in recyclerview again when activity is resumed. I know that it is to do with cursor or content resolver.
Here is the java class with which I have problem.
while retreiving contacts again on onResume, last contact is re-added on first card in recycler view
package com.android.eventers;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.util.ArrayList;
import java.util.Locale;
public class ContactsActivity extends AppCompatActivity implements ContactsAdapter.ListItemClickListener {
private static final int CHECK_CLICK = 1;
private static final String LIST_STATE_KEY = "list_state";
FloatingActionButton mFloatingActionButton;
RecyclerView mRecyclerView;
ContactsAdapter mAdapter;
String contactName;
String mobileNumber;
String mobileNumberSelected;
Contacts contactsObject;
TextView noItem;
private ArrayList<Contacts> contactsArrayList;
ArrayList<String> tempList;
private Parcelable mListState;
private LinearLayoutManager mLayoutManager;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
private boolean mCalledFromOncreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mCalledFromOncreate = true;
noItem = (TextView) findViewById(R.id.no_listitem_in_contacts);
noItem.setVisibility(View.GONE);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.add_fab_in_main);
contactsArrayList = new ArrayList<Contacts>();
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
launchConacts();
for (int i = 0; i < contactsArrayList.size(); i++) {
Log.e("name:", "" + contactsArrayList.get(i).getName());
for (int j = 0; j < contactsArrayList.get(i).getMobileNumber().size(); j++) {
Log.e("num:", contactsArrayList.get(i).getMobileNumber().get(j));
}
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = "";
int counter = 0;
for (int i = 0; i < contactsArrayList.size(); i++) {
Contacts singleContact = contactsArrayList.get(i);
if (contactsArrayList.get(i).getFlag()) {
data = data + "\n" + singleContact.getName().toString() + " " + singleContact.getSelectedMobileNumber();
counter++;
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), true);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
} else {
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), false);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
}
}
mEditor.commit();
Toast.makeText(ContactsActivity.this, "Selected contacts: \n" + data, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ContactsActivity.this, ReportActivity.class);
intent.putExtra("TOTAL_KEY", contactsArrayList.size() + "");
intent.putExtra("SELECTED_KEY", counter + "");
startActivity(intent);
}
});
}
#Override
public void onListItemClick(final int clickedItemIndex, int whichClick) {
switch (whichClick) {
case CHECK_CLICK: {
//Toast.makeText(ContactsActivity.this, "Clicked on Checkbox: "+clickedItemIndex , Toast.LENGTH_SHORT).show();
int selectedMobileNumberPosition = 0;
String selectedMobileNumber = contactsArrayList.get(clickedItemIndex).getSelectedMobileNumber();
if (contactsArrayList.get(clickedItemIndex).getMobileNumber().size() > 1) {
final String items[] = new String[contactsArrayList.get(clickedItemIndex).getMobileNumber().size()];
for (int j = 0; j < contactsArrayList.get(clickedItemIndex).getMobileNumber().size(); j++) {
items[j] = contactsArrayList.get(clickedItemIndex).getMobileNumber().get(j);
if (items[j].contains(selectedMobileNumber)) {
selectedMobileNumberPosition = j;
}
}
AlertDialog levelDialog;
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select the mobile number");
builder.setSingleChoiceItems(items, selectedMobileNumberPosition, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mobileNumberSelected = items[item];
contactsArrayList.get(clickedItemIndex).setSelectedMobileNumber(mobileNumberSelected);
// levelDialog.dismiss();
}
});
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(ContactsActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
}
});
levelDialog = builder.create();
levelDialog.show();
}
break;
}
}
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if (state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
#Override
protected void onResume() {
super.onResume();
if (!mCalledFromOncreate) {
contactsArrayList.clear();
launchConacts();
mAdapter.notifyDataSetChanged();
Log.e("Inside", "onResume after clear");
}
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
void launchConacts() {
//Cursor pho = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Log.i("Size is "," "+phones.getCount());
if (phones != null && (phones.getCount() > 0)) {
phones.moveToFirst();
phones.move(0);
for (int i = 0; i < phones.getCount(); i++) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumberStr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = phoneNumberUtil.parse(phoneNumberStr, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
if (phoneNumberType == PhoneNumberType.MOBILE) {
if (name.equals(contactName)) {
phoneNumberStr = phoneNumberStr.replaceAll(" ", "");
if (phoneNumberStr.contains(mobileNumber)) {
} else {
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
if (!tempList.contains(mobileNumber)) {
// Log.e("phone: ", " " + phoneNumber);
contactsObject.setMobileNumber(mobileNumber);
tempList.add(mobileNumber);
}
}
} else {
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added", contactsObject.getName());
}
contactsObject = new Contacts();
tempList = new ArrayList<String>();
contactName = name;
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
tempList.add(mobileNumber);
// Log.e("name: ", " " + name);
// Log.e("phone: ", " " + mobileNumber);
contactsObject.setName(name);
contactsObject.setMobileNumber(mobileNumber);
contactsObject.setFlag(mSharedPreferences.getBoolean("checkbox_" + name, false));
contactsObject.setSelectedMobileNumber(mSharedPreferences.getString("selected_mobile_number_for_" + name, mobileNumber));
}
}
} catch (Exception e) {
} finally {
}
if (phones.isLast()) {
contactsArrayList.add(contactsObject);
// Log.e("object added last>>>>>", contactsObject.getName());
}
phones.moveToNext();
}
//phones.close();
}
mRecyclerView = (RecyclerView)
findViewById(R.id.recycler_view_in_contacts);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new
LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new
ContactsAdapter(contactsArrayList, ContactsActivity.this);
mRecyclerView.setAdapter(mAdapter);
if (contactsArrayList.size() == 0)
{
noItem.setVisibility(View.VISIBLE);
}
}
#Override
protected void onPause() {
super.onPause();
mCalledFromOncreate = false;
}
}
Here is what I found which is adding one more item in your list
Try removing:
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added : ", contactsObject.getName);
}
Hope this helps.
I have a listview where I have 50 elements being displayed. I have decided to paginate the view so on each part of the view there are 10 elements and then a next button is clicked to get to the next 10 elements. How can i set 10 data ? I follow this article
http://rakhi577.wordpress.com/2013/05/20/listview-pagination-ex-2/
Here is my code .Can you help me with my code or a link to a guide on how to implement this correctly?
public class MainActivity extends ListActivity {
Context context;
Button btnSearch ;
EditText txtSearch;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
//loadList(0);
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//loadList(j);
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
//String address = c.getString(TAG_ADDRESS);
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I change the code. When i click next button[like 2,3,4,5]. showing first page data. Here is my modified code.Any help Appreciated :
public class MainActivity extends ListActivity {
private TextView title;
Context context;
Button btnSearch ;
EditText txtSearch;
private ListView listview;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
title = (TextView)findViewById(R.id.title);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position%2==0)
{
view.setBackgroundColor(Color.parseColor("#F4FA58"));
}else
{
view.setBackgroundColor(Color.parseColor("#DA81F5"));
}
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
new GetContacts().execute();
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
title.setText("Page "+(index+1)+" of "+noOfBtns);
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int number = 0;
int start = number * NUM_ITEMS_PAGE;
// looping through All Contacts
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
//for (int i = 0; i < contacts.length(); i++) {
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
Below is my code to show list view with pagination. There is two blue button for change pages.
You can customize according to you need.
Create UserCategory.java
package com.UserCategory;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
public class UserCategory extends Activity implements OnClickListener{
private final int PAGE_SIZE = 5;
private int StartingIndex = 0;
ArrayList<String> userClass=new ArrayList<String>();
int textlength=0;
private String lv_arr[];
private ListView lv1;
EditText searchText;
//Button Previous;
private String Machine[]={"Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12","Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12"};
ImageView next,Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
searchText=(EditText)findViewById(R.id.et_Serchlist);
next=(ImageView)findViewById(R.id.btn_next);
Previous=(ImageView)findViewById(R.id.btn_previous);
next.setOnClickListener(this);
Previous.setOnClickListener(this);
//parsing();
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , Machine));
changeListViewModel(0);
}
private void changelist(int startingIndex) {
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}else if(startingIndex >= userClass.size())
startingIndex -= PAGE_SIZE;
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("ending index"+endingIndex);
if(StartingIndex!=0){
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
if(endingIndex > userClass.size()) endingIndex = userClass.size();
try {
String[] subSet = getDataSubset1(startingIndex, endingIndex);
System.out.println("subSet array"+subSet);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
} catch (Exception e) {
e.printStackTrace();
}
}
private String[] getDataSubset1(int startingIndex, int endingIndex){
String[] changeList = new String[endingIndex - startingIndex];
int index = -1;
for(int x = startingIndex; x < endingIndex; x++)
changeList[++index] = userClass.get(x);
return changeList;
}
private void changeListViewModel(int startingIndex){
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}
else if(startingIndex >= Machine.length){
startingIndex -= PAGE_SIZE;
}
System.out.println("strating"+startingIndex);
System.out.println("startingIndex"+startingIndex);
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("endingIndex"+endingIndex);
if(StartingIndex!=0)
{
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
System.out.println("ending index"+endingIndex);
if(endingIndex > Machine.length) {
endingIndex = Machine.length;
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
String[] subSet = getDataSubset(startingIndex, endingIndex);
System.out.println("subSet main array"+subSet.length);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
}
private String[] getDataSubset(int startingIndex, int endingIndex){
String[] toRet = new String[endingIndex - startingIndex];
int index = -1;
System.out.println("index"+index);
for(int x = startingIndex; x < endingIndex; x++)
toRet[++index] = Machine[x];
return toRet;
}
private void parsing() {
// TODO Auto-generated method stub
try {
URL url = new URL("http://10.10.1.100/DogEventsWebService/EventService.svc/categories/1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("UserCategory");
Machine = new String[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Machine[i] = new String();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("ClassDescription");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Machine[i]=((Node) nameList.item(0)).getNodeValue();
}
System.out.println("after for loop Machine"+Machine);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_next:
textlength=searchText.getText().length();
System.out.println("nextbutton"+textlength);
if(textlength==0){
changeListViewModel(StartingIndex + PAGE_SIZE);
}else{
changelist(StartingIndex + PAGE_SIZE);
}
break;
case R.id.btn_previous:
textlength=searchText.getText().length();
if(textlength==0){
changeListViewModel(StartingIndex - PAGE_SIZE);
}else{
changelist(StartingIndex - PAGE_SIZE);
}
break;
default:
break;
}
}
}
create main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<View android:layout_height="35dp"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<TextView android:id="#+id/tv_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:layout_alignParentTop="true"
android:layout_marginLeft="0dp"
android:textSize="25dp"/>
<EditText
android:id="#+id/et_Serchlist"
android:layout_height="35dp"
android:paddingLeft="19dp"
android:layout_marginLeft="60dp"
android:layout_toRightOf="#+id/tv_header"
android:maxLength="20"
android:maxLines="1"
android:inputType="text"
android:hint="Search"
android:textColor="#ffffff"
android:background="#drawable/my_border"
android:layout_width="100dip"/>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:textSize="4px"
android:layout_below="#+id/tv_header"
android:layout_above="#+id/btn_previous"
android:layout_height="wrap_content" />
<View android:layout_height="55dp"
android:layout_below="#+id/ListView0"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<ImageView
android:src="#drawable/grewprevious"
android:id="#+id/btn_Whiteprevious"
android:layout_width="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/right"
android:id="#+id/btn_grewforward"
android:layout_width="wrap_content"
android:layout_marginLeft="259dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/backward"
android:id="#+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:onClick="backButtonClicked"/>
<ImageView android:src="#drawable/forward"
android:id="#+id/btn_next"
android:layout_width="80dp"
android:layout_marginBottom="6dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/ListView0"
android:layout_marginLeft="249dp"
android:text="Next"
android:onClick="nextButtonClicked"/>
</RelativeLayout>
Create userlist.xml
<?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">
<TextView android:id="#+id/tv_className"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Add my_border.xml into Drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dip" android:color="#ee777777" />
<solid android:color="#ee444444"/>
<padding
android:left="20dip"
android:top="2dip"
android:right="20dip"
android:bottom="2dip" />
<corners android:radius="15dip" />
![enter image description here][1]</shape>
If it give error for iamges then use any other images and run application.
Let me know it work for you.
Thanks
I am having difficulty making my layout to work...
What I want to do is have two spinners and a button below those and once the button is clicked, I display the results based on the values selected in the spinners.
-----------
| Spinner 1 |
-----------
-----------
| Spinner 2 |
-----------
-----------
| Button |
-----------
Result 1
Result 2
Result 3
Result 4
Result 5
I have tried to put the results in a ListView, but the problem I face is that once the button is clicked, I can see the repetition of Spinner1, Spinner2 and the Button itself multiple times.
The xml for the layout is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/done" />
<LinearLayout
android:id="#+id/moreContent"
android:layout_width="match_parent"
android:visibility="visible"
android:orientation="vertical"
android:layout_height="wrap_content"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
</LinearLayout>
Can someone please advise where am I going wrong?
The code is as follows:
package ms.timetable;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ListActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
RetreiveFeedTask rft = new RetreiveFeedTask();
rft.execute();
}
});
}
#SuppressLint("NewApi")
private class RetreiveFeedTask extends AsyncTask<Void, Void, String> {
TreeMap<String, String> _timetable = null;
#Override
protected String doInBackground(Void... arg0) {
// TODO Auto-generated method stub
_timetable = FetchTimetableInfo();
return null;
}
protected void onPostExecute(String str){
if (_timetable != null){
ArrayList<TimeTable> tarr = new ArrayList<TimeTable>();
Iterator<Entry<String, String>> it = _timetable.entrySet().iterator();
String toastText = "";
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
toastText = toastText + key + " --- " + value + "\n";
//System.err.println(key + " --- " + value);
TimeTable tt = new TimeTable();
tt.set_line(value);
String [] tem = key.split("---");
tt.set_arrival(tem[1]);
tt.set_departure(tem[1]);
tarr.add(tt);
}
//Toast.makeText(context, toastText, Toast.LENGTH_LONG).show();
//tmap.add(_timetable);
setListAdapter((ListAdapter) new TimetableAdapter(getApplicationContext(), tarr));
}
}
private TreeMap<String, String> FetchTimetableInfo(){
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
String origin = (String) spinner1.getSelectedItem();
String destination = (String) spinner2.getSelectedItem();
//String val = String.valueOf(spinner1.getSelectedItem());
ArrayList<String> linesServOrigin = LineStation.GetServingLines(origin);
ArrayList<String> linesServDest = LineStation.GetServingLines(destination);
linesServOrigin.retainAll(linesServDest);
//ArrayList<String> preferredLines = linesServOrigin.re.retainAll(linesServDest);
Log.e(this.getClass().toString(), "Selected value is : " + linesServOrigin.get(0));
try
{
for (int k = 0; k < linesServOrigin.size(); k++)
{
String url = "http://tt.ptv.vic.gov.au/tt/XSLT_REQUEST?itdLPxx_lineMain=" + LineStation.GetLineMain(linesServOrigin.get(0)) + "&itdLPxx_lineID=" + LineStation.GetLineID(linesServOrigin.get(0)) + "&itdLPxx_output=html";
DataManager dm = new DataManager(url, getApplicationContext());
ArrayList<String> stationData = dm.GetStationsData();
ArrayList<ArrayList<String>> timetableData = dm.GetTimetableData();
ArrayList<String> originTimetable = null;
ArrayList<String> originTimetable1 = null;
ArrayList<String> destinationTimetable = null;
ArrayList<String> destinationTimetable1 = null;
int origPos = 0;
int destPos = 0;
int ctr = 0;
for (int i = 0; i < stationData.size(); i++)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
//originTimetable = timetableData[i];
origPos = i;
}
else if (stationData.get(i).equals( destination) || (destination + " - ARR").equals(stationData.get(i)))
{
//destinationTimetable = timetableData[i];
destPos = i;
}
if (origPos != 0 && destPos != 0)
{
break;
}
}
if (origPos > destPos)
{
dm.SwitchDirection();
stationData = dm.GetStationsData();
timetableData = dm.GetTimetableData();
}
for (int i = stationData.size() - 1; i >= 0; i--)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
if (originTimetable == null)
{
originTimetable = timetableData.get(i);
}
else if (originTimetable1 == null)
{
originTimetable1 = timetableData.get(i);
}
}
else if (stationData.get(i).equals(destination) || (destination + " - ARR").equals(stationData.get(i)))
{
if (destinationTimetable == null)
{
destinationTimetable = timetableData.get(i);
}
else if (destinationTimetable1 == null)
{
destinationTimetable1 = timetableData.get(i);
}
}
}
TreeMap<String, String> ttable = new TreeMap<String, String>();
if (originTimetable != null && destinationTimetable != null)
{
//int curtime = Integer.parseInt(DateTime.Now.ToString("HHmm", CultureInfo.CurrentCulture));
String temp = new SimpleDateFormat("HHmm").format(Calendar.getInstance().getTime());
int curtime =Integer.parseInt(temp);
System.err.println("Origin timetable size = " + originTimetable.size());
System.err.println("Destination timetable size = " + destinationTimetable.size());
for (int j = 0; j < originTimetable.size(); j++)
{
if (Integer.parseInt((originTimetable.get(j))) > curtime)
{
if (Integer.parseInt((destinationTimetable.get(j))) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j)) == -1))
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
ctr = 0;
if (originTimetable1 != null)
{
for (int j = 0; j < originTimetable1.size(); j++)
{
if (originTimetable1 != null && Integer.parseInt(originTimetable1.get(j)) > curtime)
{
if (Integer.parseInt(destinationTimetable.get(j)) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j))) == -1)
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
}
Iterator<Entry<String, String>> it = ttable.entrySet().iterator();
//foreach (KeyValuePair<String, List<String>> item in lineStations)
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
System.err.println(key + " --- " + value);
}
return ttable;
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
class TimeTable{
private String _departure, _arrival, _line;
public TimeTable(){
}
public TimeTable(String departure, String arrival, String line){
_departure = departure;
_arrival = arrival;
_line = line;
}
public String get_departure() {
return _departure;
}
public void set_departure(String _departure) {
this._departure = _departure;
}
public String get_arrival() {
return _arrival;
}
public void set_arrival(String _arrival) {
this._arrival = _arrival;
}
public String get_line() {
return _line;
}
public void set_line(String _line) {
this._line = _line;
}
}
}
The adapter is as follows:
package ms.timetable;
import java.util.ArrayList;
import ms.timetable.MainActivity.TimeTable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TimetableAdapter extends ArrayAdapter<TimeTable>{
private final Context context;
private final ArrayList<TimeTable> values;
public TimetableAdapter(Context context, ArrayList<TimeTable> values){
super(context, R.layout.activity_main, values);
this.context = context;
this.values = values;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
TextView textView2 = (TextView) rowView.findViewById(R.id.textView2);
//System.err.println("Position is : "+position);
TimeTable tt = values.get(position);
textView.setText(tt.get_departure());
textView2.setText(tt.get_arrival());
return rowView;
}
}
The problem is due to
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
in getView() method.
You are inflating whole activity_main in a row and then adding it to a listview.
Put a row for results in separate xml instead of activity_main. So you will have a new xml file say, row.xml which will contain:
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
So you will have to inflate as
View rowView = inflater.inflate(R.layout.row, parent, false);
And then add the generated rows in the listview which is in activity_main.xml.
So your problem will be solved. Hope it helps.
I have custom ListView with an adapter that lets users see entries made to a database. Everything with the ListView works fine, until I try to click on any but the first entry in the list. When clicked, the entry should be loaded into an editor. For some reason, no matter which entry is clicked, the first entry in the list is loaded into the editor. Here is the activity code for the ListView:
public class MainActivity extends Activity {
public static final String KEY_ID = "listviewId";
public static final String KEY_SHORT = "projectShortTextView";
public static final String KEY_FULL = "projectFullTextView";
public static final String KEY_HOURS = "listviewHoursTV";
public static final String KEY_PROID = "projectIdTV";
private SQLiteDatabase db;
private TimesheetDatabaseHelper dbHelp = new TimesheetDatabaseHelper(this);
/** Gets a valid calendar instance for use */
final Calendar c = Calendar.getInstance();
/** Strings for formatting the date's for use */
public String dateViewForm = "EEE MM/dd/yyyy";
public String dateForm = "MM/dd/yyyy";
public String timeForm = "HH:mm";
/** Strings to store formated calendar outputs */
public String date, dateView;
/** Prepares buttons and EditText for use */
public Button minusButton, plusButton, quickAdd;
public EditText dateEditText;
public ListView list;
TimestampAdapter adapter;
SimpleDateFormat formDateView = new SimpleDateFormat(dateViewForm, Locale.US);
SimpleDateFormat formDate = new SimpleDateFormat(dateForm, Locale.US);
SimpleDateFormat formTime = new SimpleDateFormat(timeForm, Locale.US);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BugSenseHandler.initAndStartSession(MainActivity.this, "8b04fe90");
setContentView(R.layout.activity_main);
try {
updateCheck();
} catch (NameNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
/** Method to get todays date and display it in the proper places */
date = initialDates();
getDailyTimestamps(date);
/**
* Implements the Minus Button with OnCLickListener and
* calls the minusButtonHandler if called */
minusButton = (Button)findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
date = minusButtonHandler();
getDailyTimestamps(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
/**
* Implements the Plus Button with OnCLickListener and
* calls the plusButtonHandler if called */
plusButton = (Button)findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
date = plusButtonHandler();
getDailyTimestamps(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
quickAdd = (Button)findViewById(R.id.quickAddButton);
quickAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAddHandler(v);
getDailyTimestamps(date);
}
});
}
#SuppressWarnings("deprecation")
private void updateCheck() throws NameNotFoundException, IOException, InterruptedException, ExecutionException {
Log.d("Checking for updates", "true");
String urlVersion;
UpdateCheck check = new UpdateCheck();
urlVersion = check.execute().get();
Log.d("urlVerion", urlVersion);
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String packageVersion = pInfo.versionName;
Log.d("Package Version", packageVersion);
if (!urlVersion.equals(packageVersion)) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Version Check");
alert.setMessage("You're version is out of date. Please visit "
+ "www.ubundude.com/p/beta.html to update to the latest version.");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.show();
}
}
#Override
protected void onResume() {
super.onResume();
getDailyTimestamps(date);
}
private void getDailyTimestamps(String date) {
ArrayList<HashMap<String, String>> stampList = new ArrayList<HashMap<String, String>>();
/** Open the database table for reading and writing */
db = dbHelp.getReadableDatabase();
String getTimestamps = "select ti._id, pr.name, pr.shortcode, ti.hours, ti.project "
+ "from timestamp ti inner join projects pr "
+ "where ti.project = pr._id and ti.date_in = '" + date + "'";
Cursor cu = db.rawQuery(getTimestamps, null);
if(cu != null && cu.getCount() > 0){
cu.moveToFirst();
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, Integer.toString(cu.getInt(0)));
map.put(KEY_SHORT, cu.getString(1));
map.put(KEY_FULL, cu.getString(2));
map.put(KEY_HOURS, cu.getString(3));
map.put(KEY_PROID, Integer.toString(cu.getInt(4)));
stampList.add(map);
} while(cu.moveToNext());
}
cu.close();
db.close();
list = (ListView)findViewById(R.id.timestampListView);
adapter = new TimestampAdapter(this, stampList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d("ListView On Click", "Position: " + position);
TextView idTV = (TextView)findViewById(R.id.listviewId);
TextView proIdTV = (TextView)findViewById(R.id.projectIdTV);
TextView full = (TextView)findViewById(R.id.projectShortTextView);
String test = full.getText().toString();
Log.d("Listview", "Project Name: " + test);
int timeId = Integer.parseInt(idTV.getText().toString());
Log.d("Listview", "Timestamp ID: " + timeId);
int proId = Integer.parseInt(proIdTV.getText().toString());
Log.d("Listview", "Project ID: " + proId);
Intent intent = new Intent(MainActivity.this, TimestampEditorActivity.class);
intent.putExtra("TIMESTAMP_ID", timeId);
intent.putExtra("PROJECT_ID", proId);
startActivity(intent);
}
});
}
private String initialDates() {
dateView = formDateView.format(c.getTime());
date = formDate.format(c.getTime());
/** Sets the text in the dateEditText to the current date */
dateEditText = (EditText)findViewById(R.id.dateEditText);
dateEditText.setText(dateView, TextView.BufferType.NORMAL);
return date;
}
/** Gets the next day and displays to dateEditText
* #throws ParseException */
private String plusButtonHandler() throws ParseException {
c.setTime(formDateView.parse(dateView));
c.add(Calendar.DAY_OF_MONTH, 1);
dateView = formDateView.format(c.getTime());
date = formDate.format(c.getTime());
dateEditText = (EditText)findViewById(R.id.dateEditText);
dateEditText.setText(dateView, TextView.BufferType.NORMAL);
return date;
}
/** Gets the previous day and displays to dateEditText
* #throws ParseException */
private String minusButtonHandler() throws ParseException {
c.setTime(formDateView.parse(dateView));
c.add(Calendar.DAY_OF_MONTH, -1);
dateView = formDateView.format(c.getTime());
date = formDate.format(c.getTime());
dateEditText = (EditText)findViewById(R.id.dateEditText);
dateEditText.setText(dateView, TextView.BufferType.NORMAL);
return date;
}
/**
* Intent to move to TimestampEditorActivity
*
* #param view Gets the current view context to pass with the intent
*/
public void addNewHandler(View view) {
Intent intent = new Intent(this, TimestampEditorActivity.class);
startActivity(intent);
}
/**
* Get current date and time and place them into Timestamp table as generic entry
*
* #param view
* #throws SQLException
*/
public void quickAddHandler(View view) throws SQLException {
String timeIn, timeOut, dateIn, dateOut;
int project = 1; //Will get from Default project in settings
timeIn = formTime.format(c.getTime());
timeOut = timeIn;
dateIn = formDate.format(c.getTime());
dateOut = dateIn;
db = dbHelp.getWritableDatabase();
String insertSQL = "insert into timestamp (date_in, time_in, date_out, time_out, hours, project) " +
"values('" + dateIn + "', '" + timeIn + "', '" + dateOut +
"', '" + timeOut + "', 0, '" + project + "')";
try {
db.execSQL(insertSQL);
} catch(Exception e) {
Log.d("save Fail", e.getLocalizedMessage(), e.fillInStackTrace());
}
db.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Here is the xml for the ListView:
<TextView
android:id="#+id/projectShortTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/defaultText"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/projectFullTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/projectShortTextView"
android:text="#string/defaultText"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/listviewId"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/projectShortTextView"
android:text="#string/defaultInt" />
<Button
android:id="#+id/listviewEditButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/listviewHoursTV"
android:background="#drawable/edit"
android:focusable="false" />
<TextView
android:id="#+id/listviewHoursTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="#string/defaultTime"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/projectIdTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/projectFullTextView"
android:layout_toRightOf="#+id/listviewId"
android:text="#string/defaultInt"
android:visibility="invisible" />
</RelativeLayout>
And here is the adapter:
public class TimestampAdapter extends BaseAdapter {
private Activity activity;
private ArrayList> data;
private static LayoutInflater inflater = null;
public TimestampAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
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.listview_timestamp, null);
TextView projectShort = (TextView)vi.findViewById(R.id.projectShortTextView);
TextView projectFull = (TextView)vi.findViewById(R.id.projectFullTextView);
TextView stampId = (TextView)vi.findViewById(R.id.listviewId);
TextView hoursEdit = (TextView)vi.findViewById(R.id.listviewHoursTV);
TextView projectId = (TextView)vi.findViewById(R.id.projectIdTV);
HashMap<String, String> timestamp = new HashMap<String, String>();
timestamp = data.get(position);
stampId.setText(timestamp.get(MainActivity.KEY_ID));
projectShort.setText(timestamp.get(MainActivity.KEY_SHORT));
projectFull.setText(timestamp.get(MainActivity.KEY_FULL));
hoursEdit.setText(timestamp.get(MainActivity.KEY_HOURS) + " hrs");
projectId.setText(timestamp.get(MainActivity.KEY_PROID));
return vi;
}
}
The debug lines in the above code show the proper position for each row clicked, but the id's for the first row's information are the only ones that show up. And that is consistent with only the first row getting loaded into the editor.
Your problem probably lies in these lines:
TextView idTV = (TextView)findViewById(R.id.listviewId);
TextView proIdTV = (TextView)findViewById(R.id.projectIdTV);
TextView full = (TextView)findViewById(R.id.projectShortTextView);
You are finding these views in the layout of the Activity, not in the row of the ListView. If these ids are also duplicated in the ListView, access the whole row via
view.findViewById(R.id.yourId);
If StampList is a list of complex Objects that contain all of this data, you can skip the finding of Views and simply use the adapter or the AdapterView to access the object.
Edit: You are using a HashMap, this should be easier:
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap <String,String> currentMap = stampList.get(position);
Intent intent = new Intent(MainActivity.this, TimestampEditorActivity.class);
intent.putExtra("TIMESTAMP_ID", currentMap.get(MainActivity.KEY_ID));
intent.putExtra("PROJECT_ID", currentMap.get(MainActivity.KEY_PROID));
startActivity(intent);
}
Just make sure to declare stampList as final. Alternatively, if you don't want to specify stampList as final replace
HashMap <String,String> currentMap = stampList.get(position);
with
HashMap <String,String> currentMap = (HashMap<String,String>)parent.getItemAtPosition(position);