Android - pass data between from an Activity class to an Adapter class - android

I have 3 classes: LoginActivity,MapsActivity and MatchAdapter
The first 2 extends AppCompactActivity, the last one ArrayAdapter.
When i make login (if correct, matching on mySQLiteDB) i used to get ID_contact of current user and pass it to MapsActivity with intent in such way:
On my LoginActivity:
String contact=databaseHelper.searchID_Contact(username,password);
Intent intent=new Intent(LoginActivity.this,MapsActivity.class);
intent.putExtra("ID_CONTACT",contact);
startActivity(intent);
On MapsActivity i can easily retrieve this data in such way:
public String getId_contact(String conct){
return conct;
}
#Override
public void onMapReady(GoogleMap googleMap) {
String id_contact1=getIntent().getStringExtra("ID_CONTACT");
String contact=getId_contact(id_contact1);
Toast.makeText(MapsActivity.this, contact, Toast.LENGTH_LONG).show();
}
Till now everything works fine, it appears the id of the current user.
My problem is to pass this data (with intent i don't know how) even to another class named MatchAdapter that extends ArrayAdapter.
I tried this way on MapsActivity:
public class MapsActivity extends AppCompatActivity implements ...{
public String getId_contact(){
String contact=getIntent().getStringExtra("ID_CONTACT");
return contact;
}
So on MatchAdaper trying to retrieve such way:
MapsActivity mapsActivity=new MapsActivity();
String text=mapsActivity.getId_contact().toString();
But nothing..i get NULLPOINTEREXCEPTION...Can someone help me?

Ok...found the solution...On MatchAdapter extends ArrayAdapter
DatabaseHelper databaseHelper=new DatabaseHelper(getContext());
...than OnClick function....
databaseHelper.myfunction();

Well you can access method of activity from an adapter by following way, Call this method from constructor of adapter or anywhere you want.
((ActivityName)context).methodName();

When you create a new instance of MapsActivity, that isn't the same Activity instance you got when you called startActivity(). This is basically why you have a null pointer exception.
More importantly, you should never be manually creating Activity instances using "new". Generally the system creates Activity objects for you via mechanisms like startActivity(), and that is how you should obtain them.
Himanshu's suggestion can work, if your activity does happen to be "hosting" your adapter, but this isn't always guaranteed. A better approach is to pass the ID to your MatchAdapter directly, either in the constructor or as a direct setter function. At the least, you should perform a "instanceof" check to make sure your adapter context is really of type MapsActivity.

That's my MatchAdapter `package vincenzo.futsal4you;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
public class MatchAdapter extends ArrayAdapter{
List list=new ArrayList();
String text1=null;
MatchAdapter matchAdapter;
static String id_contatto3="";
String fatto3="";
Player player=new Player();
public MatchAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Match object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
final Context context = null;
final MatchHolder matchHolder;
final String cc=null;
if (row==null){
LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.display_match_row,parent,false);
matchHolder=new MatchHolder();
matchHolder.id_match=(TextView)row.findViewById(R.id.id_partita);
matchHolder.id_contact=(TextView)row.findViewById(R.id.id_contatto);
matchHolder.nome_partita=(TextView)row.findViewById(R.id.nome_partita);
matchHolder.citta=(TextView)row.findViewById(R.id.citta);
matchHolder.indirizzo=(TextView)row.findViewById(R.id.indirizzo);
matchHolder.data=(TextView)row.findViewById(R.id.data);
matchHolder.ora=(TextView)row.findViewById(R.id.ora);
// matchHolder.id_contact=row.findViewById()
matchHolder.join_us = (Button) row.findViewById(R.id.join_us);
row.setTag(matchHolder);
}
else {
matchHolder=(MatchHolder)row.getTag();
}
final Match match=(Match)getItem(position);
// matchHolder.id_contact.setText(mapsActivity.getId_partita().toString());
matchHolder.id_match.setText(match.getId().toString());
matchHolder.nome_partita.setText(match.getName().toString());
matchHolder.citta.setText(match.getCitta().toString());
matchHolder.indirizzo.setText(match.getIndirizzo().toString());
matchHolder.data.setText(match.getData().toString());
matchHolder.ora.setText(match.getOra().toString());
// assert ((MapsActivity) context) != null;
// ((MapsActivity) context).getId_partita();
// final String contact=matchHolder.getId_contatto();
Log.e("BOOOOOO", matchHolder.getId_contatto2());
final String fatto=matchHolder.getId_contatto2();
fatto3=matchHolder.getId_contatto2();
matchHolder.join_us.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//
String fatto2=matchHolder.getId_contatto2();
// final String text3=mapsActivity.getId_partita(cc).toString();
RelativeLayout rl = (RelativeLayout) v.getParent();
RelativeLayout r2 = (RelativeLayout) v.getParent();
// TextView tv = (TextView)rl.findViewById(R.id.nome_partita);
TextView tv = (TextView) rl.findViewById(R.id.id_partita);
TextView tv2 = (TextView) r2.findViewById(R.id.id_contatto);
String id_partita = tv.getText().toString();
String text2 = tv2.getText().toString();
Toast.makeText(getContext(), id_partita, Toast.LENGTH_SHORT).show();
// Toast.makeText(getContext(), matchHolder.setId_contatto(contact), Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),matchHolder.getId_contatto2(),Toast.LENGTH_SHORT).show();
player.setId_contatto(fatto3);
player.setId_partita(id_partita);
// databaseHelper=new DatabaseHelper(context);
// databaseHelper.insertPlayer2(player);
((MapsActivity)context).getJoinPlayer(player);
Toast pass1=Toast.makeText(getContext(), "One Row JOIN US created !", Toast.LENGTH_SHORT);
pass1.show();
}
});
return row;
}
static class MatchHolder{
TextView id_match,nome_partita,citta,indirizzo,data,ora,id_contact;
Button join_us;
public MatchHolder(){}
public String getId_contatto(String id_contatto) {
return id_contatto;
}
public String getId_contatto2() {
return id_contatto3;
}
public void setId_contatto(String id_contatto) {
id_contatto3 = id_contatto;
}
public MatchHolder(String id_contatto){
id_contatto3=id_contatto;
}
}
}
` So the problem was that i declared a String (id_contatto3) inside a static (inner) class (MatchHolder).Declaring it up to MatchAdapter i solve it somehow, but now i wanna call inside onClick a method that is inside another class (DatabaseHelper that extends SQLiteOpenhelper)..
I can't do ((DatabaseHelper)context).mymethod() So i've done the following "trick"...inside class MapsActivity where i've created a method (JoinPlayer) in such way:
public void JoinPlayer(Player player){
databaseHelper.insertPlayer(player);
}
where insertPlayer(Player) in DatabaseHelper is:
public void insertPlayer(Player player){
try{
db=this.getWritableDatabase();
}
catch(Exception e){
Log.e("ERROR","ERROR");
}
ContentValues contentValues=new ContentValues();
String query="select * from player";
Cursor cursor=db.rawQuery(query,null);
int count=cursor.getCount();
contentValues.put(COLUMN_ID_PLAYER,count);
contentValues.put(COLUMN_ID_MATCH_PLAYER,player.getId_partita());
contentValues.put(COLUMN_ID_CONTACT_PLAYER,player.getId_contatto());
db.insert(TABLE_PLAYER, null, contentValues);
db.close();
}
But Android suggest me to add a null condition(if ((MapsActivity)context)!=null) than ((MapsActivity)context).JoinPlayer(player) but it advise me it will be Always null and that's exactly what I get... I think is the context the main problem but have no clue right now how to solve it. Any Idea?

Related

Call another activity in Android using onPostExecute method list item click event in AsyncTask

I am working on a project which populating SQLite database table for list view and using simple array adapter.
I'm using Asyntask for that purpose and I have problem when:
I want to call another activity and
pass some values which I get from the setOnItemClickListener
I need to archive this two things in onPostExecute setOnItemClickListener method. This is my code for that.
package com.me.doctor.doctor_me;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String,Doctor,String> {
Context ctx;
DoctorAdapter doctorAdapter;
Activity activity;
ListView listView;
Doctor doctor;
DisplayDoctor displayDoctor;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity) ctx;
doctor = new Doctor();
displayDoctor = new DisplayDoctor();
}
#Override
protected String doInBackground(String... strings) {
String method = strings[0];
DatabaseOperation databaseOperation = new DatabaseOperation(ctx);
if(method.equals("get_info")){
listView = activity.findViewById(R.id.display_list_view);
SQLiteDatabase db = databaseOperation.getReadableDatabase();
Cursor cursor = databaseOperation.getInformation(db);
doctorAdapter = new DoctorAdapter(ctx,R.layout.display_doctor_row);
String name, category, hospital;
int id;
while(cursor.moveToNext()){
id = cursor.getInt(cursor.getColumnIndex("d_id"));
name = cursor.getString(cursor.getColumnIndex("d_name"));
category = cursor.getString(cursor.getColumnIndex("d_category"));
hospital = cursor.getString(cursor.getColumnIndex("d_hospital"));
Doctor doctor = new Doctor(id,name,category,hospital);
publishProgress(doctor);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Doctor... values) {
// add each of doctor class object add method inside the adapter class
doctorAdapter.add(values[0]);
}
#Override
protected void onPostExecute(String s) {
if(s.equals("get_info")){
listView.setAdapter(doctorAdapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
Doctor doctor = (Doctor)parent.getItemAtPosition(position);
String ID = Integer.toString(doctor.getId());
Toast.makeText(ctx,ID,Toast.LENGTH_LONG).show();
// I need fire another activity and pass some values which i getting here
}
});
}else{
Toast.makeText(ctx,s,Toast.LENGTH_LONG).show();
}
}
}
And this is the class which call to the AsyncTask Class
package com.me.doctor.doctor_me;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DisplayDoctor extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_doctor_layout);
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute("get_info");
}
}
I had investigate closed question on Stack Overflow, but I did not found a solution.
Short answer:
you already have context in Background task
Context ctx;
use this this to call next activiry
ctx.startActivity(nextActivityIntent)
u can add values to the intent like this
Intent nextActivityIntent = new Intent(ctx,NextActivity.class);
nextActivityIntent.putExtra("data", "some data");
with async task i guess you are trying to query data base on another thread
You can use loaders for the same
Loaders run on separate thread
here is a simple example of cursor loader
example taken from github
public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks {
public static final int LOADER_ID = 0;
private ArrayAdapter<String> forecastAdapter;
private ForecastAdapter mForecastAdapter;
public ForecastFragment() { }
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
getLoaderManager().initLoader(LOADER_ID, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//some database query
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//some action
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}

Refreshing ListView each time I search a new term

I am using google book API to search a book with the title.It shows me the result for the first time. The next I search it clears the ListView but not showing the new search result.
There is a peculiar error. When I search a book it shows me 3 to 4 books whereas I have set MaxResult to 10. When I manually call the API in the browser I get 10 results.
Here is the code I am using.
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Book>>{
private static final int BOOK_ID = 1;
public static final String LOG_TAG = MainActivity.class.getName();
private static String book_url;
private BookAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt=(Button)findViewById(R.id.search);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchTerm=(EditText)findViewById(R.id.search_book);
String search=searchTerm.getText().toString();
book_url="https://www.googleapis.com/books/v1/volumes?q="+search+"&maxResults=10";
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_ID, null, MainActivity.this);
mAdapter=new BookAdapter(MainActivity.this,new ArrayList<Book>());
ListView bookListView=(ListView)findViewById(R.id.list);
mAdapter.notifyDataSetChanged();
bookListView.setAdapter(mAdapter);
}
});
}
public Loader<List<Book>> onCreateLoader(int i,Bundle bundle){
return new BookLoader(this,book_url);
}
public void onLoadFinished(Loader<List<Book>> loader,List<Book> books){
mAdapter.clear();
if(books!=null&&!books.isEmpty()){
mAdapter.addAll(books);
}
}
public void onLoaderReset(Loader<List<Book>> loader){
mAdapter.clear();
}
}
I tried notifyDataSetChanged(). But it doesn't work.
Here is the code for custom adapter
package com.example.android.booksearch;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by AKSPAN12 on 19-07-2017.
*/
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context context, List<Book> books) {
super(context, 0,books);
}
public View getView(int position, View convertView, ViewGroup parent){
View listItemView=convertView;
if(listItemView==null){
listItemView= LayoutInflater.from(getContext()).inflate(R.layout.book_list,parent,false);
}
Book currentBook=getItem(position);
String author=currentBook.getAuthor();
TextView authorView=(TextView)listItemView.findViewById(R.id.book_author);
authorView.setText(author);
String bookName=currentBook.getBook();
TextView bookView=(TextView)listItemView.findViewById(R.id.book_name);
bookView.setText(bookName);
return listItemView;
}
}
It shows me the result for the first time. The next I search it clears the ListView but not showing the new search result.
You probably need to restart your loader.

Package has already posted 50 toasts. Not showing more

Hello I am working on an app and in which at one point I need to take input from user and store it in database and then fetch that data and put it on different TextView. Problem is I did stored the data in database and when i trying to fetch it My app shows a pop up i.e : App is not responding and logcat shows this:
Package has already posted 50 toasts. Not showing more.
I have used 6 database operations before this pullAccStt can this be a problem.
DatabseAdapotor
public long updateAccSettTable(String loactionName, String hospitalname, String PatientId, String FirstName, String MiddleName, String LastName, String DOB,
String Gender, String Weight, String Height, String MobNo, String emailId, String Ethinicity, String patientConcentStatus, String DevicePatientId,
String CoSensorId, String DeviceId, String VideoId){
SQLiteDatabase db= helper.getWritableDatabase();
ContentValues contentValuesAccSett= new ContentValues();
contentValuesAccSett.put(DatabaseHelper.PatientId,PatientId);
contentValuesAccSett.put(DatabaseHelper.LocationName,loactionName);
contentValuesAccSett.put(DatabaseHelper.HospitalName,hospitalname);
contentValuesAccSett.put(DatabaseHelper.FirstName,FirstName);
contentValuesAccSett.put(DatabaseHelper.MiddleName,MiddleName);
contentValuesAccSett.put(DatabaseHelper.LastName,LastName);
contentValuesAccSett.put(DatabaseHelper.DateOfBirth,DOB);
contentValuesAccSett.put(DatabaseHelper.Gender,Gender);
contentValuesAccSett.put(DatabaseHelper.Weight,Weight);
contentValuesAccSett.put(DatabaseHelper.Height,Height);
contentValuesAccSett.put(DatabaseHelper.MobileNo,MobNo);
contentValuesAccSett.put(DatabaseHelper.EmailId,emailId);
contentValuesAccSett.put(DatabaseHelper.Ethnicity,Ethinicity);
contentValuesAccSett.put(DatabaseHelper.P_ConsentStatus,patientConcentStatus);
contentValuesAccSett.put(DatabaseHelper.DevicePId,DevicePatientId);
contentValuesAccSett.put(DatabaseHelper.DeviceId,DeviceId);
contentValuesAccSett.put(DatabaseHelper.CoSensorId,CoSensorId);
contentValuesAccSett.put(DatabaseHelper.VideoId,VideoId);
long id1= db.insert(DatabaseHelper.Accoun_setting_Table,null,contentValuesAccSett);
if (id1<0){
Message.message(helper.context,"Unsuccessfull");
}else {
Message.message(helper.context,"Account setting Updated");
}
db.close();
return id1;
}
public String pullAccSett(){
String patientId = null;
Message.message(helper.context,"patient id is: ");
SQLiteDatabase db=helper.getWritableDatabase();
String query="Select * From "+DatabaseHelper.Accoun_setting_Table+" ;";
Cursor AccCursor=db.rawQuery(query,null);
Message.message(helper.context,"query "+query);
while(AccCursor.moveToFirst()) {
int index1 = AccCursor.getColumnIndex(DatabaseHelper.PatientId);
patientId=AccCursor.getString(index1);
}
AccCursor.close();
db.close();
return patientId ;
}
Activity Class calling this
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class AccountSettingFragment extends Fragment {
FloatingActionButton fabEdit;
DatabaseAdaptor databaseAdaptor=null;
TextView PatientId;
private Context context;
public AccountSettingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_account_setting, container, false);
fabEdit=(FloatingActionButton)view.findViewById(R.id.btnFabEdit);
PatientId=(TextView)view.findViewById(R.id.patientId);
context=getActivity();
databaseAdaptor=new DatabaseAdaptor(context);
databaseAdaptor.pullAccSett();
fabEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AccountsSettingEdit.class);
getActivity().startActivity(intent);
}
});
return view;
}
}
Message Class
import android.content.Context;
import android.widget.Toast;
/**
* Created by frnds on 3/2/2016.
*/
public class Message {
public static void message(Context context,String message){
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
}
And when i call this pullAccSett(); my app hangs and goes to not responding.
and log cat shows message:
Package has already posted 50 toasts. Not showing more.
What is the reason behind this.
Your while loop i thinks will runs for infinite time. because every time it will be true and you have no break statement.
so change your code like this.
try {
if (AccCursor.moveToFirst()) {
while (AccCursor.moveToNext()) {
//code for fetch data from cursor
}
}
AccCursor.close();
}catch (Exception e) {
Log.e("Getdata", e.getMessage(), e);
}
There is some enhancement for the code above. If cursor is in position -1, AccCursor.moveToNext will move it to position 0, so you can do better something like:
try {
while(AccCursor.moveToNext()) {
//Execute code
}
AccCursor.close();
}catch(final Exception lException) {
Log.e("Getdata", "Exception looping Cursor: " + lException.getMessage());
}

How to make a listview accept and display as much data as entered

If anyone knows, I was learning from O'reily Head First Android development book and got stuck in the code of page of 338 where it uses addTimeRecord but it doesn't work acually... In the example or following code as I press "Save the data" time and note fields should be added to listview. Can somebody help please?
First the MainActivity
package com.sigdel.practicelistview;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
TimeTrackerAdapter timeTrackerAdapter;
ListView listView;
TimeRecord record;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//until now listview is displayed but is empty so now we add data in list
//and control its behaviour by adapter
ListView listView = (ListView) findViewById(R.id.times_list);
TimeTrackerAdapter timeTrackerAdapter =new TimeTrackerAdapter();
//listView is the name for the listview and timeTrackerAdapter is the name for adapter
listView.setAdapter(timeTrackerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.time_list_menu, menu);
return true;
}
public static final int TIME_ENTRY_REQUEST_CODE = 1;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.add_time_menu_item) {
Intent intent = new Intent(this, AddTimeActivity.class);
//startActivity(intent);
startActivityForResult(intent,TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String time = data.getStringExtra("time");
String note = data.getStringExtra("note");
Toast.makeText(this, time,Toast.LENGTH_SHORT).show();
Toast.makeText(this, note,Toast.LENGTH_SHORT).show();
timeTrackerAdapter.addTimeRecord( new TimeRecord(time, notes));
//this above line doesn't work addTimeRecord is not defined
timeTrackerAdapter.notifyDataSetChanged();
}
}
}
}
TimeRecord
package com.sigdel.practicelistview;
//creating data object called TimeRecord
//Based on the app design, you’ll need to store a
//time and note for each time entered. Rather than
//separately storing that information, create a data
//object to store both fields in a single object.
//you build an Adapters that stores
//data, build your own data object to keep
//your data organized
public class TimeRecord {
private String time;
private String notes;
public TimeRecord(String time, String notes) {
//TimeRecord is the object here. this refers to TimeRecord. now you define your object constructor
// you say that your TimeRecord object should have time and notes as fields
// that have time and notes as variables
// thus time and notes are ready to accept the returned values to define the
//TimeRecord object
this.time = time;
this.notes = notes;
//ghokne
}
//Now get ready to return time and notes values to create the object to be displayed
//in the listview
//Below are the methods to return the values to define object
public String getTime() { return time; }
//Ok once real time is returned, now you need to set it
public void setTime(String time) { this.time = time; }
public String getNotes() { return notes; }
public void setNotes(String notes) { this.notes = notes; }
}
TimeTrackerAdapter
package com.sigdel.practicelistview;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class TimeTrackerAdapter extends BaseAdapter{
private ArrayList<TimeRecord> times = new ArrayList<TimeRecord>();
#Override
public int getCount() {
return times.size();
}
#Override
public Object getItem(int index) {
return getItem(index);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(int index, View view, ViewGroup parent) {
//The first time getView is called on your Adapter,
//the View passed in is null. Since the Adapter
//knows how the data should be displayed, it’s up to
//the Adapter to instantiate the View the first time.
if (view == null){
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.time_list_item, parent, false);
}
//The TimeRecord object in the ArrayList at the index has everything you need to populate the view.
//say that time holds the object in a row of the index
TimeRecord time = times.get(index);
//say that the time_view of the layout should display the value carried by timeTextView
TextView timeTextView = (TextView) view.findViewById(R.id.time_view);
//set the string in getTime() part of TimeRecord object as timeTextView.
//i.e timeTextView is the layout, time is the object and getTime() is the time part of the object
timeTextView.setText(time.getTime());
TextView notesTextView = (TextView) view.findViewById(R.id.notes_view);
//set the string in getNotes() part of TimeRecord object as notesTextView.
//notesTextView layout ma time object ko getNOtes() part ko string lai set garne
notesTextView.setText(time.getNotes());
return view;
}
public TimeTrackerAdapter() {
times.add(new TimeRecord("38:23", "Feeling good!"));
times.add(new TimeRecord("48:23", "Feelingjj good!"));
times.add(new TimeRecord("18:23", "Feelingookkl good!"));
times.add(new TimeRecord("32:23", "Feelioong good!"));
}
}
1. You'll get stack overflow on TimeTrackerAdapter.getItem(int index).
The method is infinitely calling itself. You might want to return something like this:
#Override
public TimeRecord getItem(int index) {
return times.get(i);
}
2. Implement TimeTrackerAdapter.addTimeRecord(TimeRecord)
Your adapter lacks method for adding new items. You could implement it in this way:
public void add(TimeRecord record) {
items.add(record);
}
Now after you call timeTrackerAdapter.notifyDataSetChanged() the data should be displayed in the list.

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/

Categories

Resources