Android HTML Parser Example - android

I was looking into many HTML parser for android. I tried many libraries. Can anyone please show me an example how to do it. I want to extract the content of each tag. Please help. I am stuck with this.

Please look at this list. Actually, it's lots of options outside there. For instance, I chose HtmlCleaner library for implementation. Below is an example of usage:
Project structure:
Actual source code:
public class HtmlHelper {
TagNode rootNode;
public HtmlHelper(URL htmlPage) throws IOException
{
HtmlCleaner cleaner = new HtmlCleaner();
rootNode = cleaner.clean(htmlPage);
}
List<TagNode> getLinksByClass(String CSSClassname)
{
List<TagNode> linkList = new ArrayList<TagNode>();
TagNode linkElements[] = rootNode.getElementsByName("a", true);
for (int i = 0; linkElements != null && i < linkElements.length; i++)
{
String classType = linkElements[i].getAttributeByName("class");
if (classType != null && classType.equals(CSSClassname))
{
linkList.add(linkElements[i]);
}
}
return linkList;
}
}
public class StackParser extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.parse);
button.setOnClickListener(myListener);
}
private ProgressDialog pd;
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
pd = ProgressDialog.show(StackParser.this, "Working...", "request to server", true, false);
new ParseSite().execute("http://www.stackoverflow.com");
}
};
private class ParseSite extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... arg) {
List<String> output = new ArrayList<String>();
try
{
HtmlHelper hh = new HtmlHelper(new URL(arg[0]));
List<TagNode> links = hh.getLinksByClass("question-hyperlink");
for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
output.add(divElement.getText().toString());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return output;
}
protected void onPostExecute(List<String> output) {
pd.dismiss();
ListView listview = (ListView) findViewById(R.id.listViewData);
listview.setAdapter(new ArrayAdapter<String>(StackParser.this, android.R.layout.simple_list_item_1 , output));
}
}
}

Related

After pressing back button, previous activity (listview) is emtpty

In my android project i have a listview with items loaded from an online database. When i click on an item i go to another class where i can delete or update it. My problem is that when i press the back button, my listview is empty. I tried onBackPressed with intent to go to previous activity but it is empty again. I want to reload my listview when from a clicked item i press the back button. Below is my code.
The listview:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
//finish();
}
});
search = (EditText)findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
#Override
public void afterTextChanged(Editable s) {
}
});
// check student's name whether contain text entered in search box
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}}
And the code from item click:
public class SingleStudent extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://sissy-nickels.000webhostapp.com/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://sissy-nickels.000webhostapp.com/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView NAME,SURNAME,DEPT,REGNUM,GRADE;
String NameHolder, SurnameHolder, DeptHolder, RegnumHolder, GradeHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlestudent);
NAME = (TextView)findViewById(R.id.name);
SURNAME = (TextView)findViewById(R.id.surname);
DEPT = (TextView)findViewById(R.id.dept);
REGNUM = (TextView)findViewById(R.id.regnum);
GRADE = (TextView)findViewById(R.id.grade);
UpdateButton = (Button)findViewById(R.id.BDel);
DeleteButton = (Button)findViewById(R.id.BUp);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ListViewValue");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SingleStudent.this,StudentUpdate.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("name", NameHolder);
intent.putExtra("surname", SurnameHolder);
intent.putExtra("dept", DeptHolder);
intent.putExtra("regnum", RegnumHolder);
intent.putExtra("grade", GradeHolder);
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(SingleStudent.this, "Φόρτωση", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(SingleStudent.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(SingleStudent.this,"Φόρτωση",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(SingleStudent.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
NameHolder = jsonObject.getString("Name").toString() ;
SurnameHolder = jsonObject.getString("Surname").toString() ;
DeptHolder = jsonObject.getString("Dept").toString() ;
RegnumHolder = jsonObject.getString("Regnum").toString() ;
GradeHolder = jsonObject.getString("Grade").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
SURNAME.setText(SurnameHolder);
DEPT.setText(DeptHolder);
REGNUM.setText(RegnumHolder);
GRADE.setText(GradeHolder);
}
}}
Than you in advance!
try this on AllStudents activity
#Override
protected void onResume() {
super.onResume();
if (studentList != null && studentList.size()>0) {
ListAdapter adapter = new ListAdapter(studentList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
*Note
when you make a search you run the filterStudents() method
and replace the current list in the adapter
ListAdapter adapter = new ListAdapter(filteredList, this);
but make sure that if you search for nothing .. return the original list
ListAdapter adapter = new ListAdapter(studentList, this);
or you will get an empty list view
You should not recreate from secondActivity. You just finish it when your work is done in secondActivity. Which means, simply you have to do the below in your secondActivity.
#Override
public void onBackPressed() {
super.onBackPressed();
}

Calling fragment method from Asynctask PostExecute

I need help on how to call a method that is in a fragment from a class AsyncTask. I've been looking to similar questions, I've tried some things and it has not worked for me.
The problem:
The AsyncTask class downloads an XML and saves some tags that interest me. Next in the method onPostExecute I have to call another method that is in the Fragment class to fill in the textviews with the downloaded values of the XML.
Code:
public class XMLParse extends AsyncTask<String, Void, Void> {
public static String v_temperatura = "", v_humitat = "", v_pressio = "", v_pluja = "", v_hora = "", v_vent = "";
protected void onPostExecute(Void args) {
for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
v_temperatura = getNode("temp", eElement);
v_humitat =getNode("hum", eElement);
v_pressio = getNode("baro", eElement);
v_vent = getNode("windinmph", eElement);
v_pluja = getNode("todayraininmm", eElement);
v_hora = getNode("time", eElement);
if (onAnar.equals("widget")) {
WidgetActivity widgetActivity = new WidgetActivity();
widgetActivity.omplirTextViews(MyApplication.getAppContext());
} else if (onAnar.equals("frgDades")) {
/*
* Here I need to call the fragment method to
* fill the values in the textviews
*
* Example:
* DadesActualsFragment dadesActualsFragment = new DadesActualsFragment();
* dadesActualsFragment.omplirTextViews();
*/
}
}
}
}
}
Edit:
This is the code that execute the AsyncTask:
#Override
public void onRefresh() {
Toast.makeText(MyApplication.getAppContext(), "test", Toast.LENGTH_SHORT).show();
try {
XMLParse xmlParse = new XMLParse();
xmlParse.execute("frgDades");
} catch (Exception e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
Fragment TextViews code:
The omplirTextViews() method take the value of the variables that are defined to the XMLParse class.
public class DadesActualsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private SwipeRefreshLayout mSwipeRefreshLayout;
TextView tv_app_temperatura_val, tv_app_humitat_val, tv_app_pressio_val, tv_app_vent_val, tv_app_pluja_val, tv_app_hora_val;
public DadesActualsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.fragment_dades_actuals, container, false);
tv_app_temperatura_val = myInflatedView.findViewById(R.id.tv_app_temperatura_val);
tv_app_humitat_val = myInflatedView.findViewById(R.id.tv_app_humitat_val);
tv_app_pressio_val = myInflatedView.findViewById(R.id.tv_app_pressio_val);
tv_app_vent_val = myInflatedView.findViewById(R.id.tv_app_vent_val);
// Inflate the layout for this fragment
return myInflatedView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
// Implementació del Swipe Refresh
mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.fragment_dadesActuals_swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(this);
}
#Override
public void onRefresh() {
Toast.makeText(MyApplication.getAppContext(), "test", Toast.LENGTH_SHORT).show();
// Executar l'XML parse cada cop que es refresca el widget
try {
//XMLParse xmlParse = new XMLParse(dadesActualsFragment);
//xmlParse.execute("frgDades");
DadesActualsFragment dadesActualsFragment = new DadesActualsFragment();
new XMLParse(dadesActualsFragment).execute("frgDades");
} catch (Exception e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
public void omplirTextViews() {
System.out.println("------------------");
tv_app_temperatura_val.setText(XMLParse.v_temperatura);
tv_app_humitat_val.setText(XMLParse.v_humitat);
tv_app_pressio_val.setText(XMLParse.v_pressio);
tv_app_vent_val.setText(XMLParse.v_vent);
}
}
How can I do it?
Regards.
You could do something like this, you can pass the fragment instance while calling the Asynctask constructor. Please see the code below.
class WorkerTask extends AsyncTask<Void, Void, Void> {
private DadesActualsFragment dadesActualsFragment;
WorkerTask(DadesActualsFragment dadesActualsFragment) {
this.dadesActualsFragment = dadesActualsFragment;
}
#Override
protected Void doInBackground(Void... params)
{
...
}
#Override
protected void onPostExecute(Void res)
{
for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
v_temperatura = getNode("temp", eElement);
v_humitat =getNode("hum", eElement);
v_pressio = getNode("baro", eElement);
v_vent = getNode("windinmph", eElement);
v_pluja = getNode("todayraininmm", eElement);
v_hora = getNode("time", eElement);
if (onAnar.equals("widget")) {
WidgetActivity widgetActivity = new WidgetActivity();
widgetActivity.omplirTextViews(MyApplication.getAppContext());
} else if (onAnar.equals("frgDades")) {
dadesActualsFragment.omplirTextViews();
}
}
}
}
}
And you have to initialize and trigger AsyncTak like this
new WorkerTask(dadesActualsFragment).execute();
You need to access the current instance of the fragment:
class YourTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
...
}
#Override
protected void onPostExecute(Void args)
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.container);
if (fragment != null && fragment instanceof DadesActualsFragment) {
((DadesActualsFragment) fragment).omplirTextViews();
}
}
}

how to show only selected data when spinner value is selected in android?

I have got 3 spinner where data is coming from server, if we click the search button without selecting any spinner then on next activity , it should show all list(all product without condition), but if we select according to 3 spinner then it should show only related item.I am getting all item when clicking search button without selecting anything but i am not getting selected item in next activity .
here is my Search Activity:
public class PMSearchActivity extends AppCompatActivity {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private ImageButton mtoolbar,pmplus;
private Button mpigeonSearchbtn;
private Spinner pmcountry;
private Spinner pmstrain;
private Spinner pmdistance;
private TextView error_text;
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmsearch);
getSupportActionBar().hide();
pmplus = (ImageButton) findViewById(R.id.plus);
pmplus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMSearchActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
finish();
}
}) ;
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMSearchActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
mpigeonSearchbtn = (Button) findViewById(R.id.pmaddcompanybtn);
mpigeonSearchbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
pmcountry = (Spinner) findViewById(R.id.sname);
pmstrain = (Spinner) findViewById(R.id.fbcountry);
pmdistance = (Spinner) findViewById(R.id.pstrain);
error_text = (TextView) findViewById(R.id.error_text);
adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems);
pmstrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems2);
pmdistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems3);
pmcountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void attemptLogin() {
// Reset errors.
// mEmailView.setError(null);
//mPasswordView.setError(null);
// Store values at the time of the login attempt.
String PMcountry = pmcountry.getSelectedItem().toString();
String PMstrains = pmstrain.getSelectedItem().toString();
String PMdistance = pmdistance.getSelectedItem().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
}
Intent intent = new Intent(PMSearchActivity.this, PMPigeonListingActivity.class);
intent.putExtra("Country_name", PMcountry);
intent.putExtra("Strain_name", PMstrains);
intent.putExtra("Distance_name", PMdistance);
startActivity(intent);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListStrainTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Strain-");
// Json coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListDistanceTask() {
}
// Json coding
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Country-");
// Json coding
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
here in PiegonListing activity:
public class PMPigeonListingActivity extends AppCompatActivity {
private Button mpigeonListBtn;
private ImageView mimg3;
private ImageButton mtoolbar;
private String PostCountry;
private String PostStrain;
private String PostDistance;
private Button listpigeonbutton;
private Spinner lsDistance;
private Spinner lsStrain;
private Spinner lsCountry;
private Button lssearchbutton;
private TextView listallbtn;
//Web api url
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
//Tag values to read from json
public static final String TAG_IMAGE_URL = "pimage";
public static final String TAG_NAME = "pprice";
public static final String TAG_PID = "pid";
public static final String TAG_PNAME = "pname";
public static final String TAG_PDETAILS = "pdetails";
public static final String TAG_MOBILE = "pmobile";
public static final String TAG_EMAIL = "pemail";
//GridView Object
private GridView gridView;
private GridView gridView2;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private ArrayList<String> names;
private ArrayList<Integer> pid;
private ArrayList<String> pname;
private ArrayList<String> pdetails;
private ArrayList<String> pimage;
private ArrayList<String> pmobile;
private ArrayList<String> pemail;
//for inline search
private ArrayList<String> images2;
private ArrayList<String> names2;
private ArrayList<Integer> pid2;
private ArrayList<String> pname2;
private ArrayList<String> pdetails2;
private ArrayList<String> pimage2;
private ArrayList<String> pmobile2;
private ArrayList<String> pemail2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmpigeon_listing);
getSupportActionBar().hide();
gridView = (GridView) findViewById(R.id.gridView);
gridView2 = (GridView) findViewById(R.id.gridView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
PostCountry = extras.getString("Country_name");
PostStrain = extras.getString("Strain_name");
PostDistance = extras.getString("Distance_name");
}
images = new ArrayList<>();
names = new ArrayList<>();
pid = new ArrayList<>();
pname = new ArrayList<>();
pdetails = new ArrayList<>();
pmobile = new ArrayList<>();
pemail = new ArrayList<>();
images2 = new ArrayList<>();
names2 = new ArrayList<>();
pid2 = new ArrayList<>();
pname2 = new ArrayList<>();
pdetails2 = new ArrayList<>();
pmobile2 = new ArrayList<>();
pemail2 = new ArrayList<>();
lsStrain = (Spinner) findViewById(R.id.lsStrain);
lsDistance = (Spinner) findViewById(R.id.lsDistance);
lsCountry = (Spinner) findViewById(R.id.lsCountry);
lssearchbutton = (Button) findViewById(R.id.lssearchbutton);
listallbtn = (TextView) findViewById(R.id.listallbtn);
if (PostCountry.equals("Select Country") && PostStrain.equals("Select Strain") && PostDistance.equals("Select Distance")) {
listallbtn.setVisibility(View.GONE);
} else {
listallbtn.setVisibility(View.VISIBLE);
}
//Calling the getData method
getData();
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
lssearchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
listallbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
lsCountry.setSelection(0);
lsStrain.setSelection(0);
lsDistance.setSelection(0);
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
// button list
listpigeonbutton = (Button) findViewById(R.id.listpigeonbutton);
listpigeonbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
}
});
adapter = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems);
lsStrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems2);
lsDistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems3);
lsCountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......searchPigeonList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("image"));
names.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
Log.d("Test",response);
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
gridView.setAdapter(pmpigeonlistadapter);
pmpigeonlistadapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void filter() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......hPigeonList";
final String lstrain = lsStrain.getSelectedItem().toString();
final String ldistance = lsDistance.getSelectedItem().toString();
final String lcountry = lsCountry.getSelectedItem().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid2.add(obj.getInt("id"));
pname2.add(obj.getString("pigeon_name"));
pdetails2.add(obj.getString("pigeon_details"));
pmobile2.add(obj.getString("usr_mobile"));
pemail2.add(obj.getString("usr_email"));
images2.add(obj.getString("image"));
names2.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonSearchInlineAdapter pmPigeonSearchInlineAdapter = new PMPigeonSearchInlineAdapter(getApplicationContext(), images2, names2, pid2, pdetails2, pmobile2, pemail2, pname2);
//Adding adapter to gridview
pmPigeonSearchInlineAdapter.notifyDataSetChanged();
gridView2.setAdapter(pmPigeonSearchInlineAdapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params2 = new HashMap<String, String>();
params2.put("country", lcountry);
params2.put("strain", lstrain);
params2.put("distance", ldistance);
return params2;
}
};
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
gridView2.setAdapter(null);
requestQueue2.add(stringRequest);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
// some coding
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
// some coding
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsDistance.getAdapter();
lsDistance.setSelection(array_spinner.getPosition(PostDistance));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("Select Country");
// some coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMPigeonListingActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsCountry.getAdapter();
lsCountry.setSelection(array_spinner.getPosition(PostCountry));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
In Pigeon listing activity there is 1 option like search activity where user can search without selecting any item just like in search activity.
Set listeners for each of your spinners
setOnItemSelectedListener
In onItemSelected method , get the selected value in a variable and pass on these values to next activity.
E.g.
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String yourValue = yourSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

How can i print arraylist from class AsyncTask?

I want to print an ArrayList. I have receive value arraylist from class AsyncTask, in MainActivity, I have value ArrayList, but when I print ArrayList, my app is not working. Please help me!
MainActivity
{
executeLoadProduct();
arraylistgroup = new ArrayList<String>();
arraylistgroup=TaskLoadProductGroup.getvaluearraylist();
String[] mStringArray = new String[arraylistgroup.size()];
mStringArray = arraylistgroup.toArray(mStringArray);
for (int i = 0; i < mStringArray.length; i++) {
System.out.println("string is2" + (String) mStringArray[i]);
}
executeLoadProduct
private void executeLoadProduct() {
// execute task load product
loadProductGroup = new TaskLoadProductGroup(MainActivity.this);
loadProductGroup.execute();
}
AsyncTask
public class TaskLoadProductGroup extends AsyncTask<String, Void, ArrayList<String>> {
private ActionBarActivity actionBarActivity;
private Context context;
private static ArrayList<String> arrayListgroup;
public TaskLoadProductGroup(ActionBarActivity actionBarActivity) {
this.actionBarActivity = actionBarActivity;
this.context = actionBarActivity.getApplicationContext();
}
#Override
protected void onPreExecute() {
///show progress loading
super.onPreExecute();
}
#Override
protected ArrayList<String> doInBackground(String... url) {
ArrayList<String> listProductgroup = null;
try {
Server server = new Server();
ResListProduct resListProduct = server.getListProducts(context);
//init list item for listview home product
listProductgroup = initItemProduct(resListProduct);
} catch (Exception e) {
}
return listProductgroup;
}
public static ArrayList<String> initItemProduct(ResListProduct rsProduct) {
List<GroupProduct> groups = rsProduct.getGroups();
arrayListgroup = new ArrayList<String>();
for (GroupProduct group : groups) {
// add header group
String s = group.getName();
arrayListgroup.add(s);
}
getvaluearraylist();
// getVarialty();
return arrayListgroup;
}
public static ArrayList<String> getvaluearraylist()
{
return arrayListgroup;
}
#Override
protected void onPostExecute(ArrayList<String> listProductgroup) {
super.onPostExecute(listProductgroup);
}
}
I couldn't identify why are you doing so complex code to print the ArrayList. You can just print that inside onPostExecute method like this,
#Override
protected void onPostExecute(ArrayList<String> listProductgroup) {
super.onPostExecute(listProductgroup);
for (String value : listProductgroup){
Log.d("myTag", value);
}
}
OR
Use loadProductGroup.execute().get() method, but remember this will freeze your UI.

How to use listview from different xml layout file

I am working on android ListView and i am getting one issue.I created one list view into the XML file installation.xml and i want to use that list view into my Searchdata.java. so basically what i want that when i click on searchdata button than data is fetched from web service and after parsing, it will saved into the listview.and when i click on Installation View button than new window will be appear where i could see that list data.
SearchData.java
public class SearchData extends Activity {
EditText Keyword;
JSONParser jsonparser = new JSONParser();
ListView Datalist;
HorizontalScrollView VideoDatalist;
ArrayList<HashMap<String, String>> DataList;
ArrayList<HashMap<String, String>> VideoDataList;
JSONArray contacts = null;
private ProgressDialog pDialog;
ImageButton searchdata,InstallationView;
String Keyvalue = new String();
private static final String TAG_InnerText = "InnerText";
private static final String TAG_Title = "Title";
private static final String TAG_URL = "URL";
private static final String TAG_VIDEO_URL = "URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_data);
InstallationView=(ImageButton)findViewById(R.id.InstallationView);
Keyword = (EditText) findViewById(R.id.KeyData);
Datalist=(ListView)findViewById(R.layout.activity_installation);
VideoDatalist=(HorizontalScrollView)findViewById(R.id.Horizontallist);
searchdata=(ImageButton)findViewById(R.id.searchicon);
String Keyvalue = new String();
DataList = new ArrayList<HashMap<String, String>>();
VideoDataList = new ArrayList<HashMap<String, String>>();
searchdata.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ReadData().execute();
}
});
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
startActivity(new Intent(SearchData.this, Installation.class));
}
});
}
public class ReadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchData.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
try{
Keyvalue=Keyword.getText().toString();
String Jsonstr = jsonparser.makeHttpRequest("http://10.47.93.26:8080/Search/api/Search/"+Keyvalue);
try {
if (Jsonstr != null) {
JSONArray jsonObj = new JSONArray (Jsonstr);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String name = c.optString(TAG_Title);
String url = c.optString(TAG_URL);
HashMap<String, String> info = new HashMap<String, String>();
if( !name.isEmpty() )
{
info.put(TAG_Title, name);
}
else
{
info.put(TAG_Title,"User Manual");
}
if(url.contains("youtube"))
{
info.put(TAG_URL, url);
VideoDataList.add(info);
}
else
{
info.put(TAG_URL, url);
DataList.add(info);
}
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
SimpleAdapter adapter = new SimpleAdapter(
SearchData.this, DataList,
R.layout.list_item, new String[]
{
TAG_Title
}, new int[] {
R.id.InnerText });
Datalist.setAdapter(adapter);
}
}
}
web service running and parsing code is running correctly. i am getting error at post method,so can you help me on this.
Error
Call your Installation activity in onClick() method:
And pass your ArrayList data through intent,
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
Intent intent= new Intent(SearchData.this, Installation.class);
intent.putParcelableArrayListExtra("HASH_MAP",DataList);
startActivity(intent);
}
});
In your Installation activity class,set the view in onCreate() and initialize listview from xml file:
setContentView(R.layout.activity_installation);
ListView listView = (ListView)findViwById(R.id.listview);
And try to get the data from intent:
ArrayList<HashMap<String,String>> hashmap_dataList = getIntent.getParcelableArrayListExtra("HASH_MAP");
then do whatever you want with listview and hashmap.
In the onCreate(...) method of your SearchData Activity, the following can never work and will always return 'null' (hence your NullPointerException)...
Datalist=(ListView)findViewById(R.layout.activity_installation);
Calling findViewById(...) will only work for any UI elements which have been inflated when you called setContentView(...). In this case you used R.layout.activity_search_data for your layout file which doesn't contain a ListView with an id of R.layout.activity_installation which is, by the way, a resource id of a layout file and not a resource id of a UI element.
The only way you can do what you need is to put your data as an extra into the Intent you use when you call...
startActivity(new Intent(SearchData.this, Installation.class));
...when the Installation Activity is created it will then need to get the data and create its own adapter.
EDIT: HashMap is Serializable and can be passed as an Intent extra. Pass your DataList HashMap as follows...
Intent i = new Intent(SearchData.this, Installation.class);
i.putExtra("data_list", DataList);
startActivity(i);
In the Installation Activity you can then use...
getIntent().getSerializableExtra("data_list");

Categories

Resources