display description of news in another activity - android

I need to display description of news in ShowNews activity and I used the intent
and put extra method to pass the description to the ShowNews Activity that contain a textview for setting Description. What is wrong in my code?
public class Downloader extends AsyncTask<Void,Void,Object> {
Context c;
String urlAddress ;
ListView lv;
ProgressDialog pd;
public Downloader(Context c,String urlAddress,ListView lv)
{
this.c = c;
this.urlAddress =urlAddress;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetching Data");
pd.setMessage("Fetchinf Data...please wait ");
pd.show();
}
#Override
protected Object doInBackground(Void... voids) {
return this.downloadData();
}
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Object data) {
super.onPostExecute(data);
pd.dismiss();
if (data.toString().startsWith("Error"))
{
Toast.makeText(c,data.toString(),Toast.LENGTH_LONG).show();
}
else {
// parsing
new ReadRss(c, (InputStream) data,lv).execute();
}
}
private Object downloadData()
{
Object connection = Connector.connect(urlAddress);
if (connection.toString().startsWith("Error"))
{
return connection.toString();
}
try {
HttpURLConnection con = (HttpURLConnection) connection;
int responsecode = con.getResponseCode();
if (responsecode == con.HTTP_OK) {
InputStream is = new BufferedInputStream(con.getInputStream());
return is;
}
return ErrorTracer.RESPONSE_ERROR+con.getResponseMessage();
} catch (IOException e) {
e.printStackTrace();
return ErrorTracer.IO_ERROR;
}
}
}
public class ReadRss extends AsyncTask<Void,Void,Boolean> {
Context c;
InputStream is;
ListView lv;
ProgressDialog pd;
CustomAdapter adapter ;
ArrayList<Site> sites = new ArrayList<>();
public ReadRss(Context c,InputStream is,ListView lv)
{
this.c = c;
this.is =is;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("parsing Data");
pd.setMessage("parsing Data...please wait ");
pd.show();
}
#Override
protected Boolean doInBackground(Void... voids) {
return this.parseRss();
}
#Override
protected void onPostExecute(Boolean isparsed) {
super.onPostExecute(isparsed);
pd.dismiss();
if (isparsed)
{
//bind
lv.setAdapter(new CustomAdapter(c,sites));
}
else {
Toast.makeText(c,"Unable to parse",Toast.LENGTH_LONG).show();
}
}
private Boolean parseRss()
{
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(is,null);
int event = parser.getEventType();
String value = null;
sites.clear();
Site site = new Site();
do {
String name = parser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
if (name.equals("item"))
{
site = new Site();
}
break;
case XmlPullParser.TEXT:
value = parser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("title"))
{
site.setTitle(value);
}else if (name.equals("description"))
{
site.setDescription(value);
}else if (name.equals("pubDate"))
{
site.setData(value);
}else if (name.equals("link"))
{
site.setLink(value);
}
if (name.equals("item"))
{
sites.add(site);
}
break;
}
event = parser.next();
}while (event!=XmlPullParser.END_DOCUMENT);
return true;
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Site> sites;
public CustomAdapter(Context c,ArrayList<Site> sites)
{
this.c = c;
this.sites = sites;
}
#Override
public int getCount() {
return sites.size();
}
#Override
public Object getItem(int i) {
return sites.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view==null)
{
view = LayoutInflater.from(c).inflate(R.layout.row,viewGroup,false);
}
TextView titletxt = (TextView) view.findViewById(R.id.textView);
TextView desctxt = (TextView) view.findViewById(R.id.textView2);
TextView datetxt = (TextView) view.findViewById(R.id.textView3);
Site site = (Site) this.getItem(i);
titletxt.setText(site.getTitle());
desctxt.setText(site.getDescription());
datetxt.setText(site.getData());
return view;
}
}
public class MainActivity extends AppCompatActivity {
String ulrAddress = "http://www.alahlytv.net/Rss_Feeds.aspx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this,ShowNews.class);
Site site = new Site();
intent.putExtra("one",site.getDescription());
startActivity(intent);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Downloader(MainActivity.this,ulrAddress,lv).execute();
}
});
public class ShowNews extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_news);
TextView textView = (TextView) findViewById(R.id.textView4);
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null)
{
String getName = (String) bd.get("one");
textView.setText(getName);
}
}
}

When you add any extra in your intent, don't try to get it from the Bundle. So change your reading passed data code to:
Intent intent = getIntent();
String getName = intent.getStringExtra("one", "default_value_if_null");
textView.setText(getName);

change your code like this
Intent intent = getIntent();
if(intent != null)
{
String getName = intent.getExtras().getString("one");
textView.setText(getName);
}

Related

Listview is empty again after restarting app Android

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.

Search Filter moves to tab fragments

I am working on an Activity which is a search page. It contains some values with edittext and spinner. After giving the values and clicking on search button it moves to tab fragments, there contains search results divided by three tabs (By date, By price, By city). I just tested to do on date first but it is not displaying. Please help me on this.
Search Page:
public class Search extends AppCompatActivity {
EditText name,to,from;
Spinner cscope,strainer,sinstitute,scity,scountry,cstype,sgender,sdisable,sprice;
String[] able={"Yes","No"};
String[] sex={"Male only","Female only","Both Male and Female"};
String[] price={"Free","1900S.R","1500S.R"};
String[] city={"Riyadh"};
Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
name= (EditText) findViewById(R.id.search_csname);
cscope= (Spinner) findViewById(R.id.search_scope);
strainer= (Spinner) findViewById(R.id.search_trainerName);
sinstitute= (Spinner) findViewById(R.id.search_instName);
scity= (Spinner) findViewById(R.id.search_city);
scountry= (Spinner) findViewById(R.id.search_country);
cstype= (Spinner) findViewById(R.id.search_ctype);
sgender= (Spinner) findViewById(R.id.search_gender);
sdisable= (Spinner) findViewById(R.id.search_disabled);
sprice= (Spinner) findViewById(R.id.search_price);
search= (Button) findViewById(R.id.searchNow);
ArrayAdapter<String> gen=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,sex);
gen.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sgender.setAdapter(gen);
ArrayAdapter<String> disableness=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,able);
disableness.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sdisable.setAdapter(disableness);
ArrayAdapter<String> pricess=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,price);
pricess.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sprice.setAdapter(pricess);
ArrayAdapter<String> cities=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,city); cities.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
scity.setAdapter(cities);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String sname=name.getText().toString();
final String seprice=sprice.getSelectedItem().toString();
final String secity=scity.getSelectedItem().toString();
final String sedate=from.getText().toString();
Intent s=new Intent(getApplicationContext(),SearchResults.class);
s.putExtra("csname",sname);
s.putExtra("csprice",seprice);
s.putExtra("cscity",secity);
s.putExtra("csdate",sedate);
startActivity(s);
}
});
}
public void selectToDate(View view){
DialogFragment tofrag=new SelectTodateFragment();
tofrag.show(getSupportFragmentManager(),"Date Picker");
}
public void poptoDate(int date,int month,int year){
to= (EditText) findViewById(R.id.search_to);
assert to != null;
to.setText(date+"/"+month+"/"+year);
}
#SuppressLint("ValidFragment")
public class SelectTodateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar tocal=Calendar.getInstance();
int yy=tocal.get(Calendar.YEAR);
int mm=tocal.get(Calendar.MONTH);
int dd=tocal.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(DatePicker view, int year, int mm, int dd) {
poptoDate(year, mm+1, dd);
}
}
public void selectFromDate(View view){
DialogFragment newfrag=new SelectFromdateFragment();
newfrag.show(getSupportFragmentManager(),"Date Picker");
}
public void popDate(int date,int month,int year){
from= (EditText) findViewById(R.id.search_from);
assert from != null;
from.setText(date+"/"+month+"/"+year);
}
#SuppressLint("ValidFragment")
public class SelectFromdateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(DatePicker view, int year, int mm, int dd) {
popDate(year, mm+1, dd);
}
}
}
Search Results Page:
public class SearchResults extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
private TabLayout tabs;
private ViewPager viewPager;
Bundle bundle=new Bundle();
private SearchPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tabs = (TabLayout) findViewById(R.id.search_tabLayout);
viewPager = (ViewPager) findViewById(R.id.search_pager);
tabs.addTab(tabs.newTab().setText("By Price"));
tabs.addTab(tabs.newTab().setText("By Date"));
tabs.addTab(tabs.newTab().setText("By City"));
tabs.setTabGravity(tabs.GRAVITY_FILL);
tabs.setHorizontalScrollBarEnabled(false);
pager = new SearchPager(getSupportFragmentManager(), tabs.getTabCount());
viewPager.setAdapter(pager);
Intent h=getIntent();
String cname=h.getStringExtra("csname");
String byprice=h.getStringExtra("csprice");
String bydate=h.getStringExtra("csdate");
String bycity=h.getStringExtra("cscity");
bundle.putString("coname",cname);
bundle.putString("coprice",byprice);
bundle.putString("codate",bydate);
bundle.putString("cocity",bycity);
pager.getData(bundle);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabs));
tabs.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Search pagerAdapter:
public class SearchPager extends FragmentStatePagerAdapter {
int tabCount;
private Bundle args=new Bundle();
public SearchPager(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment tab1 = new SearchPrice();
getData(args);
tab1.setArguments(args);
return tab1;
case 1:
Fragment tab2 = new SearchDate();
getData(args);
tab2.setArguments(args);
return tab2;
case 2:
Fragment tab3 = new SearchCity();
getData(args);
tab3.setArguments(args);
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
public void getData(Bundle bundle) {
this.args=bundle;
}
}
Search BYPrice:
public class SearchPrice extends Fragment {
private ListView listView;
private ProgressDialog mprogress;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private SpriceAdapter adapter;
TextView id;
Handler mHandler;
static String sname;
static String sprice;
public SearchPrice() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_search_price, container, false);
mHandler = new Handler();
id = (TextView) rootView.findViewById(R.id.copriceId);
listView = (ListView) rootView.findViewById(R.id.searchPriceList);
adapter = new SpriceAdapter(getActivity(), alist);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setScrollingCacheEnabled(false);
if (getArguments() != null) {
sname = this.getArguments().getString("coname");
sprice = this.getArguments().getString("coprice");
}
final String turl = "http://adoxsolutions.in/numuww/services/courses";
new ByPrice(this).execute(turl);
return rootView;
}
private class ByPrice extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog;
public ByPrice(SearchPrice activity) {
dialog = new ProgressDialog(activity.getContext());
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Data...");
dialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Void doInBackground(String... turl) {
try {
URL url = new URL(turl[0]);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Course");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jsArray.getJSONObject(k);
final String cid = jobj.getString("id");
final String cn = jobj.getString("course");
final String dt = jobj.getString("date");
map.put("id", cid);
map.put("course", cn);
map.put("date", dt);
map.put("trainer", jobj.getString("trainer"));
map.put("country", jobj.getString("country"));
map.put("city", jobj.getString("city"));
map.put("days", jobj.getString("no_days"));
map.put("hours", jobj.getString("tot_hrs"));
map.put("img", jobj.getString("img"));
alist.add(map);
mHandler.post(new Runnable() {
#Override
public void run() {
if (cn.equals(sname) || dt.equals(sprice)) {
Log.d("Value", cid);
id.setText(cid);
listView.setAdapter(adapter);
}
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
class SpriceAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
private Typeface typeface;
public SpriceAdapter(Context c, ArrayList<HashMap<String, String>> list) {
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final String id = MyArr.get(position).get("id");
if (convertView != null) {
convertView = inflater.inflate(R.layout.searchlist, parent, false);
TextView cname = (TextView) convertView.findViewById(R.id.searchlistName);
TextView tname = (TextView) convertView.findViewById(R.id.strainerName);
TextView country = (TextView) convertView.findViewById(R.id.searchcoName);
TextView city = (TextView) convertView.findViewById(R.id.searchciName);
TextView date = (TextView) convertView.findViewById(R.id.sdateTime);
TextView time = (TextView) convertView.findViewById(R.id.scourseTime);
TextView hours = (TextView) convertView.findViewById(R.id.scourseHours);
ImageView image = (ImageView) convertView.findViewById(R.id.scphoto);
String cn = (MyArr.get(position).get("course"));
String tn = (MyArr.get(position).get("trainer"));
String co = (MyArr.get(position).get("country"));
String ci = (MyArr.get(position).get("city"));
String dat = (MyArr.get(position).get("date"));
String dys = (MyArr.get(position).get("days"));
String hrs = (MyArr.get(position).get("hours"));
String c = context.getString(R.string.comma);
String ob = " ( ";
String cb = " ) ";
String h = " Hours";
String d = " Days";
String trainerName = tn + c;
String cdays = dys + d;
String chrs = ob + hrs + h + cb;
try {
if(hrs != null || !hrs.equals("")) {
String h1="0 Hours";
String chs=ob + h1 + cb;
hours.setText(chs);
}else{
hours.setText(chrs);
}
// image.setImageBitmap(loadBitmap(hlist.get(position).get("img")));
Glide.with(context).load(MyArr.get(position).get("img")).into(image);
cname.setText(cn);
tname.setText(trainerName);
country.setText(co);
city.setText(ci);
date.setText(dat);
time.setText(cdays);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o=new Intent(context,CourseScreen.class);
o.putExtra("id",id);
context.startActivity(o);
}
});
} catch(Exception e){
e.printStackTrace();
}
}
return convertView;
}
}
}
Search ByDate:
public class SearchDate extends Fragment {
private ListView listView;
private ProgressDialog mprogress;
TextView id;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private SdateAdapter adapter;
Handler mHandler;
static String sname;
static String sdate;
public SearchDate() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_search_date, container, false);
mHandler = new Handler();
id= (TextView) rootView.findViewById(R.id.courseId);
listView= (ListView) rootView.findViewById(R.id.searchDateList);
adapter = new SdateAdapter(getActivity(), alist);
listView.setAdapter(adapter);
listView.setScrollingCacheEnabled(false);
adapter.notifyDataSetChanged();
if (getArguments() != null) {
sname = this.getArguments().getString("coname");
sdate = this.getArguments().getString("codate");
}
final String turl = "http://adoxsolutions.in/numuww/services/courses";
new ByDate(this).execute(turl);
return rootView;
}
private class ByDate extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog;
public ByDate(SearchDate activity)
{
dialog = new ProgressDialog(activity.getContext());
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Data...");
dialog.show();
}
protected Void doInBackground(String... turl) {
try {
URL url = new URL(turl[0]);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Course");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jsArray.getJSONObject(k);
final String cid=jobj.getString("id");
final String cn=jobj.getString("course");
final String dt=jobj.getString("date");
map.put("id",cid);
map.put("course",cn);
map.put("date", dt);
map.put("trainer", jobj.getString("trainer"));
map.put("country", jobj.getString("country"));
map.put("city", jobj.getString("city"));
map.put("days", jobj.getString("no_days"));
map.put("hours", jobj.getString("tot_hrs"));
map.put("img", jobj.getString("img"));
alist.add(map);
mHandler.post(new Runnable() {
#Override
public void run() {
if(cn.equals(sname) || dt.equals(sdate) ) {
Log.d("Value",cid);
id.setText(cid);
}
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
class SdateAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
private Typeface typeface;
public SdateAdapter(Context c, ArrayList<HashMap<String, String>> list) {
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final String id = MyArr.get(position).get("id");
final String dt=MyArr.get(position).get("date");
if (convertView != null) {
convertView = inflater.inflate(R.layout.searchlist, parent, false);
TextView cname = (TextView) convertView.findViewById(R.id.searchlistName);
TextView tname = (TextView) convertView.findViewById(R.id.strainerName);
TextView country = (TextView) convertView.findViewById(R.id.searchcoName);
TextView city = (TextView) convertView.findViewById(R.id.searchciName);
TextView date = (TextView) convertView.findViewById(R.id.sdateTime);
TextView time = (TextView) convertView.findViewById(R.id.scourseTime);
TextView hours = (TextView) convertView.findViewById(R.id.scourseHours);
ImageView image = (ImageView) convertView.findViewById(R.id.scphoto);
String cn = (MyArr.get(position).get("course"));
String tn = (MyArr.get(position).get("trainer"));
String co = (MyArr.get(position).get("country"));
String ci = (MyArr.get(position).get("city"));
String dat = (MyArr.get(position).get("date"));
String dys = (MyArr.get(position).get("days"));
String hrs = (MyArr.get(position).get("hours"));
String c = context.getString(R.string.comma);
String ob = " ( ";
String cb = " ) ";
String h = " Hours";
String d = " Days";
String trainerName = tn + c;
String cdays = dys + d;
String chrs = ob + hrs + h + cb;
try {
if(hrs != null || !hrs.equals("")) {
String h1="0 Hours";
String chs=ob + h1 + cb;
hours.setText(chs);
}else{
hours.setText(chrs);
}
// image.setImageBitmap(loadBitmap(hlist.get(position).get("img")));
Glide.with(context).load(MyArr.get(position).get("img")).into(image);
cname.setText(cn);
tname.setText(trainerName);
country.setText(co);
city.setText(ci);
date.setText(dat);
time.setText(cdays);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o=new Intent(context,CourseScreen.class);
o.putExtra("id",id);
context.startActivity(o);
}
});
} catch(Exception e){
e.printStackTrace();
}
}
return convertView;
}
}
}
Same as Search ByCity:

How to increase cart counter and then button click on that

this is my adapter class where i am having a add to cart button
public class ServiceSelectionOptionsListAdapter extends ArrayAdapter<ServiceSelectionOptionsDataModel> {
private Context context;
private int layoutResourceId;
ListView list;
static final String TAG = "LISTT";
HashMap<Integer, Integer> hashMap;
String response;
ProgressDialog pdilog;
SharedPreferences prefs;
String serverresponse1;
private List<ServiceSelectionOptionsDataModel> data;
String custid;
JSONArray _jsonarray;
JSONObject jsonObject;
String subsrvceopid;
String quantity = "1";
String cartcounter;
TextView counter;
public ServiceSelectionOptionsListAdapter(Context context, int layoutResourceId,
List<ServiceSelectionOptionsDataModel> data) {
super(context, R.layout.serviceselectionoptionslist, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
prefs = context.getSharedPreferences(AppConstants.VERIFICATION,
Context.MODE_PRIVATE);
custid = prefs.getString(AppConstants.CUSTOMERID, "");
cartcounter = prefs.getString(AppConstants.CARTITEMCOUNTER, "");
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.optionname = (TextView) row.findViewById(R.id.tvsubserviceoptionname);
holder.addtocart = (Button) row.findViewById(R.id.btnaddtocart);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ServiceSelectionOptionsDataModel item = data.get(position);
holder.optionname.setText(item.getOptionname());
holder.addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
subsrvceopid = data.get(position).getId();
new addtocart().execute(custid, subsrvceopid, quantity);
new cartitemsdetails().execute(custid);
SharedPreferences.Editor editor = context.getSharedPreferences(AppConstants.VERIFICATION, context.MODE_PRIVATE).edit();
editor.putString(AppConstants.SUBSERVIEOPTIONID, subsrvceopid);
editor.commit();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView optionname;
// TextView charges;
Button addtocart;
TextView counter;
}
and this is my activity class where i m getting the size of the cart items list
class cartitemsdetails extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
pdilog = new ProgressDialog(ServiceSelectionOptionsListActivity.this);
pdilog.setMessage("Please Wait....");
pdilog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
String response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/cartdetails?customerid=" + params[0]);
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
size = jsonarray.length();
counter.setText(String.valueOf(size));
if (size == 0 )
{
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
}
if(size>0) {
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
}
pdilog.dismiss();
super.onPostExecute(aVoid);
}
}
class OptionsSelection extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/subserviceoptions?subserviceid=" + params[0]);
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ServiceSelectionOptionsDataModel datamodel = new ServiceSelectionOptionsDataModel();
jsonObject = _jsonarray.getJSONObject(i);
optionname = jsonObject.getString("OptionName");
datamodel.setOptionname(optionname);
charge = jsonObject.getString("Charges");
datamodel.setCharge(charge);
subserviceoptionid = jsonObject.getString("SubServiceOptionID");
datamodel.setId(subserviceoptionid);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ServiceSelectionOptionsListAdapter adapter = new ServiceSelectionOptionsListAdapter(ServiceSelectionOptionsListActivity.this, R.layout.serviceselectionoptionslist, lstDataModel);
options.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}

Problems with notifyDataSetChanged(). All edittext's value is changing

I have search field,When i opened activity i am getting some data, i populated those data into list view Custom row. In custom row i have Text view,edit Text, textViewCancelImage. When i got response from server,parsing those response and fetch into custom rows.After that i enter some data in search field and i will get some suggestions.If i select any suggestion then i am populating same custom row to List View. When i clicked any suggestion i am getting selected value and populating same custom row. But all previous custom row Edit Text's values also changed to 0. And i am unable to delete row when i click cancel Image.
please check Activity
public class MaintainActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog pDialog;
private ResultVO resLogin;
private Button updateMRL,clearMRL;
#InjectView(R.id.listViewReorderLevel)
protected ListView reorderLevelListView;
private AutoCompleteTextView searchField;
OrderAdapter reorderAdapter;
ArrayList<OrderLevelsListBO> OrderLevelsListBOs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reorder_level);
new GetTradeNamesListAsyncTask().execute();
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setIcon(android.R.color.transparent);
updateMRL = (Button) findViewById(R.id.btnUpdateMRL);
clearMRL = (Button) findViewById(R.id.btnClearMRL);
searchField = (AutoCompleteTextView) findViewById(R.id.searchAutoCompleteTextViewMRL);
searchField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchField.getWindowToken(), 0);
SimpleDataBO simpleDataBO = (SimpleDataBO) adapterView.getAdapter().getItem(position);
String drugName = simpleDataBO.getData();
OrderLevelsListBO OrderLevelsListBO = new OrderLevelsListBO();
OrderLevelsListBO.setTradeCompositeId(drugName);
OrderLevelsListBO.setReorderLevelInBaseUnit("0");
OrderLevelsListBOs.add(OrderLevelsListBO);
reorderAdapter.notifyDataSetChanged();
searchField.setText("");
}
});
class GetTradeNamesListAsyncTask extends AsyncTask<String, String, String> {
private ResultVO resGetTCI;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... args) {
try {
HeaderParms HeaderParms = ICommonMethods.setHeaderParams(MaintainReorderLevelActivity.this);
APIServicesImpl services = new APIServicesImpl();
resGetTCI = services.get(SimpleDataArrayListBO.class, IUrlsUtil.URL_KYM_GET_TCI, HeaderParms);
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return null;
}
protected void onPostExecute(String file_url) {
if (resGetTCI != null) {
int appStatusCode = resGetTCI.getAppStatusCode();
if (appStatusCode == Constants.APP_STATUS_CODE_SUCCESS) {
SimpleDataArrayListBO simpleDataArrayListBO = (SimpleDataArrayListBO) resGetTCI.getPayload();
ArrayList<SimpleDataBO> simpleDataBOArrayList = simpleDataArrayListBO.getSimpleDataBOList();
if(simpleDataBOArrayList!=null) {
AutocomleteAdapter autocompleteAdapter = new AutocomleteAdapter(MaintainReorderLevelActivity.this, R.layout.drug_list_row_billing, simpleDataBOArrayList);
searchField.setAdapter(autocompleteAdapter);
searchField.setThreshold(1);
new OrderListAsy().execute();
}
} else {
String resMessage = resGetTCI.getMessages().get(0);
Toast.makeText(MaintainReorderLevelActivity.this, resMessage, Toast.LENGTH_SHORT).show();
}
} else {
ExceptionMessages.showAlertDialog(MaintainReorderLevelActivity.this, IExceptionUtil.NULL_RESPONSE_TITLE, IExceptionUtil.NULL_RESPONSE_MESSAGE, true);
}
}
}
class OrderListAsy extends AsyncTask<String, String, String> {
ResultVO resGetRL;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MaintainReorderLevelActivity.this);
pDialog.setMessage(Utility.USER_ID_EXISTS_MESSAGE);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
try {
HeaderParms HeaderParms = ICommonMethods.setHeaderParams(MaintainReorderLevelActivity.this);
APIServicesImpl services = new APIServicesImpl();
resGetRL = services.get(ReorderLevelsArrayListBO.class, IUrlsUtil.URL_RL_GET_STOCKS, HeaderParms);
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return null;
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (resGetRL != null) {
int appStatusCode = resGetRL.getAppStatusCode();
if (appStatusCode == Constants.APP_STATUS_CODE_SUCCESS) {
ReorderLevelsArrayListBO reorderLevelsArrayListBO = (ReorderLevelsArrayListBO) resGetRL.getPayload();
OrderLevelsListBOs = reorderLevelsArrayListBO.getReorderLevelsList();
reorderAdapter = new OrderAdapter(MaintainReorderLevelActivity.this, OrderLevelsListBOs);
reorderLevelListView.setAdapter(reorderAdapter);
} else {
String resMessage = resGetRL.getMessages().get(0);
Toast.makeText(MaintainReorderLevelActivity.this, resMessage, Toast.LENGTH_SHORT).show();
}
} else {
ExceptionMessages.showAlertDialog(MaintainReorderLevelActivity.this, IExceptionUtil.NULL_RESPONSE_TITLE, IExceptionUtil.NULL_RESPONSE_MESSAGE, true);
}
}
}
}
MyAdapter class:
public class OrderAdapter extends BaseAdapter {
private Activity context;
ArrayList<OrderLevelsListBO> data;
OrderLevelsListBO OrderLevelsListBO;
public OrderAdapter(Activity context, ArrayList<OrderLevelsListBO> data) {
super();
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
EditText etReorderLevel;
TextView txtRLTradeName;
TextView txtDeleteMRL;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
OrderLevelsListBO = data.get(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.reorder_level_row, null);
holder = new ViewHolder();
holder.etReorderLevel = (EditText) convertView.findViewById(R.id.edtReorderLevel);
holder.txtRLTradeName = (TextView) convertView.findViewById(R.id.txtRLTradeName);
holder.txtDeleteMRL = (TextView) convertView.findViewById(R.id.txtDeleteMRL);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position % 2 == 1) {
convertView.setBackgroundColor(context.getResources().getColor(R.color.UPDATE_STOCK_LINE));
} else {
convertView.setBackgroundColor(context.getResources().getColor(R.color.WHITE));
}
if (OrderLevelsListBO.getTradeCompositeId() != null) {
holder.txtRLTradeName.setText(OrderLevelsListBO.getTradeCompositeId());
}
if (OrderLevelsListBO.getReorderLevelInBaseUnit() != null) {
holder.etReorderLevel.setText(OrderLevelsListBO.getReorderLevelInBaseUnit());
}
holder.etReorderLevel.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) {
if (!holder.etReorderLevel.getText().toString().equals("")) {
String reorderQuantity = holder.etReorderLevel.getText().toString();
data.get(position).setReorderLevelInBaseUnit(reorderQuantity);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.txtDeleteMRL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.remove(position);
notifyDataSetChanged();
}
});
// OrderLevelsListBOs = data;
return convertView;
}
}
Why Don't you use recyclerview instead of a listview ?
Anyway if you go with the intention of using a listview, you've to do is create a method in your custom adapter.
Something like this:
public void addData(OrderLevelsListBO orderLevelsListBO) {
data.add(orderLevelsListBO);
}
And you call this method when you add a item.
reorderAdapter.addData(orderLevelsListBO);

Update Listview after post new data from dialogfragment

I am trying to update my listview directly after I submit new data from DialogFragment.
But when I call notifyDataSetChanged() it give me an NullPointerException and my app is close.
So this is the scenario what I want
And this is my code
This activity that I use to get data from the server
public class LayoutActivity extends Fragment {
private ListView listview;
private ListItemAdapter theAdapter;
String URL = "http://localhost/api/question/get_newest_except/0/0/15";
ProgressDialog pDialog;
NodeList nodelist;
public LayoutActivity() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.layout_main, container,false);
DownloadXML a = new DownloadXML(this);
a.execute(URL);
listview = (ListView) rootview.findViewById(R.id.list01);
return rootview;
}
public class DownloadXML extends AsyncTask<String, Void, Void>{
private LayoutActivity aku;
ArrayList<ListItemObject> data;
public DownloadXML(LayoutActivity aku) {
super();
this.aku = aku;
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
data = new ArrayList<ListItemObject>();
ListItemObject itemData;
try{
for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
itemData = new ListItemObject();
itemData.setId(getNode("pb__question__id",eElement));
itemData.setOwner(getNode("pb__question__consumer__id",eElement));
if(!getNode("pb__question__consumer__id",eElement).equalsIgnoreCase("0")){
itemData.setName(getNode("pb__question__consumer__name",eElement));
itemData.setJob(getNode("pb__question__consumer__occupation", eElement));
itemData.setProfilePic(getNode("pb__question__consumer__pp",eElement));
}
itemData.setStatus(getNode("pb__question__title",eElement));
itemData.setExtras(getNode("pb__question__topic__name", eElement));
if(!getNode("att__pict",eElement).isEmpty()){
itemData.setImage(getNode("att__pict", eElement));
}
if(getNode("pb__question__type", eElement).equalsIgnoreCase("1")){
itemData.setOpini(getNode("pb__question__total__opini", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("2") || getNode("pb__question__type", eElement).equalsIgnoreCase("3")){
itemData.setOpini(getNode("pb__question__total__polling", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("4")){
itemData.setOpini(getNode("pb__question__total__rating", eElement));
}
itemData.setTipe(getNode("pb__question__type", eElement));
itemData.setIkuti(getNode("pb__question__total__follow", eElement));
itemData.setSebarkan(getNode("pb__question__total__share", eElement));
data.add(itemData);
}
}
theAdapter = new ListItemAdapter(aku.getActivity(),data);
listview.setAdapter(theAdapter);
}catch(Exception e){
Toast.makeText(getActivity(), "Koneksi dengan server gagal", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
#Override
protected Void doInBackground(String... Url) {
// TODO Auto-generated method stub
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodelist = doc.getElementsByTagName("pb__question");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
private static String getNode(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
String result = "";
if(nValue!=null){
result = nValue.getNodeValue();
}
return result;
}
}
and this is the listview adapter, in this adapter I call Dialog from each item
public class ListItemAdapter extends BaseAdapter{
private ArrayList<ListItemObject> itemCards;
private Context mContext;
private FragmentManager mFragmentManager;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ListItemAdapter(FragmentActivity fa, ArrayList<ListItemObject> d) {
super();
this.mContext = fa;
this.itemCards= d;
mFragmentManager = fa.getSupportFragmentManager();
}
#Override
public int getCount() {
return itemCards.size();
}
#Override
public Object getItem(int pos) {
return itemCards.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(final int position, View convertview, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
row = convertview;
row = View.inflate(mContext, R.layout.item_layout, null);
final boolean[] mHighlightedPositions = new boolean[itemCards.size()];
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
LinearLayout containerPP = (LinearLayout) row.findViewById(R.id.idCon);
NetworkImageViewCircle fotoPP = (NetworkImageViewCircle) row.findViewById(R.id.pp);
TextView nama = (TextView) row.findViewById(R.id.name);
TextView kerjaan = (TextView) row.findViewById(R.id.jobs);
NetworkImageView gambar = (NetworkImageView) row.findViewById(R.id.feedImage1);
TextView status = (TextView) row.findViewById(R.id.txtStatusMsg);
TextView extra = (TextView) row.findViewById(R.id.txtUrl);
TextView opinion = (TextView) row.findViewById(R.id.opini);
TextView follow = (TextView) row.findViewById(R.id.ikuti);
TextView share = (TextView) row.findViewById(R.id.sebarkan);
Button Opini = (Button) row.findViewById(R.id.Button01);
Button Ikuti = (Button) row.findViewById(R.id.Button02);
Button Sebarkan = (Button) row.findViewById(R.id.Button03);
Ikuti.setTag(position);
Opini.setTag(position);
ListItemObject item = itemCards.get(position);
if(item.getName()==null){
containerPP.setVisibility(View.GONE);
}
if(item.getExtras().equalsIgnoreCase("Pertanyaan Pengguna")){
extra.setVisibility(View.GONE);
}
if(item.getImage()==null){
gambar.setVisibility(View.GONE);
}
if(item.getTipe().equals("4")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.star_icon, 0);
}else if(item.getTipe().equals("2") || item.getTipe().equals("3")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.poll_icon, 0);
}
nama.setText(item.getName());
kerjaan.setText(item.getJob());
fotoPP.setImageUrl(item.getProfilePic(), imageLoader);
status.setText(item.getStatus());
extra.setText(item.getExtras().replaceAll("\n",""));
opinion.setText(item.getOpini());
follow.setText(item.getIkuti());
share.setText(item.getSebarkan());
gambar.setImageUrl(item.getImage(), imageLoader);
if(mHighlightedPositions[position]) {
Ikuti.setBackgroundResource(R.color.ijo);
Ikuti.setTextColor(Color.WHITE);
}else{
Ikuti.setBackgroundResource(R.color.abu2);
Ikuti.setTextColor(Color.BLACK);
}
Opini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddKomentar(v,position);
}
});
Ikuti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Sebarkan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return row;
}
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.show(fm, "Dialog");
}
}
and this is the DialogFragment
public class DialogAddOpini extends DialogFragment{
ListItemAdapter theAdapter;
String question_id,owner_id;
EditText question_field;
ProgressDialog pDialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.addopini, null);
Bundle mArgs = getArguments();
question_id = mArgs.getString("question");
owner_id = mArgs.getString("owner");
builder.setTitle("Tambahkan Opini");
builder.setView(dialogView)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
question_field = (EditText) dialogView.findViewById(R.id.content);
SendComment send = new SendComment();
send.execute(question_field.getText().toString());
}
});
Dialog dialog = builder.create();
return dialog;
}
private class SendComment extends AsyncTask<String, Void, Void>{
public SendComment() {
super();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Submitting...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
String content = params[0];
postData(content);
return null;
}
#Override
protected void onPostExecute(Void result) {
theAdapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
public void postData(String content) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/api/opini/add");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pb_question_id", question_id));
nameValuePairs.add(new BasicNameValuePair("owner_id", owner_id));
nameValuePairs.add(new BasicNameValuePair("opini_text", content));
nameValuePairs.add(new BasicNameValuePair("is_anonym", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I call notifyDataSetChanged() inside onPostExecute inside DialogFragment, but it give me NullPointerException.
Can anyone help me?
This the log
Thanks
theAdapter is not initialized in class DialogAddOpini, You need to initialized it before using it in OnPostExecute.
I will prefer to use Listener to return the data from DialogFragment and update List in the Adapter only.
public class DialogAddOpini extends DialogFragment {
private Listener mListener;
public void setListener(Listener listener) {
mListener = listener;
}
static interface Listener {
void returnData();
}
Set the listener while creating Dialog :
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
And return the data like :
#Override
protected void onPostExecute(Void result) {
if (mListener != null) {
mListener.returnData();
}
pDialog.dismiss();
}
And override returnData in Adapter and update the list:
public class ListItemAdapter extends BaseAdapter implements DialogAddOpini.Listener {
#Override
public void returnData() {
notifyDataSetChanged();
}
}
Update :
You have to pass the data and set it in the Adapter's Arraylist to reflect the changes.
Track the position while you show the dialog :
Integer selected_position =-1 ;
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
selected_position = pos;
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
#Override
public void returnData( String counter) {
itemCards.get(selected_position).setOpini(counter);
notifyDataSetChanged();
selected_position=-1;
}
Hope it helps ツ

Categories

Resources