I am fairly new to Android Application Development. I've been working on an application that computes a person's college GPA. At the moment I am currently struggling to show the GPA a student gets for each Semester. I am only able to print out the results for the first semester.
DISPLAYALLSEMESTERACTIVITY.java
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import static com.example.govinpillai.ca2.R.id.listView1;
public class DISPLAYALLSEMESTERACTIVITY extends AppCompatActivity {
DataManager sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
GPAListAdapter listAdapter ;
ListView LISTVIEW;
String SEMHOLDER;
ArrayList<String> ID_Array;
ArrayList<String> GPA_Array;
ArrayList<String> SEMESTER_Array;
Intent intent;
ArrayList<String> ListViewClickItemArray = new ArrayList<String>();
String TempHolder ;
private String LOG_TAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displayallsemesteractivity);
LISTVIEW = (ListView) findViewById(listView1);
intent = getIntent();
SEMHOLDER = intent.getStringExtra("SEM");
ID_Array = new ArrayList<String>();
GPA_Array = new ArrayList<String>();
SEMESTER_Array = new ArrayList<String>();
sqLiteHelper = new DataManager(this);
LISTVIEW.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(getApplicationContext(),DISPLAYONEGRADEACTIVITY.class);
intent.putExtra("ListViewClickedItemValue",
ListViewClickItemArray.get(position).toString());
startActivity(intent);*/
}
});
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
cursor = sqLiteDatabase.rawQuery("SELECT id, sum(gcproduct)/sum(credit) AS Semestergpa , Semester FROM " + DataManager.TABLE_NAME +" group by Semester", null);
ID_Array.clear();
SEMESTER_Array.clear();
GPA_Array.clear();
if (cursor.moveToFirst()) {
do {
ID_Array.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_ID)));
//Inserting Column ID into Array to Use at ListView Click Listener Method.
/* ListViewClickItemArray.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_ID)));*/
GPA_Array.add(cursor.getString(cursor.getColumnIndex("Semestergpa")));
SEMESTER_Array.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_5_SEMESTER)));
while(!cursor.isAfterLast()) {
Log.e(LOG_TAG, DatabaseUtils.dumpCurrentRowToString(cursor));
cursor.moveToNext();
}
} while (cursor.moveToNext());
}
listAdapter = new GPAListAdapter(DISPLAYALLSEMESTERACTIVITY.this,
ID_Array,
GPA_Array,
SEMESTER_Array
);
LISTVIEW.setAdapter(listAdapter);
cursor.close();
}
}
GPAListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class GPAListAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> GPA;
ArrayList<String> SEMESTER;
public GPAListAdapter(
Context context2,
ArrayList<String> id,
ArrayList<String> gPA,
ArrayList<String> sEMESTER
)
{
this.context = context2;
this.ID = id;
this.SEMESTER = sEMESTER;
this.GPA = gPA;
}
public int getCount() {
// TODO Auto-generated method stub
return ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View child, ViewGroup parent) {
Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.gpaitems, null);
holder = new Holder();
holder.IDTextView = (TextView) child.findViewById(R.id.textViewID);
holder.GPATextView = (TextView) child.findViewById(R.id.textViewGPA);
holder.SEMESTERTextView = (TextView) child.findViewById(R.id.textViewSEMESTER);
child.setTag(holder);
} else {
holder = (Holder) child.getTag();
}
holder.IDTextView.setText(ID.get(position));
holder.GPATextView.setText(GPA.get(position));
holder.SEMESTERTextView.setText(SEMESTER.get(position));
return child;
}
public class Holder {
TextView IDTextView;
TextView GPATextView;
TextView SEMESTERTextView;
}
}
My logcat output
[ 02-03 23:15:46.304 6376: 6376 E/ ]
0 {
id=2
Semestergpa=3.75
SEMESTER=1
}
[ 02-03 23:15:46.304 6376: 6376 E/ ]
1 {
id=4
Semestergpa=3
SEMESTER=2
}
Desired Output in Android Virtual Device
id=2
Semester=1
Semester GPA=3.75
id=4
Semester=2
Semester GPA=3
Actual Output in Android Virtual Device
id=2
Semester=1
Semester GPA=3.75
Could someone show me what have I done wrong and what I can do to fix it ?
In DISPLAYALLSEMESTERACTIVITY.java, my guess is you did cursor.moveToNext() twice, so it advances by 2 & skips one record each time.
For the cursor related code in ShowSQLiteDBdata(), can you try replacing it with the below code?
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
// do everything here first
ID_Array.add(....)
.....
.....
// only move to next cursor position at end of while loop
cursor.moveToNext();
}
}
Hope this help, good luck!
Related
I am trying to delete a row or any row while by clicking on my custom listview adapter which extends Baseadapter. I have found many solutions on Google but none of them worked for me.I am successfully generating a listview with the help of this class but can't delete a row or any row.
Here is my code
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.BaseAdapter;
import com.brl.loverfreedatingapp.R;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class WhoLikedMeAdapter extends BaseAdapter {
private Context context; //context
private ArrayList<String> masterID = new ArrayList<String>();
private ArrayList<String> slaveID = new ArrayList<String>();
private ArrayList<String> masterName = new ArrayList<String>();
private ArrayList<String> slaveName = new ArrayList<String>();
private ArrayList<String> slaveUrl = new ArrayList<String>();
public WhoLikedMeAdapter(Context context, ArrayList<String> masterID, ArrayList<String> slaveID, ArrayList<String> masterName, ArrayList<String> slaveName, ArrayList<String> slaveUrl) {
this.context = context;
this.masterID = masterID;
this.slaveID = slaveID;
this.masterName = masterName;
this.slaveName = slaveName;
this.slaveUrl = slaveUrl;
}
#Override
public int getCount() {
return masterID.size(); //returns total of items in the list
}
#Override
public Object getItem(int position) {
return masterID.get(position); //returns list item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// inflate the layout for each list row
if (convertView == null) {
convertView = LayoutInflater.from(context).
inflate(R.layout.wholikeme_row, parent, false);
}
CircleImageView profile_image = (CircleImageView) convertView.findViewById(R.id.profile_image);
TextView name = (TextView)convertView.findViewById(R.id.name);
ImageButton unlike = (ImageButton)convertView.findViewById(R.id.unlike);
ImageButton like = (ImageButton)convertView.findViewById(R.id.like);
name.setText(slaveName.get(position));
//--
if(slaveUrl.get(position).equals("")){
Picasso.with(context)
.load(R.drawable.image_placeholder)
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}else {
Picasso.with(context)
.load(slaveUrl.get(position))
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}
//-------------
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
unlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
// returns the view for the current row
return convertView;
}
}
Found the solution! I have to remove all the data in a row to remove a listview row. Previously I was trying with only 1 data (masterID).
masterID.remove(position);
slaveID.remove(position);
masterName.remove(position);
slaveName.remove(position);
slaveUrl.remove(position);
notifyDataSetChanged();
I have a custom listview adapter setup up that I need to call in my fragment, but I can't seem the pass my activity to it. I have a very similar set up, but called from within an activity, and it works very well. So, I think the issue is with passing the activity context to the adapter, but I'm not sure how to achieve it.
Below is the code for my fragment, where I make the call to my custom adapter:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class SiblingUnitFragment extends Fragment {
Context siblingContext = this.getActivity();
Activity context = this.getActivity();
ProgressDialog progressDialog;
ListView siblingLVAdapter;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultSiblings;
String HttpURLSiblings = "https://[myDataSpot]/getSiblings.php";
HashMap<String, String> hashMapSiblings = new HashMap<>();
HttpParse httpParse = new HttpParse();
String[] Uuid;
String[] Usize;
String[] Ustatus;
String SV;
String[] svSeparated;
ListView siblingListView;
public SiblingUnitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_siblings, container, false);
siblingListView = (ListView) view.findViewById(R.id.SiblingsList);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null) {
SV = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
}
if (SV.contains("-")) {
svSeparated = SV.split("-");
SearchValue = svSeparated[0];
getSiblings(SearchValue, LexaUser);
} else {
SearchValue = SV;
getSiblings(SearchValue, LexaUser);
}
}
public void getSiblings(String searchInput, String lexaUser) {
class SiblingsClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(siblingContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONArray json = new JSONArray(httpResponseMsg);
Uuid = new String[json.length()];
Usize = new String[json.length()];
Ustatus = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i);
Uuid[i] = object.getString("id");
Usize[i] = object.getString("size");
Ustatus[i] = object.getString("status");
}
siblingLVAdapter = new SiblingsListViewAdapter(context, Uuid, Usize, Ustatus);
siblingListView.setAdapter(siblingLVAdapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(siblingContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(siblingContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapSiblings.put("searchinput", params[0]);
hashMapSiblings.put("lexauser", params[1]);
finalResultSiblings = httpParse.postRequest(hashMapSiblings, HttpURLSiblings);
return finalResultSiblings;
}
}
SiblingsClass siblingsClass = new SiblingsClass();
siblingsClass.execute(searchInput, lexaUser);
}
}
And this is my code for the adapter:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SiblingsListViewAdapter extends BaseAdapter {
Activity context;
String Uuid[];
String Usize[];
String Ustatus[];
public SiblingsListViewAdapter(Activity context, String[] Uuid, String[] Usize, String[] Ustatus) {
super();
this.context = context;
this.Uuid = Uuid;
this.Usize = Usize;
this.Ustatus = Ustatus;
}
public int getCount() {
// TODO Auto-generated method stub
return Uuid.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewUid;
TextView txtViewSize;
TextView txtViewStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.siblings_list, null);
holder = new ViewHolder();
holder.txtViewUid = (TextView) convertView.findViewById(R.id.SiblingsUid);
holder.txtViewSize = (TextView) convertView.findViewById(R.id.SiblingsSize);
holder.txtViewStatus = (TextView) convertView.findViewById(R.id.SiblingsStatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewUid.setText(Uuid[position]);
holder.txtViewSize.setText(Usize[position]);
holder.txtViewStatus.setText(Ustatus[position]);
return convertView;
}
}
And here is the logcat error:
error: incompatible types: SiblingsListViewAdapter cannot be converted to ListView
All help is appreciated. Thank you!
A per the Fragment Lifecycle, You need to call getContext only after onAttach method of your fragment lifecycle is called otherwise there is no associated activity hence there is no context
so use it like
// declare context
Context siblingContext ;
then initialise it
.. onCreateView(...){
siblingContext = getContext();
context = getActvity();
}
you mistake in instantiate your adapter in line 24.change ListView siblingLVAdapter; to
SiblingsListViewAdapter siblingLVAdapter;
and use Context context =getActivity(); or Activity activity=getActivity(); in onAtach methode
I'm trying to get an item deleted from both my custom listview and from the database on button click. I got so far but from the code below you are likely to see my error. When the first item is deleted the positions change however the idarray info is not updated. Please help!
History Adapter:
package uk.co.rascagneres.clocking_app;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Jacques on 08/08/2016.
*/
public class HistoryAdapter extends BaseAdapter implements ListAdapter{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public ArrayList<String> idArray = new ArrayList<String>();
DatabaseHandler db;
public HistoryAdapter (ArrayList<String> list, Context context, ArrayList<String> idArray, DatabaseHandler db){
this.list = list;
this.context = context;
this.idArray = idArray;
this.db = db;
}
#Override
public int getCount(){
return list.size();
}
#Override
public Object getItem(int pos){
return list.get(pos);
}
#Override
public long getItemId(int pos){
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.history_list, null);
}
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(list.get(position));
System.out.println(idArray.get(position));
System.out.print(idArray);
db.deleteRowID(Integer.parseInt(idArray.get(position)));
list.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
HistoryFragment:
package uk.co.rascagneres.clocking_app;
import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Jacques on 03/08/2016.
*/
public class HistoryFragment extends Fragment {
DatabaseHandler db;
View myView;
ArrayList<String> historyArray = new ArrayList<String>();
ArrayList<String> idArray = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.history_layout, container, false);
db = new DatabaseHandler(getActivity());
ArrayList<String> list = insertData();
HistoryAdapter adapter = new HistoryAdapter(list, getActivity(), idArray, db);
ListView lView = (ListView)myView.findViewById(R.id.listView);
lView.setAdapter(adapter);
return myView;
}
public ArrayList<String> insertData(){
Cursor c = db.getAllData();
ArrayList<String> list = new ArrayList<String>();
while(c.moveToNext()) {
int id = c.getInt(0);
long in = c.getLong(1);
long out = c.getLong(2);
String outTime;
if(out == 0){
outTime = "N/A";
}else{
outTime = ClockingFragment.getDate(out, "HH:mm");
}
String date = ClockingFragment.getDate(in, "EEE, MMM d");
String inTime = ClockingFragment.getDate(in, "HH:mm");
historyArray.add(date + "\n Clocked In: " + inTime + "\n Clocked Out: " + outTime + "\n");
idArray.add(String.valueOf(id));
}
if (historyArray.isEmpty()){
historyArray.add("No History Available!");
}
return historyArray;
}
public ArrayList<String> getIdArray(){
System.out.println(idArray);
return idArray;
}
}
Section of Database Handler:
public void deleteRowID(int ID)
{
SQLiteDatabase db = this.getWritableDatabase();
String IDString = String.valueOf(ID);
try
{
db.delete(TABLE_NAME, "ID = ?", new String[] { IDString });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
I am trying to get database from SQLite database and trying to populate the ListView and also adding data in ArrayList<String> . The ListView is populated nicely but problem is ArrayList<String> is not populated nicely.
Suppose I have data in database like:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
........
My ListView Showing data in this way. But ArrayList<String> add the data this way:
A
B
C
D
E
F
A
B
C
D
E
F
G
H
......
That means my ArrayList<String> takes first 6 value then repeat it and then it takes next 6 value then again repeat it ..... . That means When I click item "H" from list view the ArrayList<String> shows me "B". I don't know why it is happening?
My Code, CustomList which extends CursorAdapter
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class CustomList extends CursorAdapter {
CheckBox favoriteBox;
TextView cityName, countryName;
ArrayList<String> city_name;
ArrayList<String> country_name;
ArrayList<String> country_short;
ArrayList<CheckBox> check_box;
public CustomList(Context context, Cursor c, ArrayList<String> city_name,
ArrayList<String> country_name, ArrayList<String> country_short,
ArrayList<CheckBox> check_box) {
super(context, c, 0);
this.city_name = city_name;
this.country_name = country_name;
this.country_short = country_short;
this.check_box = check_box;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.all_city_list, parent, false);
return retView;
}
#Override
public void bindView(final View view, Context context, Cursor cursor) {
cityName = (TextView) view.findViewById(R.id.cityName);
String cityS = cursor.getString(cursor.getColumnIndex("city_name"));
cityName.setText(cityS);
city_name.add(cityS);//adding value to ArrayList<String>
countryName = (TextView) view.findViewById(R.id.countryName);
String conS = cursor.getString(cursor.getColumnIndex("country_name"));
countryName.setText(conS);
country_name.add(conS);//adding value to ArrayList<String>
country_short.add(""
+ cursor.getString(cursor.getColumnIndex("country_short")));//adding value to ArrayList<String>
favoriteBox = (CheckBox) view.findViewById(R.id.favoriteCheckBox);
check_box.add(favoriteBox);
if (cursor.getInt(cursor.getColumnIndex("favorite")) == 0) {
favoriteBox.setChecked(false);
} else {
favoriteBox.setChecked(true);
}
}
}
Class AllCityListFragment which extends Fragment
import java.io.IOException;
import java.util.ArrayList;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
public class AllCityListFragment extends Fragment {
private CustomList customAdapter;
private DatabaseHelper databaseHelper;
ArrayList<String> city_name = new ArrayList<String>();
ArrayList<String> country_name = new ArrayList<String>();
ArrayList<String> country_short = new ArrayList<String>();
ArrayList<CheckBox> check_box = new ArrayList<CheckBox>();
public static final String ARG_OS = "OS";
int pos;
String sql = "";
ListView list;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.all_city_layout, null);
databaseHelper = new DatabaseHelper(view.getContext());
try {
databaseHelper.createDataBase();
databaseHelper.openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(view.getContext(), "Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
list = (ListView) view.findViewById(R.id.citylist);
list.setFocusable(false);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View myview,
int position, long id) {
Toast.makeText(getActivity(),
position + " " + city_name.get(position),
Toast.LENGTH_LONG).show();
}
});
sql = "SELECT _id, city_name, country_name, country_short, favorite FROM city order by country_name asc;";
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomList(getActivity(), databaseHelper
.getResult(sql), city_name, country_name,
country_short, check_box);
list.setAdapter(customAdapter);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In this picture I clicked "Shirajganj" but the Toast shows me "230 Thakurgaon" position =230 is correct but city_name.get(230) should be "Shirajganj" . I think it is doing wrong when I am trying to add value to ArrayList<String> in binView in CustomList. How can I solve this problem?
It's not a good idea to fill that array in bindView method. The Android doesn't create separate view for each row in the list, it's utilize already created ones, that's why you will always receive unexpected results in your arraylist. The better is to fill the array in your activity, instead of the adapter. Just query your database for the same result like this:
Cursor cursor = getContentResolver().query(
uri,
projection,
selectionClause
selectionArgs,
sortOrder);
while (cursor.moveToNext ()){
arrayList.add(cursor.getAsString(cursor.getColumnIndex('column_name')));
}
cursor.close()
I am making a custom adapter for list view and got NPE. I have already read other questions but none of them.
Here is the logcat
07-04 06:54:58.036: E/AndroidRuntime(1340): FATAL EXCEPTION: main
07-04 06:54:58.036: E/AndroidRuntime(1340): java.lang.NullPointerException
07-04 06:54:58.036: E/AndroidRuntime(1340): at com.example.amirkh.MainActivity$FastFoodAdapter.getView(MainActivity.java:166)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.AbsListView.obtainView(AbsListView.java:2159)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.ListView.measureHeightOfChildren(ListView.java:1246)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.ListView.onMeasure(ListView.java:1158)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.view.View.measure(View.java:15518)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.TableRow.measureChildBeforeLayout(TableRow.java:247)
the code works this way. there is a databasehandler that organize database, a fastfood class and main class. in main class the user enteres a fastfood name and it goes to data base. when user clicks on the"show data" tab whole data should be shown.
here is the main class:
package com.example.amirkh;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import android.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ActionProvider;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem.OnActionExpandListener;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends TabActivity {
private TabHost myTabHost;
private FastFoodAdapter<String> adpter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTabHost = getTabHost();
TabHost.TabSpec spec;
// Adding First Tab
spec = myTabHost.newTabSpec("first");
spec.setContent(R.id.inputtab);
spec.setIndicator("Input data");
myTabHost.addTab(spec);
// Adding Second Tab
spec = myTabHost.newTabSpec("second");
spec.setContent(R.id.listView1);
spec.setIndicator("Show data");
myTabHost.addTab(spec);
myTabHost.setCurrentTab(0);
// final List<FastFood> fflist = new ArrayList<FastFood>();
final EditText etname = (EditText) findViewById(R.id.etname);
final EditText etaddress = (EditText) findViewById(R.id.etaddress);
final ListView lv = (ListView) findViewById(R.id.listView1);
final DataBaseHandeler dbh = new DataBaseHandeler(MainActivity.this);
final RadioGroup radiogroup = (RadioGroup) findViewById(R.id.radioGroup1);
final FastFood fastfood = new FastFood();
final RadioButton rbsit = (RadioButton) findViewById(R.id.rbsit);
final RadioButton rbdeli = (RadioButton) findViewById(R.id.rbdeliv);
final RadioButton rbtake = (RadioButton) findViewById(R.id.rbtake);
refreshComponents();
Button save = (Button) findViewById(R.id.btnsave);
Button remove = (Button) findViewById(R.id.btnremove);
// Create context menu
registerForContextMenu(lv);
// end of context menu
// start of save button
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
FastFood ffastfood = new FastFood("", "", "");
ffastfood.setName(etname.getText().toString());
ffastfood.setAddress(etaddress.getText().toString());
etname.setText("");
etaddress.setText("");
if (rbsit.isChecked()) {
ffastfood.setFlag("1");
} else if (rbtake.isChecked()) {
ffastfood.setFlag("2");
} else if (rbdeli.isChecked()) {
ffastfood.setFlag("3");
}
Toast toast = Toast.makeText(MainActivity.this,
"Fastfood is saved.", 2000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
dbh.addFastFood(ffastfood);
refreshComponents();
}
}); // end of save
// remove
remove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
EditText etrmvid = (EditText) findViewById(R.id.etrmvid);
dbh.removeFastFood(Integer.parseInt(etrmvid.getText()
.toString()));
etrmvid.setText("");
Toast toast = Toast.makeText(MainActivity.this,
"Fastfood is removed.", 2000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
refreshComponents();
}
});// end of remove
Context context = getApplicationContext();
// Adapter
}
class FastFoodAdapter<String> extends ArrayAdapter<String> {
public FastFood fastfood = new FastFood();
public FastFoodAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_item_row, parent,
false);
}
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_item_row, parent,
false);
TextView tv = (TextView) row.findViewById(R.id.txtTitle23);
TextView tv2 = (TextView) row.findViewById(R.id.txtTitle2);
ImageView iv = (ImageView) row.findViewById(R.id.imgIcon);
tv.setText(fastfood.getName());
tv2.setText(fastfood.getAddress());
if (fastfood.getFlag().equals("1"))
iv.setImageResource(R.drawable.sit);
else if (fastfood.getFlag().equals("2"))
iv.setImageResource(R.drawable.ta);
else if (fastfood.getFlag().equals("3"))
iv.setImageResource(R.drawable.deli);
return row;
}
}// /end of adapter
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.contexmenu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return super.onContextItemSelected(item);
}
private void refreshComponents() {
ListView lv = (ListView) findViewById(R.id.listView1);
TextView lblCount = (TextView) findViewById(R.id.lblcount);
DataBaseHandeler dbh = new DataBaseHandeler(MainActivity.this);
List<FastFood> fflist = dbh.getAllFastFoods();
// lv.setAdapter(new FastFoodAdapter<String>(context,
// textViewResourceId, objects))
lv.setAdapter(new FastFoodAdapter<FastFood>(MainActivity.this,
android.R.layout.simple_list_item_1, fflist));
lblCount.setText("Count of all FastFoods are " + dbh.getFastFoodCount());
}
}
here is fastfood class
package com.example.amirkh;
public class FastFood {
private String name;
private String address;
private String flag;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public FastFood(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
}
public FastFood() {
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return (String.format("%s %s ", getName(), getAddress()));
}
}
and the databasehandeler
package com.example.amirkh;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandeler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "FastFoodManager";
private static final String TABALE_FASTFOODS = "fastfoods";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
private static final String KEY_ADDRESS = "address";
private static final String KEY_FLAG = "flag";
public DataBaseHandeler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABALE_FASTFOODS + " ("
+ KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, "
+ KEY_ADDRESS + " TEXT, " + KEY_FLAG + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABALE_FASTFOODS);
onCreate(db);
}
// insert a record
public void addFastFood(FastFood fastfood) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, fastfood.getName());
values.put(KEY_ADDRESS, fastfood.getAddress());
values.put(KEY_FLAG, fastfood.getFlag());
db.insert(TABALE_FASTFOODS, null, values);
db.close();
}
// remove a record by ID
public void removeFastFood(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABALE_FASTFOODS, KEY_ID + " =?",
new String[] { String.valueOf(id) });
db.close();
}
// count
public int getFastFoodCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABALE_FASTFOODS, null);
// db.close();
return cursor.getCount();
}
// get all contacts
public List<FastFood> getAllFastFoods() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABALE_FASTFOODS, null);
List<FastFood> fflist = new ArrayList<FastFood>();
if (cursor.moveToFirst()) {
do {
FastFood ff = new FastFood();
ff.setId(Integer.parseInt(cursor.getString(0)));
ff.setName(cursor.getString(1));
ff.setAddress(cursor.getString(2));
ff.setFlag(cursor.getString(3));
fflist.add(ff);
} while (cursor.moveToNext());
}
// db.close();
return fflist;
}
}
Thanks for helping
You are getting this NullPointerException because you are trying to compare a null String in this line
fastfood.getFlag().equals("1")
In your adapter you create an object of Food using
public FastFood fastfood = new FastFood();
In the empty constructor of Food class nothing is assigned to any of the member String so when you try to do
fastfood.getFlag().equals("1")
you are trying to call equals method on a null object.
So you get a NullPointerException.
You should use the Food objects from the List that you pass in the FastFoodAdapter constructor.
Your NPE come from:
if (fastfood.getFlag().equals("1"))
So fastfood.getFlag() seems null. You should use setFlag() before or try this comparison:
if ("1".equals(fastfood.getFlag()))