Null Pointer Exception in Receiving serializable object - android

I am trying to populate values into list view. It is working fine. And on clicking list row its description activity is going to open. I am getting null pointer exception on populating values.
ListView mylistview = null;
mylistview = (ListView) findViewById(R.id.list);
CustomAdapter listAdapter = new CustomAdapter(SearchActivityResult.this, 0, temp);
mylistview.setAdapter(listAdapter);
list=temp;
mylistview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
Intent i = new Intent(SearchActivity.this, DescriptionActivity.class);
Bundle b = new Bundle();
b.putSerializable("plant", list.get(pos));
i.putExtras(b);
startActivity(i);
Then this serializable object is received as following:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
plant = (Plant) b.getSerializable("plant");
setContentView(R.layout.description_activity);
setTitle("Flora Enroute");
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent = titleView.getParent();
if (parent != null && (parent instanceof View)) {
View parentView = (View)parent;
parentView.setBackgroundColor(Color.parseColor("#99CC00"));
}
}
initViews();
populateValues();
}
private void populateValues() {
Picasso.with(this).load(plant.getimagepath()).error(R.drawable.plant_icon).resize(240,320).into(ivImage);
commonname.setText(plant.getcommonname());
scientificname.setText(plant.getscientificname());
planttype.setText(plant.getplanttype());
season.setText(plant.getseason());
growthhabit.setText(plant.getgrowthhabit());
duration.setText(plant.getduration());
leafshape.setText(plant.getleafshape());
flowershape.setText(plant.getflowershape());
flowercolor.setText(plant.getflowercolor());
lightexposure.setText(plant.getlightexposure());
growthrate.setText(plant.getgrowthrate());
waterreq.setText(plant.getwaterrequirement());
sid.setText(plant.getsid());
features.setText(plant.getfeatures());
}
private void initViews() {
commonname = (TextView) findViewById(R.id.commonname);
duration = (TextView) findViewById(R.id.duration);
features = (TextView) findViewById(R.id.features);
flowercolor = (TextView) findViewById(R.id.flowercolor);
flowershape = (TextView) findViewById(R.id.flowershape);
growthhabit = (TextView) findViewById(R.id.growthhabit);
growthrate = (TextView) findViewById(R.id.growthrate);
leafshape = (TextView) findViewById(R.id.leafshape);
lightexposure = (TextView) findViewById(R.id.lightexposure);
planttype = (TextView) findViewById(R.id.planttype);
scientificname = (TextView) findViewById(R.id.scientificname);
season = (TextView) findViewById(R.id.season);
sid = (TextView) findViewById(R.id.sid);
showMap = (TextView) findViewById(R.id.show_map);
ivImage = (ImageView) findViewById(R.id.iv_);
}
I am getting null pointer exception on poulate values function. When I click any list row to start its description activity I got null pointer exception.

In populateValues(), you are setting texts for various textviews.
All other textviews are initialized in initViews(). But you have missed initializing waterreq
So you may be getting NPE on line:
waterreq.setText(plant.getwaterrequirement());
Please initialize it in initViews() function.
Hope this helps.

Related

Click Button to pass argument from fragment to another fragment

I am trying to make this but errors.
When I click a button and it executes function "showData()" ;
The reason I want to do this function because I want to change a fragment when
I click this button and also "pass the arguments" to the new fragment.
So it will keep executing function "passData()";
But it will get NullPointerException after 「editTextNAME.setText(restaurant.name); 」this line.
showData()
public void showData(View view){
RestaurantRepo repo = new RestaurantRepo(this);
ArrayList<HashMap<String, String>> restaurantList = repo.getRestaurantList();
if ( restaurantList.size()!=0 ) {
ListView lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
restaurantID = (TextView) view.findViewById(R.id.restaurantID);
String idRestaurant = restaurantID.getText().toString();
Bundle data = new Bundle();
data.putString("restaurantID", idRestaurant); // argument
Fragment fraUorD = null;
fraUorD = new EditFragment_Fix_UorD();
if ( null != fraUorD ) {
android.app.FragmentManager fragementManager = getFragmentManager();
android.app.FragmentTransaction transaction = fragementManager.beginTransaction();
transaction.replace(R.id.content_frame, fraUorD);
transaction.addToBackStack(null);
transaction.commit();
passData(data); // when transaction done , execute passData() -> i want to pass argument when the new fragment come out
}
}
});
ListAdapter adapter = new SimpleAdapter( MainActivity.this,restaurantList, R.layout.edit_fragment_fix_view,
new String[] { "id","name","type","price","phone","addr"},
new int[] {R.id.restaurantID, R.id.restaurantNAME,R.id.restaurantTYPE,
R.id.restaurantPRICE,R.id.restaurantPHONE,R.id.restaurantADDR});
lv.setAdapter(adapter);
}
else
Toast.makeText(this,"No restaurant!",Toast.LENGTH_SHORT).show(); // no data
passData()
public void passData(Bundle data){
int a = Integer.parseInt( data.getString("restaurantID", "")) ; // get it
Toast.makeText(this, ""+a,Toast.LENGTH_SHORT).show();
editTextNAME = (EditText) findViewById(R.id.editTextUpdateName);
editTextTYPE = (EditText) findViewById(R.id.editTextUpdateType);
editTextPRICE = (EditText) findViewById(R.id.editTextUpdatePrice);
editTextPHONE = (EditText) findViewById(R.id.editTextUpdatePhone);
editTextADDR = (EditText) findViewById(R.id.editTextUpdateAddr);
RestaurantRepo repo = new RestaurantRepo(this);
Restaurant restaurant = new Restaurant();
restaurant = repo.getRestaurantById(a);
// Everything is ok, but when executing codes below here will get errors
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
editTextNAME.setText(restaurant.name);
editTextTYPE.setText(String.valueOf(restaurant.type));
editTextPRICE.setText(String.valueOf(restaurant.price));
editTextPHONE.setText(restaurant.phone);
editTextADDR.setText(restaurant.addr);
}
Logcat here :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.example.user.foody.MainActivity$override.passData(MainActivity.java:284)
at com.example.user.foody.MainActivity$override.access$dispatch(MainActivity.java)
at com.example.user.foody.MainActivity.passData(MainActivity.java:0)
at com.example.user.foody.MainActivity$2$override.onItemClick(MainActivity.java:244)
at com.example.user.foody.MainActivity$2$override.access$dispatch(MainActivity.java)
at com.example.user.foody.MainActivity$2.onItemClick(MainActivity.java:0)
The problem is that you cannot findviewbyId on fragment before onViewCreated.
I recommend reading this post about passing data through fragments.
http://gunhansancar.com/best-practice-to-instantiate-fragments-with-arguments-in-android/
important piece:
public static MyFragment newInstance(...)

Android 2 sqlite database tables in the same listview adapter

I have made an android SQLite database with two tables, each of them are performing in separate activities. And I'm trying to put them in the same listview.
This is my activity where the listview is.
public class MainActivity extends ActionBarActivity {
ListView lv;
SQLController dbcon;
TextView incomeID_tv, incomePayer_tv, incomeAmount_tv;
TextView incomeDate_tv, incomeCategory_tv, incomePayments_tv;
TextView expenseID_tv, expensePayee_tv, expenseAmount_tv;
TextView expenseDate_tv, expenseCategory_tv, expensePayments_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbcon = new SQLController(this);
dbcon.open();
lv = (ListView) findViewById(R.id.incomeList_id);
Cursor cursor = dbcon.readIncomeData();
String[] from = new String[] { DBHelper.INCOME_ID, DBHelper.INCOME_AMOUNT, DBHelper.INCOME_PAYER,
DBHelper.INCOME_DATE, DBHelper.INCOME_CATEGORY, DBHelper.INCOME_PAYMENTS};
int[] to = new int[] { R.id.income_id, R.id.income_amount, R.id.income_payer, R.id.income_date,
R.id.income_category, R.id.income_payments};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.income_entry, cursor, from, to);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
Cursor ecursor = dbcon.readExpenseData();
String[] efrom = new String[] { DBHelper.EXPENSE_ID, DBHelper.EXPENSE_AMOUNT, DBHelper.EXPENSE_PAYEE,
DBHelper.EXPENSE_DATE, DBHelper.EXPENSE_CATEGORY, DBHelper.EXPENSE_PAYMENTS};
int[] eto = new int[] { R.id.expense_id, R.id.expense_amount, R.id.expense_payee, R.id.expense_date,
R.id.expense_category, R.id.expense_payments};
SimpleCursorAdapter eadapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.expense_entry, ecursor, efrom, eto);
eadapter.notifyDataSetChanged();
lv.setAdapter(eadapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
incomeID_tv = (TextView) view.findViewById(R.id.income_id);
incomeAmount_tv = (TextView) view.findViewById(R.id.income_amount);
incomePayer_tv = (TextView) view.findViewById(R.id.income_payer);
incomeDate_tv = (TextView) view.findViewById(R.id.income_date);
incomeCategory_tv = (TextView) view.findViewById(R.id.income_category);
incomePayments_tv = (TextView) view.findViewById(R.id.income_payments);
String incomeID = incomeID_tv.getText().toString();
String incomeAmount = incomeAmount_tv.getText().toString();
String incomePayer = incomePayer_tv.getText().toString();
String incomeDate = incomeDate_tv.getText().toString();
String incomeCategory = incomeCategory_tv.getText().toString();
String incomePayments = incomePayments_tv.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(),
IncomeEdit.class);
modify_intent.putExtra("incomeID", incomeID);
modify_intent.putExtra("newIncomeAmount", incomeAmount);
modify_intent.putExtra("newIncomePayer", incomePayer);
modify_intent.putExtra("newIncomeDate", incomeDate);
modify_intent.putExtra("newIncomeCategory", incomeCategory);
modify_intent.putExtra("newIncomePayments", incomePayments);
startActivity(modify_intent);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
expenseID_tv = (TextView) view.findViewById(R.id.expense_id);
expenseAmount_tv = (TextView) view.findViewById(R.id.expense_amount);
expensePayee_tv = (TextView) view.findViewById(R.id.expense_payee);
expenseDate_tv = (TextView) view.findViewById(R.id.expense_date);
expenseCategory_tv = (TextView) view.findViewById(R.id.expense_category);
expensePayments_tv = (TextView) view.findViewById(R.id.expense_payments);
String expenseID = expenseID_tv.getText().toString();
String expenseAmount = expenseAmount_tv.getText().toString();
String expensePayer = expensePayee_tv.getText().toString();
String expenseDate = expenseDate_tv.getText().toString();
String expenseCategory = expenseCategory_tv.getText().toString();
String expensePayments = expensePayments_tv.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(),
ExpenseEdit.class);
modify_intent.putExtra("expenseID", expenseID);
modify_intent.putExtra("newExpenseAmount", expenseAmount);
modify_intent.putExtra("newExpensePayee", expensePayer);
modify_intent.putExtra("newExpenseDate", expenseDate);
modify_intent.putExtra("newExpenseCategory", expenseCategory);
modify_intent.putExtra("newExpensePayments", expensePayments);
startActivity(modify_intent);
}
});
}
The problem is that it shows just the expenses. I think the problem is from the adapter, but I don't know how to include both of them in the same adapter. :)
set doesn't mean add. If you setAdapter it means the old one (if any) will be replaced. The same goes for the OnItemClickListener.
If the cursors had the same column names, you could combine them however they differ and the adapter has no means to distinguish between the data of the 2 cursors (expenses and incomes).
Furthermore each click listener has type-specific actions like putting specific intent extras. This just means that you want multiple adapters therefore multiple ListView's.
You need to make your table and app design more generic or continue using 2 ListViews.

android ListActivity onListItemClick to open data in another activity

Hey I have tried to make a ListActivity that show the internal saved data, there have been saved from another activity. And when I click on an item, it should open a new activity with the internal data, and then open the data.
Here is the first activity. there shall show the listview and when clicked on an item, the user should be send to second activity whith more details
public class ShowListActivity extends ListActivity {
private ArrayAdapter<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.holo_blue_bright);
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String product = ((TextView)v).getText().toString();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("product", product);
startActivity(i);
}
Here is the other activity there shall recived the data and open it.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
TextView showCloseRange = (TextView) findViewById(R.id.show_close_range);
TextView showToRight = (TextView) findViewById(R.id.show_to_right);
TextView showToCenterRight = (TextView) findViewById(R.id.show_to_center_right);
TextView showToCenter = (TextView) findViewById(R.id.show_to_center);
TextView showToCenterLeft = (TextView) findViewById(R.id.show_to_center_left);
TextView showToLeft = (TextView) findViewById(R.id.Show_to_left);
TextView showFT = (TextView) findViewById(R.id.show_ft);
TextView showTreRight = (TextView) findViewById(R.id.show_tre_right);
TextView showTreCenterRight = (TextView) findViewById(R.id.show_tre_center_right);
TextView showTreCenter = (TextView) findViewById(R.id.show_tre_center);
TextView showTreCenterLeft = (TextView) findViewById(R.id.show_tre_center_left);
TextView showTreLeft = (TextView) findViewById(R.id.show_tre_left);
TextView showAssist = (TextView) findViewById(R.id.show_assist);
TextView showSteals = (TextView) findViewById(R.id.show_steals);
TextView showFouls= (TextView) findViewById(R.id.show_fouls);
TextView showTotalPt = (TextView) findViewById(R.id.show_total_pt);
TextView showDataBlocks = (TextView) findViewById(R.id.show_data_blocks);
TextView showDataRebounds = (TextView) findViewById(R.id.show_data_rebounds);
TextView showDataTurnOcers = (TextView) findViewById(R.id.show_data_turn_overs);
TextView showDataPlayerTime = (TextView) findViewById(R.id.show_data_player_time);
TextView showNote = (TextView) findViewById(R.id.show_note);
String value = "";
FileInputStream fis;
Intent i = getIntent();
String product = i.getStringExtra("product");
ActionBar actionBar1 = getActionBar();
actionBar1.setTitle(product);
try {
fis = openFileInput(product);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
fis.close(); }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
showCloseRange.setText(strArray[0]);
showToRight.setText(strArray[1]);
showToCenterRight.setText(strArray[2]);
showToCenter.setText(strArray[3]);
showToCenterLeft.setText(strArray[4]);
showToLeft.setText(strArray[5]);
showFT.setText(strArray[6]);
showTreRight.setText(strArray[7]);
showTreCenterRight.setText(strArray[8]);
showTreCenter.setText(strArray[9]);
showTreCenterLeft.setText(strArray[10]);
showTreLeft.setText(strArray[11]);
showDataPlayerTime.setText(strArray[12]);
showTotalPt.setText(strArray[13]);
showAssist.setText(strArray[14]);
showSteals.setText(strArray[15]);
showDataBlocks.setText(strArray[16]);
showDataRebounds.setText(strArray[17]);
showDataTurnOcers.setText(strArray[18]);
showFouls.setText(strArray[19]);
showNote.setText(strArray[20]);
}
I have trouble with sending the data between the activies and open it, so it will split up in my many differents textviews.
Any ideas ?
And sorry for my bad English
Try this way,hope this will help you to solve your problem.
Instead of geting product from ListView item TextView just declare your ArrayList object outside oncreate() and try to get your particular product using position from list in ListView item click listener.
public class ShowListActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.holo_blue_bright);
list = Arrays.asList(getApplicationContext().fileList());
setListAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1, list));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, MainActivity.class);
i.putExtra("product", list.get(position));
startActivity(i);
}
}
You can check what you are sending to second activity, mean using System.out.println() you can check on logcat . Also i done small change in your code please try this.
private ArrayAdapter<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.holo_blue_bright);
String[] filenames = getApplicationContext().fileList();
ArrayList<String> arrlist = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
arrlist.add(filenames[i]);
}
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, arrlist ));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String product = arrlist.get(position);
//Here you can check what yo are sending to second activity using System.out.println
System.out.println("click product is : "+product);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("product", product);
startActivity(i);
finish();
}
Ans also in other activity mean second activity you can add System.out.println to check list item value is coming or not.
String product = getIntent().getStringExtra("product");
System.out.println("product in second activity : "+product);

Android:Inserting 1 value to Checkbox, but it's shows 2 values?

I just want to ask something about showing data to checkbox, right now, I just have successful to showing data into checbox but, now I get trouble, when I have 1 data in my database, the checkbox show 2 data? here's my example database
Table Jurusan
id | nama
1 ipa
then I have function to read this database
public ArrayList<Jurusan> getAllLabel_jurusan()
{
ArrayList <Jurusan> point = new ArrayList<Jurusan>();
String selectQuery = "SELECT id, nama_jurusan from jurusan";
Cursor c = database.rawQuery(selectQuery, null);
if( c.moveToFirst() );
do
{
Jurusan j = new Jurusan();
j.setId(c.getLong(0));
j.setNama_jurusan(c.getString(1));
// adding to todo list
point.add(j);
}
while(c.moveToNext());
return point;
}
and this is my MainActivity
public class MainActivity extends Activity implements OnItemSelectedListener
{
Button myButton;
String tmp_nama;
long id_tampung;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button) findViewById(R.id.findSelected);
displayListView();
checkButtonClick();
}
private void displayListView()
{
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
//GETTING THE DATA FROM DATABASE
id_tampung = stateList.get(0).getId();
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
stateList.add(_states);
// create an ArrayAdaptar from the String Array
//SETTING INTO CustomAdapter
dataAdapter = new MyCustomAdapter(this, R.layout.state_info,stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
private class MyCustomAdapter extends ArrayAdapter<Jurusan>
{
private ArrayList<Jurusan> stateList;
public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<Jurusan> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<Jurusan>();
this.stateList.addAll(stateList);
}
private class ViewHolder
{
TextView id;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.state_info, null);
holder = new ViewHolder();
holder.id = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Jurusan state = stateList.get(position);
holder.id.setText(" (" + state.getId() + ")");
holder.name.setText(state.getNama_jurusan());
holder.name.setTag(state);
return convertView;
}
}
My question is, the checkbox should showing 1 data from database, but when i run this code, the checkbox is showing 2 data with same value, can anybody help me?
example:
checbox1 (value:ipa)
checkbox2 (value:ipa)
i hope it should be like this...
checkbox1 (value:ipa)
In your displayListView(), you're duplicating the first entry in the stateList:
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
if(stateList.size()>0)
{
//GETTING THE DATA FROM DATABASE
id_tampung = stateList.get(0).getId();
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
stateList.add(_states);
}
I don't know what your intention here is but you probably could just remove this if block altogether.
The problem is in your code, you are add double values in your code. i added my comment before line of code.
//statelist contains an arraylist with your required data.
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
//you are checking here for zero.
if(stateList.size()>0)
{
//GETTING THE DATA FROM DATABASE
//here you are get id;
id_tampung = stateList.get(0).getId();
//here you are get name;
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
//making an object of jurusan
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
// and adding again the same arraylist. so that cause duplication.
//stateList already contained the data , which are you add this line.
stateList.add(_states);
}
yes , please replace the function displayListView as below.
private void displayListView()
{
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
/*
//GETTING THE DATA FROM DATABASE
id_tampung = stateList.get(0).getId();
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
stateList.add(_states);*/
// create an ArrayAdaptar from the String Array
//SETTING INTO CustomAdapter
dataAdapter = new MyCustomAdapter(this, R.layout.state_info,stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}

findViewById returns null. BUT WHY?

I have an Adroid Activity and I want to introduce a custom list view. This is my onCreate() activity method.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadListView();
ListView lvw = (ListView)findViewById(android.R.id.list);
lvw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String element = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), AddEntryActivity.class);
// sending data to new activity
i.putExtra("entryToEdit", element);
long idToEdit = Long.parseLong(hEntries.get(position).toString());
i.putExtra("idToEdit", idToEdit);
startActivity(i);
}
});
DbAccess oDb = new DbAccess(this);
}
As you can see LoadListView() method is called to load listview items:
private void LoadListView()
{
oDb = new DbAccess(this);
oDb.open();
List<cAttivita> entries = oDb.getAttivita();
CustomListAdapter listAdapter = new CustomListAdapter(MainActivity.this, android.R.layout.simple_list_item_1 , entries);
ListView lvwAttivita = (ListView)findViewById(android.R.id.list);
lvwAttivita.setAdapter(listAdapter);
hEntries = new HashMap();
for(int i = 0; i < entries.size(); i++)
{
hEntries.put(i, entries.get(i).getId());
}
}
CustomListAdapter class:
public CustomListAdapter(Context context, int textViewResourceId , List<cAttivita> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.WHITE);
text.setText(items.get(position).toString());
text.setBackgroundColor(Color.RED);
int color = Color.argb( 200, 255, 64, 64 );
text.setBackgroundColor( color );
}
return mView;
}
This is activity_main.xml code:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="20px"
android:paddingTop="10dip"
android:paddingBottom="10dip"/>
<ListView xmlns:android="schemas.android.com/apk/res/android";
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Attività"/>
The problem is in the line:
TextView text = (TextView) mView.findViewById(R.id.textView);
Why text returns null?
Change the following line of code inside your getView() of your CustomAdapter.
TextView text = (TextView) mView.findViewById(android.R.id.text1);
as you are taking android.R.layout.simple_list_item_1 as layout it should be android.R.id.text1 which is declared internally in Android library.
Change my line of code inside getView() and it works for you.

Categories

Resources