Populate a List View with Parse Objcets - android

My Main Activity has a button which redirects to ResterauntList Activity. I want to get a couple of Objects from my Parse Cloud, and want to add only the name to the ListView. This the code so far
package com.example.gastronomaapp;
import java.util.List;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseQueryAdapter.OnQueryLoadListener;
public class ResterauntList extends ActionBarActivity {
String mValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resteraunt_list);
Bundle bdl = getIntent().getExtras();
mValue = bdl.getString("Value");
setContentView(R.layout.activity_resteraunt_list);
populateList(mValue);
}
private void populateList(String Value) {
ParseQueryAdapter.QueryFactory<ParseObject> factory = new ParseQueryAdapter.QueryFactory<ParseObject>() {
#SuppressWarnings({ "unchecked", "rawtypes" })
public ParseQuery create() {
ParseQuery query = new ParseQuery("Restraunt");
query.whereEqualTo("Location", Value);
return query;
}
};
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(
this, factory);
adapter.setTextKey("name");
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
public void onLoading() {
// Trigger any "loading" UI
}
#Override
public void onLoaded(List<ParseObject> objects, Exception e) {
// TODO Auto-generated method stub
}
});
// Attach it to your ListView, as in the example above
ListView listView = (ListView) findViewById(R.id.restListView);
listView.setAdapter(adapter);
}
}
Not sure whats wrong, but the ListView never populates. My Parse Data Browser claims it has received requests though. Checked the Logcat, it claims the application may be doing too much work.Not really sure whats wrong.
(EDIT) Made a change as suggested in the comments. But now the list view has 2 entries but empty. I know there are 2 entries namely because they are clickable. Completely confused on what is wrong. Have edited the code too!
This is my emulator, as you can see the line there are list view entries

You are forgetting to call the adapter.notifyDatasetChanged() method. If I am not wrong, Parse queries are executed in background, right ? If so, then you need to call this method when the background thread is done.
Plus, as a suggestion, you can simplify your code as:
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("ClassName");
query.whereEqualTo("KEY","VALUE");
query.findInBackground(new FindCallback<ParseObject>(){
#Override
public void done(List<ParseObject> dataFromServer, ParseException e){
if( e == null ) { /** DO SOMETHING */ }
else { /** DO SOMETHING ELSE */ }
}
});

Related

iterating a global list from any activity

i have a list of object in an activity in which a button in the same activity adds an object to it on every click
i want to be capable to access that list and iterate it from any other activity
i made it public but it gave me an error !
package com.fawzyx.movie_rental_store;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MovieReg_activity extends Activity {
public List<movie> movies = new ArrayList<movie>();
String movName ;
int dvdNo ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mov_reg_layout);
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
EditText etdvd_no = (EditText)findViewById(R.id.etdvds);
Button btMovie_submit = (Button)findViewById(R.id.btmovsubmit);
movName= etmovie_name.getText().toString();
dvdNo = Integer.parseInt(etdvd_no.getText().toString()); // to string then to int :)
btMovie_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movies.add(new movie(movName , dvdNo) );
Toast.makeText(MovieReg_activity.this, "Movie Added", Toast.LENGTH_LONG).show();
}
});
}
}
is there a way to access and iterate the list movies from any other activity ?
You can use a static way to access to this list :
public static List<movie> movies = new ArrayList<movie>();
Then from the other activity :
int size = MovieReg_activity.movies.size(); // exp: check the size
for(movie m : MovieReg_activity.movies){
// do something with m
}
if you want to make a global list, create a static variable or put it in your application class and access it via context.
Search about creating a custom application class.
Maybe use a singleton class that holds your movie list.
Then you'll be able to access it everywhere.
http://androidresearch.wordpress.com/2012/03/22/defining-global-variables-in-android/

How to pass arraylist to other function in AsyncTask..?

I am trying to pass an array list to other function in Asyctask but it is getting null.
Written following code to read an array list
#Override
protected ArrayList<String> doInBackground(ArrayList<String>... params) {
// TODO Auto-generated method stub
switch (type) {
case MZIP:
fileManager.createZipFolderForMulti(params[0]);
return null;
}
return null;
}
Written following code to pass an array list to AsyncTask
private void zipMiltiple(ArrayList<String> multiSelectData2) {
// TODO Auto-generated method stub
new Back(MZIP).execute(multiSelectData2);
Log.d("JWP", "METHOD :"+ multiSelectData2);
}
Is there any issue in code?
I'm trying to pass the array list to the other function in Asyctask
but I'm getting array list null..
You need to check whether on this line:
private void zipMiltiple(ArrayList<String> multiSelectData2)
multiSelectData2 variable is properly instantiated, i.e.
if (multiSelectData2 != null) {
new Back(MZIP).execute(multiSelectData2);
Log.d("JWP", "METHOD :"+ multiSelectData2);
}
else {
// ArrayList is NULL
}
You need to make sure that your ArrayList is not NULL. You're passing ArrayList correctly but probably you are passing ArrayList that is not instantiated.
If it still won't work, problem is elsewhere and you should add here your logcat.
It's worth to say that there are more possible approaches:
Pass ArrayList via constructor
Make AsyncTask implementation inner class of Activity class -> since
this, you'll have direct access to variables in Activity
The best way to do that is to use inner class:
put your function inside the inner class.
implement doInBackground.
call your function from doInBackground.
package com.stack.question;
import java.util.ArrayList;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;
import android.util.Log;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
public class StackActivity extends Activity {
RatingBar ratingBar;
float nowValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new yourclass().execute("99");
}
class yourclass extends AsyncTask<String, Integer, ArrayList<String>> {
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
yourfunction(result);
zipMiltiple(result);
}
private void zipMiltiple(ArrayList<String> multiSelectData2) {
// TODO Auto-generated method stub
new Back(MZIP).execute(multiSelectData2);
Log.d("JWP", "METHOD :"+ multiSelectData2);
}
private void yourfunction(ArrayList<String> result) {
for (int i = 0; i < result.size(); i++)
Toast.makeText(StackActivity.this, result.get(i),
Toast.LENGTH_LONG).show();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("st1");
arrayList.add("st2");
// Here put your code
return arrayList;
}
}
}
This is a working example, I also include your code in it

setAdapter is not calling getView.

I know this question has been asked several times, but the solutions have been specific to the askers' problems. Consequently, none of those solutions helped me, even though I tried following all of their suggestions.
So here goes.
I have a movies Activity like this. Notice that I have a MoviesAdapter inner class, that's supposed to populate the moviesDisplay ListView.
package com.example.midtermexam;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MoviesActivity extends Activity {
public String url;
public ListView moviesDisplay;
public static ArrayList<Movie> thisMovies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
url=getIntent().getExtras().getString("url");
moviesDisplay = (ListView)findViewById(R.id.listView1);
new AsyncMoviesGet(this).execute(url);
}
public void populateListView()
{
Log.d("listview","adapter created");
Log.d("listview","Listview declared");
Log.d("listview","adapter populated");
moviesDisplay.setAdapter(new MoviesListAdapter());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies, menu);
return true;
}
private class MoviesListAdapter extends ArrayAdapter<Movie> {
public MoviesListAdapter() {
super(MoviesActivity.this, R.layout.movies_activity_listview, thisMovies);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Make sure we have a view to work with (may have been given null)
View movieView = convertView;
if (movieView == null) {
movieView = getLayoutInflater().inflate(R.layout.movies_activity_listview, parent, false);
}
// Find the car to work with.
return movieView;
}
}
}
The populateListView() method is called from an AsyncTask called AsyncMoviesGet, whose postExecute() looks like this.
#Override
protected void onPostExecute(ArrayList<Movie> result) {
if(result != null){
m.thisMovies = result;
m.populateListView();
Log.d("demo", result.toString());
} else{
Log.d("demo", "null result");
}
}
You can see the Log messages inside the populateListView() method. These 3 statements get executed. However, the setAdapter() function doesn't seem to call the "GetView" function.
Add stuff to ArrayAdapter at least, use mAdapter.addAll():
private MoviesListAdapter mAdapter;
. . . . . .
#Override
protected void onCreate(Bundle savedInstanceState) {
. . . . .
mAdapter = new MoviesListAdapter();
moviesDisplay.setAdapter(mAdapter);
}
. . . . .
protected void onPostExecute(ArrayList<Movie> result) {
if(result != null){
m.thisMovies = result;
mAdapter.clear();
mAdapter.addAll(result);
mAdapter.notifyDatasetInvalidated();
Log.d("demo", result.toString());
} else{
Log.d("demo", "null result");
}
}
You have to add a constructor to your Custom Adapter class, one that takes a context, resource id & a data structure containing the items you'd like to display, in this case your thisMovies.
public MoviesListAdapter(Context context, int resourceId,
ArrayList<String> viewItems)
{
super(context, resourceId, viewItems);
}
Then you have to construct your adapter based on the results you've received in your onPostExecute(). Before this is done, create an instance variable in the activity which will be used to store the adapter.
MoviesListAdapter mMovieAdapter = null;
Afterwards, construct it by changing this
moviesDisplay.setAdapter(new MoviesListAdapter());
to something like below
if(thisMovies != null && thisMovies.size() > 0) {
mMovieAdapter = new MoviesListAdapter(getApplicationContext(), R.layout.movies_activity_listview, thisMovies);
moviesDisplay.setAdapter(mMovieAdapter);
} else {
Log.w("MyApplication","onPostExecute() did not return any items!");
}
You should initialise and call adapter by this way..........this is just an e.g. you need to modify it according to your controls:
ListView lv = (ListView) v.findViewById(R.id.listview1);
ListViewAdapter adapter = new ListViewAdapter(container.getContext(),
android.R.layout.simple_list_item_1, R.id.textview1);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
And inside the custom adapter class, its constructor should also have these kind of parameters:
public ListViewAdapter(Context context,int resource, int textViewResourceId, List<YourObjectType> items) {
super(context,resource,textViewResourceId, items);
this.context1 = context;
// TODO Auto-generated constructor stub
}

ListView: Null pointer exception

Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.
The error specifically is
NullPointerException at line 76 at MainActivity
Here is the code of my MainActivity
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
final ArrayList<String> studentName = new ArrayList<String>();
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.listName);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);
myList.setAdapter(aa);
//droid.R.id.list;
//add
Button bAdd = (Button) findViewById(R.id.addstudent);
bAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
}
});
//edit
Button bEdit = (Button) findViewById(R.id.editstudent);
bEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
}
});
//edit
Button bDelete = (Button) findViewById(R.id.deletestudent);
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
}
});
}
public ArrayList<String> getArray(){
return studentName;
}
public void notifyArray(){
aa.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and line 76 by the way is
aa.notifyDataSetChanged();
Here is my code for the AddStudents class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddStudents extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_student);
Button bAddStudents = (Button) findViewById(R.id.add);
final EditText et = (EditText) findViewById(R.id.student_name);
bAddStudents.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
MainActivity as = new MainActivity();
as.getArray().add(et.getText().toString());
as.notifyArray();
finish();
}
});
Button bBack = (Button) findViewById(R.id.backadd);
bBack.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
and the xml part with the list view is
<ListView
android:id="#+id/listName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.
In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.
Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).
What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.
public class MainActivity extends Activity {
public static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
activity = this;
}
}
Then in your AddStudent class access it via
MainActivity.activity.notifyArray()
This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)
notifyArray() is being called before onCreate.
Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)
So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation
The common class may go something like:
class CommonHashtable{
private static Hashtable<String, Object> commonHashtable = null;
public static getInstance(){
if(commonHashtable == null)
commonHashtable = new Hashtable<String, Object>();
return commonHashtable;
}
on getInstance(), it returns a commonHashtable which can be used to store values temporarily!
so, add this on addbutton click event
Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());
and add this in you onResume() of MainActivity
Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");
if(studentName != null){
notifyArray();
}

How to implement ProgresDialog [Android]

I am experiencing a problem I have following code:
public void onCreate(Bundle savedInstanceState) {
MyDialog = ProgressDialog.show(this, "Nalagam kanale" , "Prosimo počakaj ... ", true);
MyDialog.show();
... }
Which should actually start he dialog... But the problem is that dialog is shown when everything is loaded...
How can I do solve that?
Actual code
package com.TVSpored;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class Currently extends Activity{
static final int PROGRESS_DIALOG = 0;
private ArrayList<CurrentlyItem> currentItems;
private CurrentAdapter aa;
private ListView currentListView;
private JSONArray CurrentShows;
private Communicator CommunicatorEPG;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.layout_currently);
CommunicatorEPG = new Communicator();
currentItems = new ArrayList<CurrentlyItem>();
if(currentItems == null)
int resID = R.layout.current_item;
aa = new CurrentAdapter(this, resID, currentItems);
currentListView = (ListView)findViewById(R.id.currentListView);
try {
currentListView.setAdapter(aa);
} catch (Exception e) {
Log.d(" * Napaka", e.toString());
}
try {
populateCurrent();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void populateCurrent() throws JSONException
{
CurrentShows = CommunicatorEPG.getCurrentShows(0);
for (int i = 0; i < CurrentShows.length(); i++)
{
JSONObject jsonObject = CurrentShows.getJSONObject(i);
String start = jsonObject.getString("1");
Integer duration = jsonObject.getInt("2");
String title = jsonObject.getString("3");
String epg_channel = jsonObject.getString("4");
String channel_name = jsonObject.getString("5");
CurrentlyItem newItem = new CurrentlyItem(1, 2, 3, 4, 5);
currentItems.add(i, newItem);
}
}
}
This is actual code... I would like to do populateCurrent(); in AsyncTask and meanwhile I would like a loading screen to be shown... Have been trying for few hours now but no actual success... I have successfully shown loading screen and wen trough JSONArray, but couldn't update listview...
Thanks for support!
Expected behaviour...
Show a dialog is a typical task of UI thread, but until you complete the onCreate method, the UI thread s not free to execute the dialog creation...
Two solution: create a dialog in a separate thread or execute your long task in a separate thread.
Some highlights here:
http://developer.android.com/guide/topics/ui/dialogs.html
You could wait to set the content of the activity until the you're finished with the progress dialog.
Update:
This would run your command in async-task:
new AsyncTask<Void, Void, Void> {
protected Long doInBackground(Void... voids) {
populateCurrent();
}
}.execute()
However, then you probably have to make sure to update the list in the GUI thread again and in some way tell the adapter that the list have been updated (since you've given that list to the adapter):
runOnUiThread(new Runnable() {
public void run() {
currentItems.add(i, newItem);
aa.notifyDataSetChanged();
}
}
It is probably best to create a new list entirely and set the view to view that.

Categories

Resources