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.
Related
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);
}
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] answers = new String[]{"choice0","choice2","choice0","choice1","choice3","choice3"};
Question[] questions = new Question[6];
for(int i=0; i<6; i++){
questions[i] = new Question("Question"+(1+i),new String[]{"choice0","choice1","choice2","choice3"},answers[i]);
}
ListView listView = (ListView)findViewById(R.id.listQuestions);
QuestionAdapter questionAdapter = new QuestionAdapter(this, R.layout.list_item_row_qs, questions);
listView.setAdapter(questionAdapter);
}
}
Adapter
public class QuestionAdapter extends ArrayAdapter {
Context context;
Question[] questions;
View view;
public QuestionAdapter(Context context, int id, Question[] questions){
super(context, id, questions);
this.context = context;
this.questions = questions;
}
private class ViewHolder{
TextView chapName;
RadioButton rb0;
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
Button button;
RadioGroup rg;
TextView hiddenAnswer;
}
#Override
public View getView(int pos, View row, ViewGroup parent){
this.view = row;
ViewHolder viewHolder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item_row_qs, null);
viewHolder = new ViewHolder();
viewHolder.chapName=(TextView) row.findViewById(R.id.question);
viewHolder.rb0 = (RadioButton) row.findViewById(R.id.choice0);
viewHolder.rb1 = (RadioButton) row.findViewById(R.id.choice1);
viewHolder.rb2 = (RadioButton) row.findViewById(R.id.choice2);
viewHolder.rb3 = (RadioButton) row.findViewById(R.id.choice3);
viewHolder.button = (Button) row.findViewById(R.id.check);
viewHolder.hiddenAnswer = (TextView) row.findViewById(R.id.answer);
row.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)row.getTag();
}
viewHolder.chapName.setText(questions[pos].getQuestionDescr());
viewHolder.rb0.setText(questions[pos].getChoice()[0]);
viewHolder.rb1.setText(questions[pos].getChoice()[1]);
viewHolder.rb2.setText(questions[pos].getChoice()[2]);
viewHolder.rb3.setText(questions[pos].getChoice()[3]);
viewHolder.hiddenAnswer.setText(questions[pos].getAnswer());
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowView = (ViewGroup) v.getParent();
RadioGroup group = (RadioGroup) rowView.findViewById(R.id.rg);
int selectedId = group.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(context, "Please choose the correct option", Toast.LENGTH_LONG).show();
} else {
RadioButton radioButton = (RadioButton) group.findViewById(selectedId);
String answer = String.valueOf(((TextView) rowView.findViewById(R.id.answer)).getText());
if (radioButton.getText().equals(answer)) {
Toast.makeText(context, "Correct Answer", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Wrong Answer", Toast.LENGTH_LONG).show();
}
}
}
});
return row;
}
}
Problem
First item in the list maps to 5th item. 2nd item to sixth item. I mean if I change radio button at the first item, Same radio button gets selected at the 5th list item also.
Any suggestions?
Is it because of recycling?
How do I resolve it?
I tried saving in Question object and retrieving it. I used pos to retrieve and set. But same problem still exist.
Adapter:
public class PersonAdapter extends BaseAdapter
{
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
}
Activity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
// _adapter = new PersonAdapter(this, _data);
// _listView.setAdapter(_adapter);
RedirectToMainActivityTask task = new RedirectToMainActivityTask();
task.execute();
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
private class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Intent intent = new Intent( getApplicationContext(), SecondActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
}
}
I am saving the state of the person view inside of person object
I have some problem. when I click a delete(btnPlus.setOnClickListener in the interestAdepter class) button from listview baseAdapter, I want to refresh the fragment which contains the listview.
1.InterestAdapter class{edtied}
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
public InterestAdapter() {
m_List = new ArrayList<InterestClass>();
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
2.InterestFragment{edited}
public class InterestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private ListView interest_ListView;
private InterestAdapter interest_Adapter;
String TAG="response";
RbPreference keep_Login;
public InterestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment InterestFragment.
*/
// TODO: Rename and change types and number of parameters
public static InterestFragment newInstance(String param1, String param2) {
InterestFragment fragment = new InterestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
keep_Login = new RbPreference(getContext());
Log.v("interFrag","oncreate");
// Inflate the layout for this fragment
/*if(keep_Login.get("name",null)!=null) {
return inflater.inflate(R.layout.fragment_interest, container, false);
}else{
return inflater.inflate(R.layout.need_login, container, false);
}*/
return inflater.inflate(R.layout.fragment_interest, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("ListFragment", "onActivityCreated().");
Log.v("ListsavedInstanceState", savedInstanceState == null ? "true" : "false");
if(keep_Login.get("no",null)!=null) {
String enc_Id="";
Crypto enc=new Crypto();
try{
enc_Id=enc.AES_Encode(keep_Login.get("no",null),enc.global_deckey);
}catch(Exception e){
}
interest_Adapter = new InterestAdapter();
interest_ListView = (ListView) getView().findViewById(R.id.i_ListView);
AsyncCallInterest task = new AsyncCallInterest();
task.execute(enc_Id);
}
}
private class AsyncCallInterest extends AsyncTask<String, Void, JSONArray> {
JSONArray interest_Array;
InterestFragment interest;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected JSONArray doInBackground(String... params) {
String id=params[0];
dbConnection db_Cont=new dbConnection();
interest_Array=db_Cont.getFavorite(id);
Log.v("doinbackgroud", interest_Array.toString());
return interest_Array;
}
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interest_Adapter.add(i_Class);
}
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Is there any way to refresh the fragment from the button in baseAdapter class? I searched a lot but I couldn't fine answer. Please help me, Thank you.
{edited}
I add AsyncCallAddDelFavorite class and AsyncCallInterest class. Thank you.
Update your adapter constructor. After deleting content, remove the item from the arraylist and notify dataset changed.
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
private Context mContext;
public InterestAdapter(Context context, ArrayList<InterestClass> list) {
m_List = list;
mContext = context;
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
**m_List.remove(position);
notifyDatasetChanged();**
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
Update Adapter initialization in fragment. You are adding item to adapter directly. Use arraylist and after downloading data create adapter instance.
private ArrayList<InterestClass> interestList = new ArrayList<>();
and update your onPostExecute Method
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interestList.add(i_Class);
}
interest_Adapter = new InterestAdapter(getActivity,interestList);
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
If I understand you correctly you want to remove the item from your ListView too after your removing it from your Database, to achieve that you can call this
m_List.remove(position);
interest_Adapter..notifyDataSetChanged();
First line removes the item and Second one will insure that the Adapter gets updated after the item has been removed.
Hope this helps
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);
}
}
Hello and greetings i am developing one app that accept multiple images from user and upload to server but images upload to server is ok.I just added one edittext to enter quantity of image but i am unable to get value from that respective edittext.so give me suggestion in my code.
i have edittext in gridview so i want to get text from edittext that is quantity of image so please help me
uploadphoto.java
public class UploadPhotos extends AppCompatActivity {
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
ProgressDialog progressDialog;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photos);
context = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.main_content);
labSession = new SelectLab(getApplicationContext());
paperSession = new SelectPaper(getApplicationContext());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
user_mail = user.get(SessionManager.KEY_EMAIL);
noImage = (TextView)findViewById(R.id.noImage);
final String symbol = getResources().getString(R.string.rupee_symbol);
HashMap<String, String> paper = paperSession.getPaperDetails();
strSize = paper.get(SelectPaper.KEY_SIZE);
strType = paper.get(SelectPaper.KEY_TYPE);
strdel_type=paper.get(SelectPaper.DEL_TYPE);
HashMap<String, String> lab = labSession.getLabDetails();
strMRP = lab.get(SelectLab.KEY_MRP);
strPrice = lab.get(SelectLab.KEY_PRICE);
strlab = lab.get(SelectLab.KEY_LAB);
strcity = lab.get(SelectLab.KEY_CITY);
str_username=lab.get(SelectLab.KEY_USERNAME);
//Toast.makeText(getApplicationContext(),""+strSize+"\n"+strType+"\n"+strMRP+"\n"+strPrice+"\n"+strlab+"\n"+strcity,Toast.LENGTH_LONG).show();
ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
mrp = (MaterialEditText) findViewById(R.id.MRP);
disPrice = (MaterialEditText) findViewById(R.id.discount_price);
ppr_size.setText(strSize);
ppr_type.setText(strType);
mrp.setText(symbol + " " + strMRP);
disPrice.setText(symbol + " " + strPrice);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
UploadGallery = (GridView) findViewById(R.id.uploadGallery);
UploadGallery.setFastScrollEnabled(true);
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
UploadGallery.setAdapter(selectedAdapter);
btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
btnUpload = (Button) findViewById(R.id.btn_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listOfPhotos = selectedAdapter.getAll();
if (listOfPhotos != null && listOfPhotos.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
abc = sdf.format(new Date());
abc="EPP"+abc;
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();
//progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
progressDialog=new ProgressDialog(UploadPhotos.this);
progressDialog.setMessage("Images is Uploading.......");
progressDialog.setCancelable(false);
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.mp3));
progressDialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
doFileUpload();
runOnUiThread(new Runnable() {
public void run() {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
totalprice=0;
}
Intent i=new Intent(UploadPhotos.this,Digital_Cart.class);
startActivity(i);
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
selectedAdapter.changeSelection(view, position);
}
});
}
private void doFileUpload() {
for( i = 0 ; i<listOfPhotos.size();i++) {
final CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(i);
File f = new File(objDetails.sdcardPath);
imageName = f.getName();
totalprice=totalprice+Long.parseLong(strPrice);
total=String.valueOf(totalprice);
Log.v("Abhijit",""+totalprice);
// Toast.makeText(getApplicationContext(),""+totalprice,Toast.LENGTH_LONG).show();
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://eeee.com/aaaaa/UploadFile?foldername="+abc); //TODO - to hit URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
// publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strSize));
Log.v("svbh", strSize);
entity.addPart("type",
new StringBody(strType));
entity.addPart("username",
new StringBody(user_mail));
entity.addPart("total",
new StringBody(total));
entity.addPart("mrp",
new StringBody(strMRP));
entity.addPart("price",
new StringBody(strPrice));
entity.addPart("lab",
new StringBody(strlab));
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
String initflag=String.valueOf(i+1);
entity.addPart("initflag",
new StringBody(initflag));
entity.addPart("lab_username",
new StringBody(str_username));
// totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
final String response_str = EntityUtils.toString(r_entity);
if (r_entity != null) {
Log.i("RESPONSE", response_str + "" + imageName);
runOnUiThread(new Runnable(){
public void run() {
try {
snackbar = Snackbar
.make(coordinatorLayout, i+" image "+response_str, Snackbar.LENGTH_LONG)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View view) {
snackbar.dismiss();
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
//Toast.makeText(getApplicationContext(),i+" image "+response_str, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
noImage.setVisibility(View.GONE);
UploadGallery.setVisibility(View.VISIBLE);
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
Log.d("DATAt",dataT.toString());
selectedAdapter.addAll(dataT);
}
}
}
and selected_adapter_test
public class SelectedAdapter_Test extends BaseAdapter{
private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
mContext = c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageLoader = imageLoader;
// clearCache();
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgEdit;
EditText qty;
Button ok;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
} else {
data.get(position).isSeleted = true;
((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
}
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty= 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public ArrayList getAll(){
return data;
}
}
And customGallery.java
public class CustomGallery {
public String sdcardPath;
public int qty;
EditText aaa;
public boolean isSeleted;
}
so please help to get text from edittext that is quantity.i cant figure out the problem from last one week.
Thanks in advance
Here is the code :
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.qty.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// save your text here
data.get(i).qty= 1;
}
});
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty= 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}