I have a list view that retrieves data from parse.com. I have added onscroll listener to load the list items after every 15 items. It's working fine but when the whole list is loaded and when we want to scroll back to the top the scrolling is not smooth its like moving up and down. To better understand my problem watch this video
My code
public class InterActivity extends Activity
{
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
FinalAdapter adapter;
List<CodeList> codelist = null;
SharedPreference shrdPreference;
private int limit = 15;
View footerView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.inter_layout);
shrdPreference = new SharedPreference();
//Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(InterActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Please wait loading ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist = new ArrayList<CodeList>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
query.setLimit(limit);
ob = query.find();
for (ParseObject inter : ob) {
map.setIntroduction((String) inter.get("intro"));
map.setFinalCodeText((String) inter.get("codetext"));
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.inter_layoutListView);
// Pass the results into ListViewAdapter.java
adapter = new FinalAdapter(InterActivity.this,
codelist);
// AlphaInAnimationAdapter animationAdapter = new AlphaInAnimationAdapter(adapter);
// animationAdapter.setAbsListView(listview);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
//listview.setOnItemClickListener(InterActivity.this);
//listview.setOnItemLongClickListener(InterActivity.this);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) { // TODO Auto-generated method stub
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count
- threshold) {
// Execute LoadMoreDataTask AsyncTask
new Loadmore().execute();
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
}
}
private class Loadmore extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(InterActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("load More Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading more...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist = new ArrayList<CodeList>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
query.setLimit(limit += 15);
ob = query.find();
for (ParseObject inter : ob) {
ParseFile listpic = (ParseFile) inter.get("alphabetimg");
ParseFile levelpic = (ParseFile) inter.get("levelimg");
ParseFile apipic = (ParseFile) inter.get("apiimg");
ParseFile descpicone = (ParseFile) inter.get("descimgone");
ParseFile descpictwo = (ParseFile) inter.get("descimgtwo");
ParseFile videopic = (ParseFile) inter.get("videoimg");
ParseFile hashtagpic = (ParseFile) inter.get("hashimg");
ParseFile video = (ParseFile) inter.get("demovideo");
// ParseFile downloadfile = (ParseFile) inter.get("download");
CodeList map = new CodeList();
map.setIntroduction((String) inter.get("intro"));
map.setFinalCodeText((String) inter.get("codetext"));
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
int position = listview.getLastVisiblePosition();
adapter = new FinalAdapter(InterActivity.this,
codelist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
listview.setSelectionFromTop(position, 0);
mProgressDialog.dismiss();
}
}
You should not recreate the list and the adapter each time you load more data. Replace the LoadMore class by this one:
private class Loadmore extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(InterActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("load More Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading more...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist.clear();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
query.setLimit(limit += 15);
ob = query.find();
for (ParseObject inter : ob) {
ParseFile listpic = (ParseFile) inter.get("alphabetimg");
ParseFile levelpic = (ParseFile) inter.get("levelimg");
ParseFile apipic = (ParseFile) inter.get("apiimg");
ParseFile descpicone = (ParseFile) inter.get("descimgone");
ParseFile descpictwo = (ParseFile) inter.get("descimgtwo");
ParseFile videopic = (ParseFile) inter.get("videoimg");
ParseFile hashtagpic = (ParseFile) inter.get("hashimg");
ParseFile video = (ParseFile) inter.get("demovideo");
// ParseFile downloadfile = (ParseFile) inter.get("download");
CodeList map = new CodeList();
map.setIntroduction((String) inter.get("intro"));
map.setFinalCodeText((String) inter.get("codetext"));
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
int position = listview.getLastVisiblePosition();
adapter.notifyDataSetChanged();
listview.setSelectionFromTop(position, 0);
mProgressDialog.dismiss();
}
}
Tell me :)
Try using OnTouchListener instead of OnScrollListener (this will help you detect the scroll direction in a easier fashion and react accordingly):
listView.setOnTouchListener(new View.OnTouchListener() {
float height;
#Override
public boolean onTouch(View v, MotionEvent event) {
float height = event.getY();
int action = event.getAction();
int threshold = 1;
int count = listview.getCount();
if(action == MotionEvent.ACTION_DOWN){
// do nothing
this.height = height;
}else if(action == MotionEvent.ACTION_UP){
if(this.height < height){
Log.v(TAG, "Scrolled up");
// do nothing - user is going up
}else if(this.height > height){
Log.v(TAG, "Scrolled down");
//execute LoadMore Task
if (listview.getLastVisiblePosition() >= count
- threshold) {
// Execute LoadMoreDataTask AsyncTask
new Loadmore().execute();
}
}
}
return false;
}
});
Related
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();
}
I have my class that is based on a tutorial online, i dont fully understand it yet ( working on it ), but its working.
It populates the listview, now i want to get the id and show the data related to that id on a more detailed activity.
I already obtain the id of the item i am clicking:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
But now, i am not getting how i will do this, get the data of the position i clicked.
I have a inner class "GetObras" but i cant use the variables from it on my onCreate, i tried make them global, etc
public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView list;
private static String url = "http://ploran.gear.host/scriptobras6.php";
ArrayList<HashMap<String, String>> obrasList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obrasList = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.list1);
new GetObras().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
}
private class GetObras extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray obras = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray obras = jsonObj.getJSONArray("obras");
// looping through All
for (int i = 0; i < obras.length(); i++) {
JSONObject c = obras.getJSONObject(i);
String id = c.getString("Id");
String nomeObra = c.getString("NomeObra");
String idCliente = c.getString("idCliente");
String DataLevantamento = c.getString("DataPLevantamento");
String DataRealizacao = c.getString("DataRLevantamento");
String Estado = c.getString("Estado");
String DataMateriais = c.getString("DataRMateriais");
String DataInicioObra = c.getString("DataInicioObra");
String DataConclusao = c.getString("DataConclusao");
String DataVestoria = c.getString("DataVestoria");
String Obs = c.getString("Obs");
String Prompor = c.getString("Prompor");
String Levantpor = c.getString("Levantpor");
String executpor = c.getString("executpor");
// tmp hash map for single contact
HashMap<String, String> obra = new HashMap<>();
// adding each child node to HashMap key => value
obra.put("Id", id);
obra.put("nomeObra", nomeObra);
obra.put("idCliente", idCliente);
obra.put("DataLevantamento", DataLevantamento);
obra.put("DataRealizacao", DataRealizacao);
obra.put("Estado", Estado);
obra.put("DataMateriais", DataMateriais);
obra.put("DataIncioObra", DataInicioObra);
obra.put("DataConclusao", DataConclusao);
obra.put("DataVestoria", DataVestoria);
obra.put("Obs", Obs);
obra.put("Prompor", Prompor);
obra.put("Levantpor", Levantpor);
obra.put("executpor", executpor);
// adding contact to contact list
obrasList.add(obra);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, obrasList,
R.layout.list_item, new String[]{"nomeObra", "idCliente",
"Estado"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
list.setAdapter(adapter);
}
}
List<String> cities;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// User pressed the search button
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// User changed the text
return false;
}
}
If what i think is correct, i could just get the JsonArray from the doInBackground method in GetObras and do:
JSONObject c = obras.getJSONObject(position);
Thank you.
You can retrieve it using obrasList reference. As your are passing obrasList to your adapter.
Below is the sample code:
obrasList.get(position).get(yourkey);
Hope this will help you.. :))
I used AndroidBegin guide to populate my ListView with data from Parse.com table (http://www.androidbegin.com/tutorial/android-parse-com-simple-listview-tutorial/) and it shows an empty ListView.
// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(QuestionsList.this);
// Set progressdialog title
mProgressDialog.setTitle("Parse.com Simple ListView Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Locate the class table named "Country" in Parse.com
if (AnswerActivity.friend.isEmpty()) {
if (AnswerActivity.wantedTop == AnswerActivity.all) {
// Locate the class table named "Info" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Info");
// Locate the column named "Views" in Parse.com and order list by ascending
query.orderByDescending("Views");
try {
ob = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
} else {
// Locate the class table named "Info" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Info");
// Search for the wanted topic
query.whereContains("User_Topic", AnswerActivity.wantedTop);
// Locate the column named "Views" in Parse.com and order list by ascending
query.orderByDescending("Views");
try {
ob = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
} else {
if (AnswerActivity.wantedTop == AnswerActivity.all) {
// Locate the class table named "Info" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Info");
// Search for the wanted topic
query.whereContains("User_Name", AnswerActivity.friend);
// Locate the column named "Views" in Parse.com and order list by ascending
query.orderByDescending("Views");
try {
ob = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
} else {
// Locate the class table named "Info" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Info");
// Search for the wanted topic
query.whereContains("User_Topic", AnswerActivity.wantedTop);
query.whereContains("User_Name", AnswerActivity.friend);
// Locate the column named "Views" in Parse.com and order list by ascending
query.orderByDescending("Views");
try {
ob = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into an ArrayAdapter
adapter = new ArrayAdapter<String>(QuestionsList.this,
R.layout.listview_item);
// Retrieve object "name" from Parse.com database
for (ParseObject country : ob) {
adapter.add((String) country.get("name"));
}
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Capture button clicks on ListView items
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send single item click data to SingleItemView Class
Intent i = new Intent(QuestionsList.this,
SingleItemView.class);
// Pass data "name" followed by the position
i.putExtra("name", ob.get(position).getString("name")
.toString());
// Open SingleItemView.java Activity
startActivity(i);
}
});
}
}
Later, I used ParseQueryAdapter tutorial, but still, it doesn't work.
Someone knows how to do it?
make a parse query factory
ParseQueryAdapter.QueryFactory<Post> factory;
factory = new ParseQueryAdapter.QueryFactory<Post>() {
#Override
public ParseQuery<Post> create() {
ParseQuery query = new ParseQuery("YourParseObject");
return query;
}
};
make a parse query adapter
private ParseQueryAdapter<Post> adapter;
adapter = new ParseQueryAdapter<Post>(this, factory) {
#Override
public View getItemView(final Post object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.post_item, null);
}
return v;
}
};
adapter.setPaginationEnabled(true);
adapter.setTextKey("title");
adapter.setImageKey("Image");
adapter.loadObjects();
ListView your_list_view = (ListView) findViewById(R.id.list);
your_list_view.setAdapter(adapter);
done, now objects are in a list
make sure that you have a sperate xml file for each parseobject, here i have it labaled as (R.id.post_item)
You really don't need an AsyncTask for that...
Just create your query, invoke findInBackGround() which will create a Async for you, and on the callback, populate your listview.
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> results, ParseException e) {
if (results != null && results.size() > 0) {
YourAdapter adapter = new YourAdapter(context, results);
list.setAdapter(adapter);
Alternatively, if you want to use a ParseQueryAdapter, it's even simpler:
// create your query before, but do no call findInBackground.
YourParseQueryAdapter adapter = new YourParseQueryAdapter(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
return query;
}
});
list.setAdapter(adapter);
Have a good read at the documentation again in case of any issues
Hope this helps!
I have an AsyncTask that loads all my data on parse.com, then the user has a checkbox to select the categories he wants to display.
Once I get those choices (from a separate class via an interface), I reload the asyncTask, but It still lists everything (like if the array of choices gets erased/reloaded).
here is my code to get the selected categories :
#Override
public void onOkay(ArrayList<Integer> selected) {
StringBuilder stringBuilder = new StringBuilder();
if (selected.size() != 0) {
for (int i = 0; i < selected.size(); i++) {
String categories = selectedArray[selected.get(i)];
stringBuilder = stringBuilder.append(", " + categories);
}
//this is to display the content of the selectedArray :
Toast.makeText(this, "You have selected: "
+ stringBuilder.toString(), Toast.LENGTH_SHORT).show();
//reloading the AsyncTask class :
new RemoteDataTask().execute();
}
}
My AsyncTask :
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//timer and progressdialog...
}
#Override
protected Void doInBackground(Void... params) {
list_of_articles = new ArrayList<Articles>();
try {
// Locate the class table named "Article" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Article");
query.whereWithinKilometers("Localisation_Vendeur", device_location, rayon);
//this is the query I use :
query.whereContainedIn ("Category",Arrays.asList(selectedArray));
ob = query.find();
for (ParseObject article : ob) {
// Locate images in article_image column
ParseFile image = (ParseFile) article.get("label1");
Articles map = new Articles();
map.setArticle_label1((String) article.get("label2"));
map.setArticle_label2((String) article.get("label3"));
map.setArticle_category((String) article.get("Category"));
map.setArticle_label4((String) article.get("label4"));
map.setArticle_image(image.getUrl());
list_of_articles.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this,
list_of_articles);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
How can I make that work ? Keep in mind that the query works, i've tested with an array that i filled manually and it works.
Thanks.
You should pass categories that user wants to display as arguments to AsyncTask through AsyncTask.execute(Params... params). They will be available in AsyncTask.doInBackground method as that method parameters. Use them inside doInBackgorund method to set your query appropriately.
private class RemoteDataTask extends AsyncTask<List<String>, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//timer and progressdialog...
}
#Override
protected Void doInBackground(List<String>... params) {
list_of_articles = new ArrayList<Articles>();
try {
// Locate the class table named "Article" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Article");
query.whereWithinKilometers("Localisation_Vendeur", device_location, rayon);
//this is the query I use :
query.whereContainedIn ("Category", params[0]);
ob = query.find();
for (ParseObject article : ob) {
// Locate images in article_image column
ParseFile image = (ParseFile) article.get("label1");
Articles map = new Articles();
map.setArticle_label1((String) article.get("label2"));
map.setArticle_label2((String) article.get("label3"));
map.setArticle_category((String) article.get("Category"));
map.setArticle_label4((String) article.get("label4"));
map.setArticle_image(image.getUrl());
list_of_articles.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this,
list_of_articles);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
Then in code run AsyncTask by calling new RemoteDataTask().execute(Arrays.asList(selectedArray)). Make sure that selectedArray is updated properly before every call of AsyncTask.
my goal is to dismiss the initial progressdialog if there's no internet connection (let's say after 10 seconds) and then trigger another alertdialog whice prompts the user to check his internet connection and try again.
here is my RemoteDataTask class :
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
Create the progressdialog
*/
mProgressDialog = new ProgressDialog(MainActivity.this);
//title :
mProgressDialog.setTitle("SmartShop. Shopping made easy !");
//message :
mProgressDialog.setMessage("Chargement...");
mProgressDialog.setIndeterminate(false);
//show the progressdialog...Only if gpslocation is available !! :)
if (gps.canGetlocation()){
mProgressDialog.show();
}
//mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
long delayInMillis = 3000;
list_of_articles = new ArrayList<Articles>();
try {
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
},delayInMillis );
// Locate the class table named "Article" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Article");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
//query.orderByAscending("ranknum");
query.whereWithinKilometers("Localisation_Vendeur",device_location,rayon);
ob = query.find();
for (ParseObject article : ob) {
// Locate images in article_image column
ParseFile image = (ParseFile) article.get("Image_Article");
Articles map = new Articles();
map.setArticle_name((String) article.get("Nom_Article"));
map.setArticle_vendor((String) article.get("Nom_Vendeur"));
//map.setArticle_vendor((String) article.get("reduction"));
map.setArticle_image(image.getUrl());
list_of_articles.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this,
list_of_articles);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
my progressdialog does not dismiss with this code. what's wrong with it ? and where should I call the second alertdialog "check internet connection and try again" ?
Thanks !
You should perform UI modifications only from the UI thread. Timer runs its tasks in its own thread, not in the UI thread. You can do something like this:
runOnUiThread(new Runnable() { public void run() {
mProgressDialog.dismiss();
}});
And start a new dialog in the same way.