For example, I need to judge the contents of the item in the Item can be clicked.
enter image description here
As shown in the picture, I need to get the gray Item cannot be clicked.
Here is my adapter
public class RoomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context mContext;
private List<Room> mDatas;
public RoomAdapter(Context context, List<Room> mDatas) {
mInflater = LayoutInflater.from(context);
this.mContext = context;
this.mDatas = mDatas;
}
#Override
public int getCount() {
return mDatas.size();
}
#Override
public Object getItem(int position) {
return mDatas.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Room room = mDatas.get(position);
ViewHolder viewHolder = null;
View view;
if (convertView == null) {
viewHolder = new ViewHolder();
view = mInflater.inflate(R.layout.roomstate_item, null);
viewHolder.tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
viewHolder.tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
viewHolder.tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
viewHolder.tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
view.setTag(viewHolder);
}else{
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
// String nu = room.getRoom_number();
viewHolder.tv_roomstate.setText(room.getRoom_status());
viewHolder.tv_roomnumber.setText(room.getRoom_number());
viewHolder.tv_roomtype.setText(room.getRoomType().getRoom_type_name());
viewHolder.tv_roomprice.setText(room.getRoomType().getRoom_type_price());
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setClickable(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setClickable(false);
view.setBackgroundResource(R.drawable.doubleg);
}
return view;
}
private class ViewHolder {
TextView tv_roomnumber;
TextView tv_roomstate;
TextView tv_roomtype;
TextView tv_roomprice;
}
}
Here is my Activity
public class RoomList extends Activity {
private ImageView iv_back;
private TextView tv_hotelname;
private GridView griv_hotel;
private RoomAdapter adapter;
private String hotelname;
private String url
= "http://jm/user/room/selectRoomByHotelName?hotel_name=";
private List<Room> mRoom;
private RoomType mRoomType;
private boolean isfinish = false;//判断请求是否完成
private String hotel_address;
private String hotel_id;
private Bundle mBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_room_list);
init();
sendRequestWithOkHttp();
boolean is = true;
while (is) {
if (isfinish) {
adapter = new RoomAdapter(this, mRoom);
griv_hotel.setAdapter(adapter);
griv_hotel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
TextView tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
TextView tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
TextView tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
String roomnumber = tv_roomnumber.getText().toString();
String roomstate = tv_roomstate.getText().toString();
String roomtype = tv_roomtype.getText().toString();
String roomprice = tv_roomprice.getText().toString();
Log.e("房间类型",roomtype);
// if (roomstate.equals("0") && roomtype.equals("0")) {
// view.setClickable(false);
// } else if (roomstate.equals("1") && roomtype.equals("0")) {
// view.setClickable(true);
// } else if (roomstate.equals("1") && roomtype.equals("1")) {
// view.setClickable(true);
// } else {
// view.setClickable(false);
// }
mBundle.putString("roomnumber", roomnumber);
mBundle.putString("roomstate", roomstate);
mBundle.putString("roomtype", roomtype);
mBundle.putString("roomprice", roomprice);
mBundle.putString("hoteladdress", hotel_address);
mBundle.putString("hotelid", hotel_id);
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}
});
is = false;
}
}
}
private void init() {
initView();
initEvents();
}
private void initEvents() {
iv_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void initView() {
iv_back = (ImageView) findViewById(R.id.iv_back);
tv_hotelname = (TextView) findViewById(R.id.tv_hotelname);
mBundle = getIntent().getExtras();
hotelname = mBundle.getString("hotelname");
tv_hotelname.setText(hotelname);
griv_hotel = (GridView) findViewById(R.id.griv_hotel);
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
#Override
public void run() {
MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
try {
OkHttpClient client = new OkHttpClient();
String postBody = hotelname;
Request request = new Request.Builder()
.url(url + hotelname)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
try {
parseJSON(responseData);
isfinish = true;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSON(String responseData) throws JSONException {
JSONArray JSONArray = new JSONArray(responseData);
mRoom = new ArrayList<Room>();
for (int i = 0; i < JSONArray.length(); i++) {
try {
JSONObject JSON = JSONArray.getJSONObject(i);
String room_number = JSON.getString("room_number");
String room_status = JSON.getString("room_status");
JSONObject jsonObject = JSON.getJSONObject("roomType");
String room_type_name = jsonObject.getString("room_type_name");
String room_type_price = jsonObject.getString("room_type_price");
JSONObject jsonObj = JSON.getJSONObject("hotel");
hotel_id = String.valueOf(jsonObj.getInt("hotel_id"));
hotel_address = jsonObj.getString("hotel_location");
mRoomType = new RoomType(null, room_type_name, room_type_price, null, null);
mRoom.add(new Room(null, room_number, room_status, null, null, mRoomType));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I set view.setClickable (false)in my Adapter, but it does not work.
item.setEnabled(false);
when u need to make it clickable call
item.setEnabled(true);
Here item is your edittext or button or anything else
Try this:
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setEnabled(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setEnabled(false);
view.setBackgroundResource(R.drawable.doubleg);
}
else
view.setEnabled(true);
The right way is to write a Boolean value, and let it based on a Boolean value to determine whether to jump.
private boolean checkedIntent = false;
if (roomstate.equals("0") && roomtype.equals("0")) {
checkedIntent = false;
} else if (roomstate.equals("1") && roomtype.equals("0")) {
checkedIntent = true;
} else if (roomstate.equals("1") && roomtype.equals("1")) {
checkedIntent = true;
} else if (roomstate.equals("0") && roomtype.equals("1")) {
checkedIntent = false;
}
if (checkedIntent == true) {
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}
Related
I am supposed to make a note/reminder kind of application. My problem is that when I exit the application, the listview(which supposedly contain the notes added) is empty. I'm going to post all of my codes here. How do I still keep the notes even after exiting the app without using database?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private NoteAdapter mNoteAdapter;
private boolean mSound;
private int mAnimOption;
private SharedPreferences mPrefs;
Animation mAnimFlash;
Animation mAnimFadeIn;
int mIDBeep = -1;
SoundPool nsp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
nsp = new SoundPool.Builder().setMaxStreams(5).setAudioAttributes(audioAttributes).build();
}else{
// sp = new SoundPool(5, AudioAttributes.STREAM_MUSIC,0);
}
try{
AssetManager assetManager = this.getAssets();
AssetFileDescriptor descriptor;
//Load our fx
descriptor = assetManager.openFd("fx1.ogg");
mIDBeep = nsp.load(descriptor,0);
} catch (IOException e) {
Log.e("error", "failed to load sound files");
mNoteAdapter = new NoteAdapter();
ListView listNote = (ListView)findViewById(R.id.listView);
listNote.setAdapter(mNoteAdapter);
listNote.setLongClickable(true);
listNote.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
mNoteAdapter.deleteNote(position);
return true;
}
});
listNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
if (mSound){
nsp.play(mIDBeep, 1,1,0,0,1);
}
Note tempNote = mNoteAdapter.getItem(whichItem);
DialogShowNote dialog = new DialogShowNote();
dialog.sendNoteSelected(tempNote);
dialog.show(getFragmentManager(), "");
}
});
}}
public void createNewNote(Note n) {
mNoteAdapter.addNote(n);
}
public void addNote(View view) {
DialogNewNote dialog = new DialogNewNote();
dialog.show(getFragmentManager(), "");
}
public void viewSettings(View view){
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
public class NoteAdapter extends BaseAdapter{
private JSONSerializer mSerializer;
List<Note> noteList = new ArrayList<Note>();
public NoteAdapter(){
mSerializer = new JSONSerializer("NotetoSelf.json",MainActivity.this.getApplicationContext());
try{
noteList= mSerializer.load();
}catch (Exception e){
noteList = new ArrayList<Note>();
Log.e("Error loading notes: ","",e);
}
}
public void saveNote(){
try{
mSerializer.save(noteList);
}catch (Exception e){
Log.e("Error Saving notes: ","",e);
}
}
public int getCount() {
return noteList.size();
}
public Note getItem(int whichItem) {
return noteList.get(whichItem);
}
public long getItemId(int whichItem) {
return whichItem;
}
public View getView(int whichItem, View view, ViewGroup viewGroup){
if(view == null){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, viewGroup, false);
}
//Grab a referece to all our TextView and ImageView Widgets
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivImportant = (ImageView) view.findViewById(R.id.imageViewImportant);
ImageView ivToDo = (ImageView) view.findViewById(R.id.imageTodo);
ImageView ivIdea = (ImageView) view.findViewById(R.id.imageViewIdea);
Note tempNote = noteList.get(whichItem);
if(!tempNote.ismImportant() && mAnimOption != SettingsActivity.NONE){
view.setAnimation(mAnimFlash);
}
else{
view.setAnimation(mAnimFadeIn);
}
if(!tempNote.ismImportant()){
ivImportant.setVisibility(View.GONE);
}
if(!tempNote.ismTodo()){
ivToDo.setVisibility(View.GONE);
}
if(!tempNote.ismIdea()){
ivIdea.setVisibility(View.GONE);
}
txtTitle.setText(tempNote.getmTitle());
txtTitle.setText(tempNote.getmDescription());
return view;
}
public void deleteNote(int n){
noteList.remove(n);
notifyDataSetChanged();
}
public void addNote(Note n){
noteList.add(n);
notifyDataSetChanged();
}
}
protected void onResume(){
super.onResume();
mPrefs = getSharedPreferences("Note to Self", MODE_PRIVATE);
mSound = mPrefs.getBoolean("sound", true);
mAnimOption = mPrefs.getInt("anim option",SettingsActivity.FAST);
mAnimFlash = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.flash);
mAnimFadeIn= AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
//set the rate of flash based on settings
if(mAnimOption == SettingsActivity.FAST) {
mAnimFlash.setDuration(100);
Log.i("anime = ", "" + mAnimOption);
}else if(mAnimOption == SettingsActivity.SLOW)
{
mAnimFlash.setDuration(1000);
Log.i("anime = ", "" + mAnimOption);
}
mNoteAdapter.notifyDataSetChanged();;
}
protected void onPause(){
}
}
Note.java
public class Note {
private String mTitle;
private String mDescription;
private boolean mIdea;
private boolean mTodo;
private boolean mImportant;
private static final String JSON_TITLE = "title";
private static final String JSON_DESCRIPTION = "description";
private static final String JSON_IDEA = "idea";
private static final String JSON_TODO= "todo";
private static final String JSON_IMPORTANT = "important";
//constructor
public Note(JSONObject jo) throws JSONException{
mTitle = jo.getString(JSON_TITLE);
mDescription = jo.getString(JSON_DESCRIPTION);
mIdea = jo.getBoolean(JSON_IDEA);
mTodo = jo.getBoolean(JSON_TODO);
mImportant = jo.getBoolean(JSON_IMPORTANT);
}
public Note(){
}
public JSONObject convertToJSON() throws JSONException{
JSONObject jo = new JSONObject();
jo.put(JSON_TITLE,mTitle);
jo.put(JSON_DESCRIPTION,mDescription);
jo.put(JSON_IDEA,mIdea);
jo.put(JSON_TODO,mTodo);
return jo;
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getmDescription() {
return mDescription;
}
public void setmDescription(String mDescription) {
this.mDescription = mDescription;
}
public boolean ismIdea() {
return mIdea;
}
public void setmIdea(boolean mIdea) {
this.mIdea = mIdea;
}
public boolean ismTodo() {
return mTodo;
}
public void setmTodo(boolean mTodo) {
this.mTodo = mTodo;
}
public boolean ismImportant() {
return mImportant;
}
public void setmImportant(boolean mImportant) {
this.mImportant = mImportant;
}
}
JSONserializer.java
public class JSONSerializer {
private String mFilename;
private Context mContext;
public JSONSerializer(String fn, Context con){
mFilename = fn;
mContext = con;
}
public void save(List<Note> notes)throws IOException, JSONException{
//Make an array in JSON fomat
JSONArray jArray = new JSONArray();
//And load it with the notes
for(Note n : notes) {
jArray.put(n.convertToJSON());
//Now write it to the private disk space of our app
Writer writer = null;
try{
OutputStream out = mContext.openFileOutput(mFilename,mContext.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(jArray.toString());
}finally {
if(writer != null){
writer.close();
}
}
}
}
public ArrayList<Note> load() throws IOException,JSONException{
ArrayList<Note> noteList = new ArrayList<Note>();
BufferedReader reader = null;
try{
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
jsonString.append(line);
JSONArray jArray = (JSONArray)new JSONTokener(jsonString.toString()).nextValue();
for (int i = 0; i < jArray.length(); i++)
noteList.add(new Note(jArray.getJSONObject(i)));
}catch (FileNotFoundException e){
//we will ignore this one, since it happens
//when we start fresh, You could add a log here.
}finally{
if (reader != null)
reader.close();
}
return noteList;
}
}
DialogNewNote.java
public class DialogNewNote extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_new_note, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription);
final CheckBox checkBoxIdea = (CheckBox) dialogView.findViewById(R.id.checkBoxIdea);
final CheckBox checkBoxToDo = (CheckBox) dialogView.findViewById(R.id.checkBoxToDo);
final CheckBox checkBoxImportant = (CheckBox) dialogView.findViewById(R.id.checkBoxImportant);
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOk = (Button) dialogView.findViewById(R.id.btnOk);
builder.setView(dialogView).setMessage("Add a new note");
btnCancel.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
dismiss();
}
});
btnOk.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Note newNote = new Note();
newNote.setmTitle(editTitle.getText().toString());
newNote.setmDescription(editDescription.getText().toString());
newNote.setmIdea(checkBoxIdea.isChecked());
newNote.setmTodo(checkBoxToDo.isChecked());
newNote.setmImportant(checkBoxImportant.isChecked());
MainActivity callingActivity = (MainActivity) getActivity();
callingActivity.createNewNote(newNote);
dismiss();
}
});
return builder.create();
}
}
DialogShowNote.java
public class DialogShowNote extends DialogFragment {
public Note mNote;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_show_note, null);
TextView txtTitle = (TextView)dialogView.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView)dialogView.findViewById(R.id.txtDescription);
ImageView ivImportant = (ImageView)dialogView.findViewById(R.id.imageViewImportant);
ImageView ivtoDo = (ImageView)dialogView.findViewById(R.id.imageViewBlank);
ImageView ivIdea = (ImageView)dialogView.findViewById(R.id.imageViewIdea);
if (!mNote.ismImportant()) {
ivImportant.setVisibility(View.GONE);
}
if (!mNote.ismTodo()) {
ivtoDo.setVisibility(View.GONE);
}
if (!mNote.ismIdea()) {
ivIdea.setVisibility(View.GONE);
}
Button btnOK = (Button)dialogView.findViewById(R.id.btnOk);
builder.setView(dialogView).setMessage("Your Note");
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return builder.create();
}
public void sendNoteSelected(Note noteSelected){
mNote = noteSelected;
}
}
Use the shared prefrences to save your data and also use it again to retrive data its simple
I found where I went wrong. I just had to add the saveNote() inside the addNote and that's it.
Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});
I am using custom list view inside fragment(From Api). on orientation change data is still in array list and also list view get notified but it hides when screen rotates.
here is the code:
public class FragNotice extends Fragment implements View.OnClickListener {
ListAdapter listAdapter;
ListView listView;
EditText editTextNotice;
private Button btnSearch;
private Button btnClear;
private int incre = 1;
private boolean boolScroll = true;
public FragNotice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
setRetainInstance(true);
search(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return init(inflater.inflate(R.layout.notice_activity, container, false));
}
private View init(View view) {
editTextNotice = (EditText) view.findViewById(R.id.editTextNotice);
btnSearch = (Button) view.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
btnClear = (Button) view.findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
listView = (ListView) view.findViewById(R.id.listViewNotice);
listView.setOnScrollListener(onScrollListener());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), new ArrayList<ListRowItem>());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
AsyncRequest.OnAsyncRequestComplete onAsyncRequestComplete = new AsyncRequest
.OnAsyncRequestComplete() {
#Override
public void asyncResponse(String response, int apiKey) {
switch (apiKey) {
case 1:
listView(response);
break;
}
}
};
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnClear) {
incre = 1;
boolScroll = true;
editTextNotice.setText(null);
if (listAdapter != null)
listAdapter.clear();
search(true);
} else if (v.getId() == R.id.btnSearch) {
String std = editTextNotice.getText().toString();
if (std.trim().length() > 1) {
incre = 1;
boolScroll = true;
if (listAdapter != null)
listAdapter.clear();
try {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(new View(getActivity()).getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
// TODO: handle exception
}
search(false);
} else
Toast.makeText(getActivity(),
"Please enter atleast two character.", Toast.LENGTH_LONG)
.show();
}
}
class ListAdapter extends ArrayAdapter<ListRowItem> {
private final Context context;
public ListAdapter(Context asyncTask, java.util.List<ListRowItem> items) {
super(asyncTask, R.layout.notice_listitem, items);
this.context = asyncTask;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final ListRowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notice_listitem, parent, false);
holder = new ViewHolder();
holder.txtSno = (TextView) convertView.findViewById(R.id.txtSno);
holder.txtNoticePublishDate = (TextView) convertView.findViewById(R.id
.txtNoticePublishDate);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.txtNoticeDescription = (TextView) convertView.findViewById(R.id
.txtNoticeDescription);
holder.txtNoticeName = (TextView) convertView.findViewById(R.id.txtNoticeName);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtSno.setText(String.valueOf(position + 1));
holder.txtNoticeDescription.setText(new AppUtility().TitleCase(rowItem.getDescription
()));
holder.txtNoticeName.setText(new AppUtility().TitleCase(rowItem.getFileTitle()));
try {
holder.txtNoticePublishDate.setText(String.valueOf((new SimpleDateFormat("dd MMM " +
"yyyy HH:mm:ss", Locale.US)).format((new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ss", Locale.US)).parse(rowItem.getUpdateDate()))));
} catch (ParseException e) {
holder.txtNoticePublishDate.setText(new AppUtility().TitleCase(rowItem
.getUpdateDate()));
}
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return convertView;
}
/*private view holder class*/
private class ViewHolder {
TextView txtSno;
TextView txtNoticeName;
TextView txtNoticeDescription;
TextView txtNoticePublishDate;
Button btnView;
}
}
class ListRowItem {
private final String FileTitle;
private final String Description;
private final String ContentType;
private final int DocumentUploadID;
private final String UpdateDate;
ListRowItem() {
this.FileTitle = "";
this.Description = "";
this.ContentType = "";
this.DocumentUploadID = 0;
this.UpdateDate = "";
}
ListRowItem(String fileTitle, String description, String contentType, int
documentUploadID, String updateDate) {
this.FileTitle = fileTitle;
this.Description = description;
this.ContentType = contentType;
this.DocumentUploadID = documentUploadID;
this.UpdateDate = updateDate;
}
public String getFileTitle() {
return FileTitle;
}
public int getDocumentUploadID() {
return DocumentUploadID;
}
public String getUpdateDate() {
return UpdateDate;
}
public String getDescription() {
return Description;
}
public String getContentType() {
return ContentType;
}
}
private void listView(String response) {
try {
ArrayList<ListRowItem> lstItem;
if(listAdapter==null){
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
listAdapter = new ListAdapter(getActivity(), lstItem);
} else {
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
listAdapter.addAll(lstItem);
} else {
for (ListRowItem items : lstItem) {
listAdapter.add(items);
}
}
}
if (listAdapter != null)
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
private AbsListView.OnScrollListener onScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 5;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold) {
if (boolScroll) {
if (editTextNotice.getText().toString().trim().length() > 0)
search(false);
else
search(true);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
private void search(boolean bool) {
String URL;
if (bool) {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/0/" + incre;
incre = incre + 1;
} else {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/" +
editTextNotice.getText().toString().trim() + "/" + incre;
incre = incre + 1;
}
AsyncRequest asyncRequest;
if (incre > 2)
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
null, 1);
else
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
"Fetching data", 1);
asyncRequest.execute(URL);
}
}
You need to load the data into the ListView again. You are binding the ListView to an adapter, you need to do it in onConfigurationChanged() method.
When orientation changes the activity reloads again.So you have to override onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Your Code Here
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Your Code Here
}
}
create a directory layout-land in the resources copy the your .xml file there align and set the Edittext and Button according to landscape layout .may be it solved your problem if the listview doest not get enough space to show in landscape layout
In onViewCreated(View view, Bundle savedInstanceState) method above you are setting new empty arraylist every time. So the previous items which are loaded are removed from adapter even though it is retained by setRetainInstance(true)
So you should have a Field that holds the arraylist and pass that field to adapter
private ArrayList<ListRowItem> listItems = new ArrayList<>()
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), listItems);//pass the Arraylist here
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
Then in private void listView(String response) method, add items to that listview created above as
listItems = new Gson().fromJson(response, listType);
listAdapter.notifyDataSetChanged();
Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}
The problem is that when i stretch up the pullToRefreshLiew (similar to listview), the memory the application occupy will be increasing step by step. I have tried many methods from the internet, but the bug still exists.
When i stretch up the pullToRefreshLiew, the memory will increasing to 90m
from 50m gradually.
Here is my memory monitor:
Here is my code below: (I omit the import code)
if you need my xml code,i will paste them as well.I am very grateful to you for your help.
public class YuerjingActivity extends CommonActivity implements View.OnClickListener {
private RelativeLayout back;
private int baseid;
private PullToRefreshListView pullToRefreshListView;
private ArrayList<ForumListItem> forumListItems = new ArrayList<ForumListItem>();
private MyAdapter myAdapter;
private LinearLayout noTip;
private RelativeLayout postForum;
static class ViewHolder1 {
TextView title;
TextView line;
}
static class ViewHolder2 {
private ImageView avatar;
private TextView name;
private TextView time;
private ImageView huo;
private ImageView jing;
private TextView title;
private LinearLayout pics;
private ImageView img1;
private ImageView img2;
private ImageView img3;
private ImageView img4;
private TextView replynum;
}
protected class MyAdapter extends BaseAdapter {
public MyAdapter() {
}
public int getCount() {
return forumListItems.size();
}
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int t = getItemViewType(position);
ViewHolder1 viewHolder1 = null;
ViewHolder2 viewHolder2 = null;
ForumListItem forumListItem = forumListItems.get(position);
if (convertView == null) {
if (t == 1) {
convertView = getLayoutInflater().inflate(R.layout.item_top, null);
viewHolder1 = new ViewHolder1();
viewHolder1.title = (TextView) convertView.findViewById(R.id.title);
viewHolder1.line = (TextView) convertView.findViewById(R.id.top_line);
convertView.setTag(viewHolder1);
} else {
convertView = getLayoutInflater().inflate(R.layout.common_forum_item, null);
viewHolder2 = new ViewHolder2();
viewHolder2.avatar = (ImageView) convertView.findViewById(R.id.avatar);
viewHolder2.name = (TextView) convertView.findViewById(R.id.name);
viewHolder2.time = (TextView) convertView.findViewById(R.id.time);
viewHolder2.jing = (ImageView) convertView.findViewById(R.id.jing);
viewHolder2.huo = (ImageView) convertView.findViewById(R.id.huo);
viewHolder2.pics = (LinearLayout) convertView.findViewById(R.id.pics);
viewHolder2.img1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder2.img2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder2.img3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder2.img4 = (ImageView) convertView.findViewById(R.id.img4);
viewHolder2.replynum = (TextView) convertView.findViewById(R.id.replynum);
viewHolder2.title = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(viewHolder2);
}
} else {
if (t == 1) {
viewHolder1 = (ViewHolder1) convertView.getTag();
} else {
viewHolder2 = (ViewHolder2) convertView.getTag();
}
}
if (t == 1) {
viewHolder1.title.setText(forumListItem.getTitle());
if (position + 1 < getCount()) {
if (forumListItems.get(position + 1).getIs_top() == 0) {
viewHolder1.line.setVisibility(View.VISIBLE);
} else {
viewHolder1.line.setVisibility(View.GONE);
}
} else {
viewHolder1.line.setVisibility(View.GONE);
}
} else {
if (forumListItem.getAvatar() == null) {
viewHolder2.avatar.setImageResource(R.drawable.user);
} else {
ImageLoader.getInstance().displayImage(forumListItem.getAvatar(), viewHolder2.avatar, UIL.getOption3());
}
viewHolder2.name.setText(forumListItem.getName());
viewHolder2.time.setText(DateUtils.toNow(forumListItem.getTime()));
viewHolder2.title.setText(forumListItem.getTitle());
if (forumListItem.getIs_hot() == 1) {
viewHolder2.huo.setVisibility(View.VISIBLE);
} else {
viewHolder2.huo.setVisibility(View.GONE);
}
if (forumListItem.getIs_rec() == 1) {
viewHolder2.jing.setVisibility(View.VISIBLE);
} else {
viewHolder2.jing.setVisibility(View.GONE);
}
viewHolder2.replynum.setText(forumListItem.getReplynum());
viewHolder2.img1.setVisibility(View.GONE);
viewHolder2.img2.setVisibility(View.GONE);
viewHolder2.img3.setVisibility(View.GONE);
viewHolder2.img4.setVisibility(View.GONE);
for (int i = 0; i < forumListItem.pics.size(); i++) {
if (i == 0) {
viewHolder2.pics.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img1, UIL.getOptions(R.drawable.info_head));
viewHolder2.img1.setVisibility(View.VISIBLE);
}
if (i == 1) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img2, UIL.getOptions(R.drawable.info_head));
viewHolder2.img2.setVisibility(View.VISIBLE);
}
if (i == 2) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img3, UIL.getOptions(R.drawable.info_head));
viewHolder2.img3.setVisibility(View.VISIBLE);
}
if (i == 3) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img4, UIL.getOptions(R.drawable.info_head));
viewHolder2.img4.setVisibility(View.VISIBLE);
}
}
}
return convertView;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return forumListItems.get(position).getIs_top();
}
}
private static class ForumListItem {
private String avatar;
private String name;
private String time;
private int is_hot;
private int is_rec;
private int has_pic;
private int is_top;
private String title;
private String replynum;
private int id;
public ArrayList<String> pics = new ArrayList<String>();
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getIs_top() {
return is_top;
}
public void setIs_top(int is_top) {
this.is_top = is_top;
}
public int getHas_pic() {
return has_pic;
}
public void setHas_pic(int has_pic) {
this.has_pic = has_pic;
}
public int getIs_rec() {
return is_rec;
}
public void setIs_rec(int is_rec) {
this.is_rec = is_rec;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getReplynum() {
return replynum;
}
public void setReplynum(String replynum) {
this.replynum = replynum;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yuerjing);
init();
}
private void init() {
back = generateFindViewById(R.id.back);
back.setOnClickListener(this);
baseid = 0;
noTip = generateFindViewById(R.id.notip);
pullToRefreshListView = generateFindViewById(R.id.quanzi);
myAdapter = new MyAdapter();
pullToRefreshListView.setAdapter(myAdapter);
pullToRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
pullToRefreshListView.setOnRefreshListener(new MyOnRefreshListener2());
pullToRefreshListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (HttpUtil.isNetworkConnected(getApplicationContext())) {
Intent intent = new Intent(YuerjingActivity.this, NewForumActivity.class);
intent.putExtra("postid", forumListItems.get(position - 1).getId());
startActivity(intent);
} else {
}
}
});
postForum = generateFindViewById(R.id.xiexie);
postForum.setOnClickListener(this);
getList("new");
}
class MyOnRefreshListener2 implements PullToRefreshBase.OnRefreshListener2<ListView> {
public MyOnRefreshListener2() {
}
#Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
getList("new");
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
getList("old");
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
private void getList(final String dir) {
if (HttpUtil.isNetworkConnected(getApplicationContext())) {
RequestQueue m_queue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
String param = "";
String url = "";
try {
if (UserInfo.getInstance().getHaslogin(getApplicationContext()) == -1 || UserInfo.getInstance().getHaslogin(getApplicationContext()) == 0) {
object.put("uid", 0);
} else {
object.put("uid", UserInfo.getInstance().getUserId(getApplicationContext()));
object.put("token", UserInfo.getInstance().getAccessToken(getApplicationContext()));
}
object.put("utype", 1);
object.put("posttype", "2");
object.put("classid", "0");
object.put("pagesize", 10);
object.put("dir", dir);
if (!dir.equals("new")) {
object.put("baseid", baseid);
}
param = object.toString();
url = Rpc.m_rpc_url + "&message=" + "USER_GET_ARTICLES3" + "&data=" + java.net.URLEncoder.encode(param, "utf-8");
System.err.println(url);
System.err.println(baseid);
} catch (Exception e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String result = response.toString();
JSONObject indexData = Utils.getInfoJsonObject(result);
boolean flag = indexData.getBoolean("ret");
int flagCode = indexData.getInt("retCode");
if (!flag) {
} else {
if (flagCode == 1) {
if (dir.equals("new")) {
forumListItems.clear();
baseid = 0;
}
String avatar_header = indexData.getString("avatar_header");
JSONArray jsonArray = indexData.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
ForumListItem forumListItem = new ForumListItem();
if (jsonArray.getJSONObject(i).getString("author_avatar").equals("null") || jsonArray.getJSONObject(i).getString("author_avatar") == null) {
forumListItem.setAvatar(null);
} else {
forumListItem.setAvatar(avatar_header + jsonArray.getJSONObject(i).getString("author_avatar"));
}
forumListItem.setName(jsonArray.getJSONObject(i).getString("author_name"));
forumListItem.setTime(jsonArray.getJSONObject(i).getString("post_time"));
forumListItem.setReplynum(jsonArray.getJSONObject(i).getString("replynum"));
forumListItem.setTitle(jsonArray.getJSONObject(i).getString("title"));
forumListItem.setId(jsonArray.getJSONObject(i).getInt("id"));
if (jsonArray.getJSONObject(i).getInt("is_hot") == 1) {
forumListItem.setIs_hot(1);
} else {
forumListItem.setIs_hot(0);
}
if (jsonArray.getJSONObject(i).getInt("has_pic") == 1) {
forumListItem.setHas_pic(1);
} else {
forumListItem.setHas_pic(0);
}
if (jsonArray.getJSONObject(i).getInt("is_rec") == 1) {
forumListItem.setIs_rec(1);
} else {
forumListItem.setIs_rec(0);
}
if (jsonArray.getJSONObject(i).getInt("is_top") == 1) {
forumListItem.setIs_top(1);
} else {
forumListItem.setIs_top(0);
}
if (forumListItem.getHas_pic() == 1 && jsonArray.getJSONObject(i).has("pics")) {
JSONArray pics = jsonArray.getJSONObject(i).getJSONArray("pics");
for (int j = 0; j < pics.length(); j++) {
forumListItem.pics.add(avatar_header + pics.getJSONObject(j).getString("srcurl"));
}
}
forumListItems.add(forumListItem);
}
}else {
Toast.makeText(getApplicationContext(), "retCode=" + flagCode, Toast.LENGTH_SHORT).show();
}
myAdapter.notifyDataSetChanged();
pullToRefreshListView.onRefreshComplete();
if (forumListItems.size() > 0 && forumListItems.get(forumListItems.size() - 1).getIs_top() == 0) {
baseid = forumListItems.get(forumListItems.size() - 1).getId();
} else {
baseid = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pullToRefreshListView.onRefreshComplete();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
m_queue.add(jsonObjectRequest);
m_queue.start();
} else {
pullToRefreshListView.postDelayed(new Runnable() {
#Override
public void run() {
pullToRefreshListView.onRefreshComplete();
}
}, 500);
}
}
}