ImageView crashes my android application on Samsung Galaxy S5 - java

I'm here to ask you a question as a newbie in android developing. Right now I'm trying to follow a tutorial which teaches the basics of android developing in Android Studio, but I encountered an issue with my Samsung Galaxy S5.
What I'm trying to do is to import an image from the gallery and put it into an ImageView but when I try to start the application I get a crash error. I know that many people had this issue and I downloaded the samsung SDK, but I don't know what and how to use for this problem. (Sorry, but I started all this yesterday and I can't find anything that can help me...)
The code is here:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}">
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tabHost"
android:layout_alignParentTop="false">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/tabCreator"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Contatto"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imgContact"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:src="#drawable/no_user_logo"
android:clickable="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/txtName"
android:textAllCaps="false"
android:hint="Nome"
android:layout_marginTop="10dp" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/txtNumber"
android:hint="Numero di Telefono"
android:layout_marginTop="10dp"
android:layout_below="#id/txtName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/txtMail"
android:layout_marginTop="10dp"
android:hint="Email" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aggiungi Contatto"
android:id="#+id/btnAdd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:enabled="false"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Contatti"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/banana"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
EditText txtName, txtPhone, txtEmail;
List<Contact> lstContacts = new ArrayList<Contact>();
ListView lstViewContact;
ImageView img = (ImageView)findViewById(R.id.imgContact);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (EditText) findViewById(R.id.txtName);
txtPhone = (EditText) findViewById(R.id.txtNumber);
txtEmail = (EditText) findViewById(R.id.txtMail);
lstViewContact = (ListView)findViewById(R.id.banana);
final Button btn = (Button) findViewById(R.id.btnAdd);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addContact(txtName.getText().toString().trim(), txtPhone.getText().toString(), txtEmail.getText().toString());
Toast.makeText(getApplicationContext(), "Banana", Toast.LENGTH_SHORT).show();
}
});
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
txtName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
boolean goName = false, goPhone = false;
if(txtName.length() > 0) goName = txtName.getText().toString().trim().length() > 0;
if(txtPhone.length() > 0) goPhone = txtPhone.getText().toString().trim().length() > 0;
btn.setEnabled(goName && goPhone);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
txtPhone.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
boolean goName = false, goPhone = false;
if(txtName.length() > 0) goName = txtName.getText().toString().trim().length() > 0;
if(txtPhone.length() > 0) goPhone = txtPhone.getText().toString().trim().length() > 0;
btn.setEnabled(goName && goPhone);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("list");
tabSpec.setContent(R.id.tabList);
tabSpec.setIndicator("List");
tabHost.addTab(tabSpec);
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1) img.setImageURI(data.getData());
}
}
private class lstContactsAdapter extends ArrayAdapter<Contact> {
public lstContactsAdapter() {
super(MainActivity.this, R.layout.listview_item, lstContacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
//Se la view non esiste io la metto come listview_item all'interno della lista alla fine (non al root)
if(view == null) view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = lstContacts.get(position);
TextView name = (TextView)view.findViewById(R.id.contactName);
TextView phone = (TextView)view.findViewById(R.id.contactPhone);
TextView mail = (TextView)view.findViewById(R.id.contactMail);
name.setText(currentContact.getName());
phone.setText(currentContact.getPhone());
mail.setText(currentContact.getEmail());
return view;
}
}
private void addContact(String name, String phone, String email) {
lstContacts.add(new Contact(name, phone, email));
ArrayAdapter<Contact> adapter = new lstContactsAdapter();
lstViewContact.setAdapter(adapter);
}
}
I'm so sorry for asking this without a proper knowledge, but I hope you'll understand and help me. Thank you for reading and sorry for any grammatical error I did.

In your class, in place of this
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1) img.setImageURI(data.getData());
}
}
put this,
#Override
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1 && data.getData() != null)
img.setImageURI(data.getData());
}
super.onActivityResult(reqCode, resCode, data);
}
You should always call super class method to ensure default behaviour with your own. Also, #Override annotation makes sure that onActivityResult is called as a callback. Lastly, data.getData() != null ensures that you don't get a NPE.

Related

how to add voice search in search view

I've Created search view in my app and now i want to add voice search on that how i do that
enter image description here
this is the image
in this search view is available i want to add voice search in it
This is code for Activity_main.xml in it search view is created now want to add voice search in which the result of voice search have to display on search box
activity_main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:padding="10dp"
android:fontFamily="#font/custom_font"
android:text="#string/app_name"
android:textColor="#android:color/background_dark"
android:textSize="30dp" />
<android.support.v7.widget.SearchView
android:id="#+id/search_view"
android:layout_width="302dp"
android:layout_height="wrap_content"
android:layout_margin="12.1dp"
android:background="#drawable/search_view_design"
android:clickable="true"
android:contextClickable="true"
android:focusable="true"
android:inputType="text"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
app:queryHint="Type Word..">
</android.support.v7.widget.SearchView>
</LinearLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/empty_history"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="150dp"
android:visibility="visible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search History Here.."
android:textAlignment="center"
android:textColor="#313131"
android:textSize="22sp"
android:layout_gravity="center_horizontal" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_history"
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
MainActicity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolBar = findViewById(R.id.toolBar);
setSupportActionBar(toolBar);
textView = findViewById(R.id.textView);
searchView = findViewById(R.id.search_view);
searchView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchView.onActionViewExpanded();
}
});
mdatabase = new Databasehelper(this);
if(mdatabase.checkDatabase())
{
openDatabase();
}
else
{
LoadDatabase ld = new LoadDatabase(this);
ld.execute();
}
final String[] from = new String[] {"en_word"};
final int[] to = new int[]{R.id.suggestion_text};
suggestionadapter = new SimpleCursorAdapter(MainActivity.this,
R.layout.suggestion_row,null,from,to,0)
{
#Override
public void changeCursor(Cursor cursor) {
super.swapCursor(cursor);
}
};
searchView.setSuggestionsAdapter(suggestionadapter);
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener(){
#Override
public boolean onSuggestionSelect(int i) {
return true;
}
#Override
public boolean onSuggestionClick(int i) {
CursorAdapter ca = searchView.getSuggestionsAdapter();
Cursor cursor = ca.getCursor();
cursor.moveToPosition(i);
String clicked_word = cursor.getString(cursor.getColumnIndex("en_word"));
searchView.setQuery(clicked_word,false);
searchView.clearFocus();
searchView.setFocusable(false);
Intent intent = new Intent(MainActivity.this,Word_meaningActivity.class);
Bundle bundle = new Bundle();
bundle.putString("en_word",clicked_word);
intent.putExtras(bundle);
startActivity(intent);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
String text = searchView.getQuery().toString().replaceAll("\\s+","");
Pattern P = Pattern.compile("[A-Za-z \\-.]{1,25}");
Matcher m = P.matcher(text);
if(m.matches()) {
Cursor c = mdatabase.getmeaning(text);
if (c.getCount() == 0) {
showDialog();
} else {
searchView.clearFocus();
searchView.setFocusable(false);
Intent intent = new Intent(MainActivity.this, Word_meaningActivity.class);
Bundle bundle = new Bundle();
bundle.putString("en_word", text);
intent.putExtras(bundle);
startActivity(intent);
}
}
else{
showDialog();
}
return false;
}
can Anyone help me in that
**Edit: Dont forget the permission: Manifest.permission.RECORD_AUDIO
You can create an Speech intent to capture the voice and then recall the speech back via onActivityResult
Create an intent
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to search");
try {
startActivityForResult(intent, 123456);
} catch (ActivityNotFoundException a) {
//show toast?
}
}
And then within the onActivityResult, capture the speech and pass it to your search.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 123456: {
if (resultCode == RESULT_OK && data != null) {
ArrayList result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
textView.setText(result.get(0));
}
break;
}
}
}
The android documentation can be found here: https://developer.android.com/reference/android/speech/SpeechRecognizer

I cant get all the data from firebase to my Listview

I couldnt able to display my data from firebase to my listview in android application. Rather it only shows one data.
Heres the current data of my database:
Database
And this is my java:
public class scheduleList extends ArrayAdapter<Schedule> {
private Activity context;
private List<Schedule> scheduleList;
public scheduleList(Activity context, List<Schedule> scheduleList){
super(context, R.layout.listlayout, scheduleList);
this.context=context;
this.scheduleList=scheduleList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listviewItem = inflater.inflate(R.layout.listlayout, null, true);
TextView textViewName = (TextView) listviewItem.findViewById(R.id.textViewName);
TextView textViewSchedule = (TextView) listviewItem.findViewById(R.id.textViewSchedule);
Schedule schedule = scheduleList.get(position);
textViewName.setText(schedule.getAppointer());
textViewSchedule.setText(schedule.getAppointment_schedule());
return listviewItem;
}}
My java file:
public class Appointment extends AppCompatActivity {
CalendarView calendarView;
TextView myDate;
private Button btn1;
ListView listViewSchedule;
List<Schedule> scheduleList;
DatabaseReference databaseAppointments;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appointment);
databaseAppointments = FirebaseDatabase.getInstance().getReference("appointment");
calendarView = (CalendarView) findViewById(R.id.calendarView);
myDate = (TextView) findViewById(R.id.myDate);
listViewSchedule=(ListView) findViewById(R.id.listViewSchedule);
scheduleList = new ArrayList<>();
btn1 = (Button) findViewById(R.id.appt);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(Appointment.this, appointments2.class);
Appointment.this.startActivity(myIntent);
}
});
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int i, int i1, int i2) {
String date = (i1 + 1) + "/" + i2 + "/" + i;
myDate.setText(date);
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseAppointments.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
scheduleList.clear();
for(DataSnapshot scheduleSnapshot: dataSnapshot.getChildren()){
Schedule schedule = scheduleSnapshot.getValue(Schedule.class);
scheduleList.add(schedule);
}
scheduleList adapter = new scheduleList(Appointment.this, scheduleList);
listViewSchedule.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
and lastly my xml file containing the listview:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.cs409.instappoint.Appointment">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/myDate"
android:textSize="23sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select the date"
android:textColor="#ee912a"
android:textAlignment="center"
android:layout_marginStart="125dp"
android:layout_marginTop="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="380dp"
android:layout_marginStart="10dp"
android:layout_gravity="center"
android:layout_height="wrap_content">
<CalendarView
android:id="#+id/calendarView"
android:layout_width="wrap_content"
android:layout_height="320dp">
</CalendarView>
</LinearLayout>
<View
android:layout_width="500dp"
android:layout_height="1dp"
android:layout_gravity="center"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="0dp"
android:background="#ee912a" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Appointments"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"/>
<ListView
android:id="#+id/listViewSchedule"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/appt"
android:layout_width="450dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginEnd="120dp"
android:layout_marginStart="120dp"
android:layout_marginTop="130dp"
android:background="#drawable/bg_calen"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="Appoint now"
android:textColor="#fff" />
</LinearLayout>
Im guessing that the scrollview layout affects the listview but im not sure. Also the listview display whatevers the first on the list.
use FirebaseRecyclerAdapter. search example of how to use FirebaseRecylerAdapter with example.

Application getting Unfortunately stopped when my edittext field make null

I am confused what might be the reason behind this error.While making my edittext field null after entering a digit into it my application is getting crashed.can you find a solution for this situation ??
here is my code
java file
public class CSLActivity extends AppCompatActivity {
private Common mApp;
private AutoCompleteTextView clgName, conCent, loc;
private MultiAutoCompleteTextView skill;
private String[] qulify = new String[]{"Select Highest Qualification", "PG", "UG", "DIPLOMA"};
public String abc, abcd;
public ScrollView scrollView;
public ProgressBar progressBar;
private String q;
private Spinner level;
private int ab = 1990;
public EditText fullName, frm_yr, to_yr;
private boolean ins = false;
private boolean cIns = false;
private Button next;
private TextfieldValidator textfieldValidator;
private AlphabetValidator alphabetValidator;
private int i = 0, j = 0;
private boolean exit = false;
private String get;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_csl);
scrollView = (ScrollView) findViewById(R.id.scroll_view);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
fullName = (EditText) findViewById(R.id.fullName);
level = (Spinner) findViewById(R.id.level);
clgName = (AutoCompleteTextView) findViewById(R.id.clg_name);
conCent = (AutoCompleteTextView) findViewById(R.id.concent);
frm_yr = (EditText) findViewById(R.id.frm_yr);
to_yr = (EditText) findViewById(R.id.to_yr);
skill = (MultiAutoCompleteTextView) findViewById(R.id.skill);
loc = (AutoCompleteTextView) findViewById(R.id.location);
textfieldValidator = new TextfieldValidator();
alphabetValidator = new AlphabetValidator();
next = (Button) findViewById(R.id.next);
frm_yr.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//abc = frm_yr.getText().toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
//i = Integer.parseInt(frm_yr.getText().toString());
//i = Integer.parseInt(abc.toString());
i = Integer.parseInt(frm_yr.getText().toString());
}
});
to_yr.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
//j = Integer.parseInt(to_yr.getText().toString());
//j = Integer.parseInt(abcd.toString());
j = Integer.parseInt(to_yr.getText().toString());
}
});
new GetCollege(CSLActivity.this, progressBar, scrollView, clgName).execute();
new GetCourse(CSLActivity.this, conCent).execute();
new GetSkillSet(CSLActivity.this, scrollView, progressBar, skill).execute();
new GetLocation(CSLActivity.this, scrollView, loc, progressBar).execute();
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, qulify);
level.setAdapter(adapter1);
level.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
get = level.getSelectedItem().toString();
if (get.equalsIgnoreCase("PG")) {
q = "1";
} else if (get.equalsIgnoreCase("UG")) {
q = "2";
} else {
q = "3";
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
clgName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.ins_name);
clgName.setText(txt.getText().toString());
conCent.requestFocus();
ins = true;
}
});
conCent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.display);
conCent.setText(txt.getText().toString());
cIns = true;
frm_yr.requestFocus();
}
});
loc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
loc.setText(txt1.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromInputMethod(view.getWindowToken(), 0);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
if (fullName.getText().toString().length() == 0) {
fullName.setError("Field Mandatory");
fullName.requestFocus();
} else if (!alphabetValidator.validate(fullName.getText().toString())) {
fullName.setError("Enter a Valid Name");
fullName.requestFocus();
} else if (get.equalsIgnoreCase("Select Highest Qualification")) {
level.requestFocus();
Toast.makeText(getApplicationContext(), "select Qualification", Toast.LENGTH_SHORT).show();
} else if (clgName.getText().toString().length() == 0) {
clgName.setError("Field Mandatory");
clgName.requestFocus();
} else if (conCent.getText().toString().length() == 0) {
conCent.setError("Field Mandatory");
conCent.requestFocus();
} else if (frm_yr.getText().toString().length() == 0) {
frm_yr.setError("Field Mandatory");
frm_yr.requestFocus();
} else if (to_yr.getText().toString().length() == 0) {
to_yr.setError("Field Mandatory");
to_yr.requestFocus();
} else if (i > j) {
to_yr.setError("Passed out year less than join year");
to_yr.requestFocus();
} else if (i == j) {
to_yr.setError("Check the year entered");
to_yr.requestFocus();
} else if (i <= ab) {
frm_yr.setError("Enter a valid Year");
frm_yr.requestFocus();
} else if (j <= ab) {
to_yr.setError("Enter a valid Year");
to_yr.requestFocus();
} else if (skill.getText().toString().length() == 0) {
skill.setError("Field Mandatory");
skill.requestFocus();
} else if (!textfieldValidator.validate(skill.getText().toString())) {
skill.setError("Enter a Valid Skill");
skill.requestFocus();
} else if (loc.getText().toString().length() == 0) {
loc.setError("Field Mandatory");
loc.requestFocus();
} else if (!textfieldValidator.validate(loc.getText().toString())) {
loc.setError("Enter a Valid Location");
} else {
next.setEnabled(false);
new CslIns(CSLActivity.this, mApp.getPreference().getString(Common.u_id, ""), fullName.getText().toString(), q,
clgName.getText().toString(), conCent.getText().toString(), frm_yr.getText().toString(), to_yr.getText().toString(),
skill.getText().toString(), loc.getText().toString(), ins, cIns).execute();
/*startActivity(new Intent(getApplicationContext(), MailVerify.class));
finish();*/
}
break;
}
}
});
}
#Override
public void onBackPressed() {
if (exit) {
mApp.getPreference().edit().putBoolean(Common.PAGE1, false).commit();
super.onBackPressed();
return;
} else {
Toast.makeText(this, "Press Back again to Cancel Signup Process.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2000);
}
}
}
my xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.shuan.Project.signup.employee.CSLActivity">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/activity_horizontal_margin"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/fullName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin"
android:hint="Full Name"
android:imeOptions="actionNext"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<Spinner
android:id="#+id/level"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/clg_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/clg_name"
android:imeOptions="actionNext" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/concent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/concent"
android:imeOptions="actionNext"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:id="#+id/yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Joined"
android:textColor="#000"
android:textStyle="bold" />
<EditText
android:id="#+id/frm_yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/small_margin"
android:hint="Year"
android:imeOptions="actionNext"
android:inputType="numberDecimal"
android:maxLength="4"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Passed :"
android:textColor="#000"
android:textStyle="bold" />
<EditText
android:id="#+id/to_yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/small_margin"
android:hint="Year"
android:imeOptions="actionNext"
android:inputType="numberDecimal"
android:maxLength="4"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/layout_skill"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<MultiAutoCompleteTextView
android:id="#+id/skill"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Skills"
android:imeOptions="actionNext"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/layout_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/location"
android:imeOptions="actionDone"
android:inputType="textAutoComplete" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/next"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:background="#drawable/signin_border"
android:text="START"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
log cat
FATAL EXCEPTION: main
Process: com.shuan.Project, PID: 1432
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.shuan.Project.signup.employee.CSLActivity$1.afterTextChanged(CSLActivity.java:95)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7998)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:9814)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:990)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:529)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:224)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:38)
at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:252)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:389)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5649)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Try this code
public void afterTextChanged(Editable s) {
if(to_yr.getText().toString().length != 0){
j =Integer.parseInt(to_yr.getText().toString());
}
}
it works fine for me
At a first look, to me it seems to block on onAfterTextChanged, because is trying to parse an int from a String which is empty, so it just throws the error.
Try to verify if the EditText is "" before of parsing the integer, if it is not "" or null do as your code, if it's "" or null give it a default value, like 0 or what you want.
This crash is because of your code in afterTextChanged callback.
You should check if to_yr.getText is having some valid value before parsing it to the integer. Do not parse empty string.
Use below code:
public void afterTextChanged(Editable s) {
if(!TextUtils.isEmpty(to_yr.getText()){
j = Integer.parseInt(to_yr.getText().toString());
}
}
This is happening because you parse the empty string and the Integer class throws exception named:
Invalid int
java.lang.NumberFormatException
Do the check before parsing integer. For example
String s;
if(s != null && (!s.isEmpty())){
Integer i = s.ParseInt();
}

List View doesn't appear

I try to show a Listview to show my data
This is main_fragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
ListView contactListView;
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) view.findViewById(R.id.txtName);
emailTxt = (EditText) view.findViewById(R.id.txtEmail);
phoneTxt = (EditText) view.findViewById(R.id.txtPhone);
addressTxt = (EditText) view.findViewById(R.id.txtAddress);
contactListView = (ListView) view.findViewById(R.id.listView);
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
if (contactAdapter != null) contactAdapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
final Button addContact = (Button) view.findViewById(R.id.btnadd);
nametxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addContact.setEnabled(!nametxt.getText().toString().trim().equals(""));
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
ArrayAdapter<import_fragment.Contact> contactAdapter;
ListView contactListView;
DatabaseHandler dbHandler;
int longClickedItemIndex;
public void onActivityResult(int reqCode, int resCode, Intent data) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
ImageView contactImageImgView;
contactImageImgView = (ImageView) getActivity().findViewById(R.id.ivContactImage);
if (resCode == Activity.RESULT_OK) {
if (reqCode == 1) {
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
{
ImageView contactImageImgView;
contactImageImgView = (ImageView) view.findViewById(R.id.ivContactImage);
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
if (dbHandler.getContactsCount() != 0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Contact Options");
menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Contact");
menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Contact");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO: Implement editing a contact
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(import_fragment.Contact contact) {
String name = contact.getName();
int contactCount = Contacts.size();
for (int i = 0; i < contactCount; i++) {
if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
return true;
}
return false;
}
private void populateList() {
contactAdapter = new ContactListAdapter(getActivity());
contactListView.setAdapter(contactAdapter);
}
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
private class ContactListAdapter extends ArrayAdapter<import_fragment.Contact> {
public ContactListAdapter(Context cntx) {
super (cntx, R.layout.fragment_import, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.fragment_import, parent, false);
import_fragment.Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
return view;
}
}
This is import_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="#+id/ivContactImage" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="91dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Contact Name"
android:id="#+id/contactName"
android:layout_gravity="left|center_vertical"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:id="#+id/phoneNumber"
android:layout_gravity="left|center_vertical"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:id="#+id/emailAddress"
android:layout_gravity="left|center_vertical"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:id="#+id/cAddress"
android:layout_gravity="left|center_vertical"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="My Contacts"
android:id="#+id/textView"
android:layout_gravity="center"
android:layout_marginTop="10dp"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView"
android:layout_gravity="center"/>
</LinearLayout>
My listview in import_fragment.xml, when i open import_fragment.xml in app its appear only Contact Name and Phone and Email and Address which is added in import_fragment.xml and not the new contact information which in database added by user.
You have to setAdapter in onCreateView. Currently you are populating the list in onCreateContextMenu. Moreover, after setting the adapter, you have to call notifyDataSetChanged() as well
Try this way, i have tried this in my machine and it show me listview properly , i have done with weightSum so it will be applicable for all devices , just change your xml file with below one
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4">
<ImageView
android:id="#+id/ivContactImage"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="vertical">
<TextView
android:id="#+id/contactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Contact Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginTop="5dp"
android:text="Phone" />
<TextView
android:id="#+id/emailAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Email" />
<TextView
android:id="#+id/cAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Address" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="My Contacts"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</LinearLayout>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
Change both of your LinearLayout's height to
android:layout_height="fill_parent"
Your listView is actually "there", it's just that the container (layout) of the listView isn't big enough to fit it.
EDIT:
You are defining two different list of Contacts there! Both activity and adapter class are referring to two different Contacts. Remove the one inside the onCreateView function.
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();

Adding Custom Header to List Fragment in Android

I am trying to add a custom header that isnt clickable but will have a checkbox that will "check all" checkboxes under it.
This is my List Fragment
public class AssesmentListFragment extends ListFragment {
private static String BUNDLE_KEY_APPLICATION = "LIST_ITEM";
FastAssesmentListAdapter adapter;
View listHeader;
public AssesmentListFragment() {}
public AssesmentListFragment(Data[] data) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Data[] assestments = {new Data("Assesment ID","Name", "Date"), new Data("123456", "Assestment 2", "9/12/12"),
new Data("345672", "Assesment 3", "9/13/12"), new Data("566893", "Assesment 4", "9/14/12")};
//This is the part that makes the app crash
View header = getActivity().getLayoutInflater().inflate(R.layout.list_adapter_assesments, null);
ListView listView = getListView();
listView.addHeaderView(header);
adapter = new FastAssesmentListAdapter(getActivity(), assestments);
setListAdapter(adapter);
updateList(assestments);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void updateList(Data[] assestments) {
// NOTE: addAll is not being used to support pre-honeycomb devices
synchronized(adapter) {
adapter.clear();
adapter.addAll(assestments);
adapter.notifyDataSetChanged();
}
}
#Override
public void onListItemClick(ListView parentView, View selectedItemView, int position, long id) {
String model = (String) parentView.getItemAtPosition(position);
((FacilityActivity) getActivity()).onItemSelected(model);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putInt("curChoice", mCurCheckPosition);
}
}
This is the layout I am trying to use for header
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_header_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Assesment ID" />
<TextView android:id="#+id/adapter_header_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Name" />
<TextView android:id="#+id/adapter_header_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Date"/>
<CheckBox
android:id="#+id/header_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:color="#color/defaultTextColor"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#color/BPGreenColor" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Then this is the array adapter I am using:
public class FastAssesmentListAdapter extends ArrayAdapter<Data> {
private static int LAYOUT_ID = R.layout.list_adapter_with_checkbox_three_column;
private final Data[] assesments;
private final Context context;
LinearLayout listHeader;
static class ViewHolder {
protected TextView column1;
protected TextView column2;
protected TextView column3;
protected CheckBox checkbox;
}
public FastAssesmentListAdapter(Context context, Data[] assesments) {
super(context, LAYOUT_ID, assesments);
this.context = context;
this.assesments = assesments;
}
//ListFragment and array adapter will automatically call this over and over to auto populate the list
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Data item = getItem(position);
// Formulate row view (create if it does not exist yet)
View view = convertView;
if(view == null) {
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
view = inflater.inflate(LAYOUT_ID, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.column1 = (TextView) view.findViewById(R.id.adapter_textview_column1);
viewHolder.column2 = (TextView) view.findViewById(R.id.adapter_textview_column2);
viewHolder.column3 = (TextView) view.findViewById(R.id.adapter_textview_column3);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check_box);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), FacilityActivity.class);
getContext().startActivity(intent);
}
});
if(viewHolder.checkbox != null) {
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
item.setSelected(isChecked);
Toast.makeText(getContext(), "Checked",
Toast.LENGTH_SHORT).show();
}
}
});
}
view.setTag(viewHolder);
viewHolder.checkbox.setTag(position);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.checkbox.setTag(position);
viewHolder.column1.setText(item.getColumn1());
viewHolder.column2.setText(item.getColumn2());
viewHolder.column3.setText(item.getColumn3());
viewHolder.checkbox.setChecked(item.isSelected());
return view;
}
}
on a side note, the onlistitemclicked in the fragment doesnt work, i have to set a listener in the adapter and then it works. any ideas on that? but mainly I need to figure out how to use a custom header and custom rows in the list view. Here is the layout for the rows
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>

Categories

Resources